Merge
authorlana
Thu, 16 Mar 2017 20:47:03 +0000
changeset 44227 9379643900c6
parent 44226 815831f585ee (current diff)
parent 44225 81102185f6fe (diff)
child 44228 e46434c65a2b
Merge
hotspot/test/gc/arguments/TestExplicitGCInvokesConcurrentAndUnloadsClasses.java
hotspot/test/gc/startup_warnings/TestDefNewCMS.java
hotspot/test/gc/startup_warnings/TestParNewCMS.java
hotspot/test/gc/startup_warnings/TestParNewSerialOld.java
hotspot/test/gc/startup_warnings/TestUseAutoGCSelectPolicy.java
hotspot/test/runtime/NMT/AutoshutdownNMT.java
jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/xmltest5.out
jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/xmltest7.out
jaxws/.hgtags
jdk/make/src/classes/build/tools/jigsaw/Graph.java
jdk/src/java.base/macosx/native/launcher/jexec.c
jdk/src/java.base/share/classes/sun/security/provider/certpath/PKIXTimestampParameters.java
jdk/src/java.base/share/classes/sun/security/util/CertConstraintParameters.java
jdk/src/java.base/share/native/libzip/zlib-1.2.8/ChangeLog
jdk/src/java.base/share/native/libzip/zlib-1.2.8/README
jdk/src/java.base/share/native/libzip/zlib-1.2.8/compress.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/crc32.h
jdk/src/java.base/share/native/libzip/zlib-1.2.8/deflate.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/deflate.h
jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzclose.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzguts.h
jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzlib.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzread.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzwrite.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/infback.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/inffast.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/inffast.h
jdk/src/java.base/share/native/libzip/zlib-1.2.8/inffixed.h
jdk/src/java.base/share/native/libzip/zlib-1.2.8/inflate.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/inflate.h
jdk/src/java.base/share/native/libzip/zlib-1.2.8/inftrees.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/inftrees.h
jdk/src/java.base/share/native/libzip/zlib-1.2.8/patches/ChangeLog_java
jdk/src/java.base/share/native/libzip/zlib-1.2.8/trees.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/trees.h
jdk/src/java.base/share/native/libzip/zlib-1.2.8/uncompr.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/zadler32.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/zconf.h
jdk/src/java.base/share/native/libzip/zlib-1.2.8/zcrc32.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/zlib.h
jdk/src/java.base/share/native/libzip/zlib-1.2.8/zutil.c
jdk/src/java.base/share/native/libzip/zlib-1.2.8/zutil.h
jdk/src/java.base/unix/classes/sun/nio/ch/DefaultAsynchronousChannelProvider.java
jdk/src/jdk.desktop/share/classes/jdk/awt/AWTUtils.java
jdk/src/jdk.desktop/share/classes/module-info.java
jdk/test/java/awt/jdk/TestJDKAWTUtils.java
jdk/test/java/lang/StackWalker/CountLocalSlots.java
jdk/test/java/lang/StackWalker/LocalsCrash.java
jdk/test/java/lang/invoke/lambda/MetafactorySamReturnTest.java
jdk/test/java/lang/invoke/modules/ModuleAccessControlTest.java
jdk/test/java/lang/invoke/modules/src/m1/module-info.java
jdk/test/java/lang/invoke/modules/src/m1/p1/Main.java
jdk/test/java/lang/invoke/modules/src/m1/p1/Type1.java
jdk/test/java/lang/invoke/modules/src/m1/p2/Type2.java
jdk/test/java/lang/invoke/modules/src/m2/module-info.java
jdk/test/java/lang/invoke/modules/src/m2/q1/Type1.java
jdk/test/java/lang/invoke/modules/src/m2/q2/Type2.java
jdk/test/java/util/stream/bootlib/java.base/java/util/stream/SpliteratorTestHelper.java
jdk/test/javax/xml/jaxp/common/8035437/Document.java
jdk/test/javax/xml/jaxp/common/8035437/DocumentImpl.java
jdk/test/javax/xml/jaxp/common/8035437/Node.java
jdk/test/sun/security/krb5/auto/BadKdc.java
jdk/test/sun/security/krb5/auto/BadKdc1.java
jdk/test/sun/security/krb5/auto/BadKdc2.java
jdk/test/sun/security/krb5/auto/BadKdc3.java
jdk/test/sun/security/krb5/auto/BadKdc4.java
jdk/test/sun/security/krb5/auto/CommMatcher.java
jdk/test/sun/security/krb5/auto/MaxRetries.java
jdk/test/sun/security/krb5/auto/TcpTimeout.java
jdk/test/sun/security/krb5/auto/UdpTcp.java
jdk/test/sun/text/IntHashtable/Bug4170614Test.java
langtools/test/tools/javac/6627362/x/Object.java
langtools/test/tools/javac/T4093617/java.base/Object.java
langtools/test/tools/javac/diags/examples/ModuleInfoWithXModuleSourcePath/Extra.java
langtools/test/tools/javac/diags/examples/ModuleInfoWithXModuleSourcePath/module-info.java
langtools/test/tools/javac/diags/examples/ModuleInfoWithXmoduleClasspath/ModuleInfoWithXmoduleClasspath.java
langtools/test/tools/javac/diags/examples/ModuleInfoWithXmoduleClasspath/additional/module-info.java
langtools/test/tools/javac/diags/examples/NoSuperclass.java
langtools/test/tools/javac/diags/examples/XModuleWithModulePath/XModuleWithModulePath.java
langtools/test/tools/javac/meth/BadPolySig.java
langtools/test/tools/javac/modules/XModuleTest.java
langtools/test/tools/javac/redefineObject/java.base/Object1.java
langtools/test/tools/javac/redefineObject/java.base/Object2.java
--- a/.hgtags	Thu Mar 16 16:34:35 2017 +0000
+++ b/.hgtags	Thu Mar 16 20:47:03 2017 +0000
@@ -1,3 +1,5 @@
+fa3e76b477829afc4476f0b725cfaa440a6fd917 jdk-9+157
+b5015f742ba648184bb7fc547197bd33ebfde30d jdk-9+158
 1cc8dd79fd1cd13d36b385196271a29632c67c3b jdk7-b24
 bf2517e15f0c0f950e5b3143c4ca11e2df73dcc1 jdk7-b25
 5ae7db536e3fcf6be78e45b240a9058095e0ed38 jdk7-b26
@@ -399,3 +401,5 @@
 8c70d170e62c0c58b5bc3ba666bd140399b98c9c jdk-10+0
 45b751afd11e6c05991cf4913c5a0ac3304fcc4e jdk-9+154
 f4aff695ffe05cfdb69d8af25a4ddc6a029754ea jdk-9+155
+06bce0388880b5ff8e040e4a9d72a3ea11dac321 jdk-9+156
+74116beae88a8f17a80301aa6c83865c82f10ece jdk-10+1
--- a/.hgtags-top-repo	Thu Mar 16 16:34:35 2017 +0000
+++ b/.hgtags-top-repo	Thu Mar 16 20:47:03 2017 +0000
@@ -396,5 +396,9 @@
 71a766d4c18041a7f833ee22823125b02e1a7f1e jdk-9+151
 ef056360ddf3977d7d2ddbeb456a4d612d19ea05 jdk-9+152
 816a6d03a7c44edfbd8780110529f1bdc3964fb9 jdk-9+153
+8d22611ffb6540bc1ace64a00c048c8b82d8c69a jdk-10+0
 8d26916eaa21b689835ffc1c0dbf12470aa9be61 jdk-9+154
 688a3863c00ebc089ab17ee1fc46272cbbd96815 jdk-9+155
+783ec7542cf7154e5d2b87f55bb97d28f81e9ada jdk-9+156
+4eb77fb98952dc477a4229575c81d2263a9ce711 jdk-9+157
+a4087bc10a88a43ea3ad0919b5b4af1c86977221 jdk-9+158
--- a/.jcheck/conf	Thu Mar 16 16:34:35 2017 +0000
+++ b/.jcheck/conf	Thu Mar 16 20:47:03 2017 +0000
@@ -1,1 +1,1 @@
-project=jdk9
+project=jdk10
--- a/common/autoconf/basics.m4	Thu Mar 16 16:34:35 2017 +0000
+++ b/common/autoconf/basics.m4	Thu Mar 16 20:47:03 2017 +0000
@@ -1202,6 +1202,18 @@
 # Check for support for specific options in bash
 AC_DEFUN_ONCE([BASIC_CHECK_BASH_OPTIONS],
 [
+  # Check bash version
+  # Extra [ ] to stop m4 mangling
+  [ BASH_VER=`$BASH --version | $SED -n  -e 's/^.*bash.*ersion *\([0-9.]*\).*$/\1/ p'` ]
+  AC_MSG_CHECKING([bash version])
+  AC_MSG_RESULT([$BASH_VER])
+
+  BASH_MAJOR=`$ECHO $BASH_VER | $CUT -d . -f 1`
+  BASH_MINOR=`$ECHO $BASH_VER | $CUT -d . -f 2`
+  if test $BASH_MAJOR -lt 3 || (test $BASH_MAJOR -eq 3 && test $BASH_MINOR -lt 2); then
+    AC_MSG_ERROR([bash version 3.2 or better is required])
+  fi
+
   # Test if bash supports pipefail.
   AC_MSG_CHECKING([if bash supports pipefail])
   if ${BASH} -c 'set -o pipefail'; then
--- a/common/autoconf/generated-configure.sh	Thu Mar 16 16:34:35 2017 +0000
+++ b/common/autoconf/generated-configure.sh	Thu Mar 16 20:47:03 2017 +0000
@@ -5170,7 +5170,7 @@
 #CUSTOM_AUTOCONF_INCLUDE
 
 # Do not change or remove the following line, it is needed for consistency checks:
-DATE_WHEN_GENERATED=1486175373
+DATE_WHEN_GENERATED=1486679715
 
 ###############################################################################
 #
@@ -24092,6 +24092,20 @@
   fi
 
 
+  # Check bash version
+  # Extra [ ] to stop m4 mangling
+   BASH_VER=`$BASH --version | $SED -n  -e 's/^.*bash.*ersion *\([0-9.]*\).*$/\1/ p'`
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking bash version" >&5
+$as_echo_n "checking bash version... " >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $BASH_VER" >&5
+$as_echo "$BASH_VER" >&6; }
+
+  BASH_MAJOR=`$ECHO $BASH_VER | $CUT -d . -f 1`
+  BASH_MINOR=`$ECHO $BASH_VER | $CUT -d . -f 2`
+  if test $BASH_MAJOR -lt 3 || (test $BASH_MAJOR -eq 3 && test $BASH_MINOR -lt 2); then
+    as_fn_error $? "bash version 3.2 or better is required" "$LINENO" 5
+  fi
+
   # Test if bash supports pipefail.
   { $as_echo "$as_me:${as_lineno-$LINENO}: checking if bash supports pipefail" >&5
 $as_echo_n "checking if bash supports pipefail... " >&6; }
--- a/common/autoconf/version-numbers	Thu Mar 16 16:34:35 2017 +0000
+++ b/common/autoconf/version-numbers	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2017, 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,7 +25,7 @@
 
 # Default version numbers to use unless overridden by configure
 
-DEFAULT_VERSION_MAJOR=9
+DEFAULT_VERSION_MAJOR=10
 DEFAULT_VERSION_MINOR=0
 DEFAULT_VERSION_SECURITY=0
 DEFAULT_VERSION_PATCH=0
--- a/common/bin/unshuffle_list.txt	Thu Mar 16 16:34:35 2017 +0000
+++ b/common/bin/unshuffle_list.txt	Thu Mar 16 20:47:03 2017 +0000
@@ -361,8 +361,8 @@
 jdk/src/java.base/share/native/libverify/check_format.c : jdk/src/share/native/common/check_format.c
 jdk/src/java.base/share/native/libverify/opcodes.in_out : jdk/src/share/native/common/opcodes.in_out
 jdk/src/java.base/share/native/libzip : jdk/src/share/native/java/util/zip
-jdk/src/java.base/share/native/libzip/zlib-1.2.8 : jdk/src/share/native/java/util/zip/zlib-1.2.8
-jdk/src/java.base/share/native/libzip/zlib-1.2.8/patches/ChangeLog_java : jdk/src/share/native/java/util/zip/zlib-1.2.8/patches/ChangeLog_java
+jdk/src/java.base/share/native/libzip/zlib : jdk/src/share/native/java/util/zip/zlib
+jdk/src/java.base/share/native/libzip/zlib/patches/ChangeLog_java : jdk/src/share/native/java/util/zip/zlib/patches/ChangeLog_java
 jdk/src/java.base/unix/classes/java/io : jdk/src/solaris/classes/java/io
 jdk/src/java.base/unix/classes/java/lang : jdk/src/solaris/classes/java/lang
 jdk/src/java.base/unix/classes/java/net : jdk/src/solaris/classes/java/net
--- a/common/conf/jib-profiles.js	Thu Mar 16 16:34:35 2017 +0000
+++ b/common/conf/jib-profiles.js	Thu Mar 16 20:47:03 2017 +0000
@@ -1080,7 +1080,7 @@
         + "." + (minor != null ? minor : version_numbers.get("DEFAULT_VERSION_MINOR"))
         + "." + (security != null ? security :  version_numbers.get("DEFAULT_VERSION_SECURITY"))
         + "." + (patch != null ? patch : version_numbers.get("DEFAULT_VERSION_PATCH"));
-    while (version.match(".*\.0$")) {
+    while (version.match(".*\\.0$")) {
         version = version.substring(0, version.length - 2);
     }
     return version;
--- a/common/nb_native/nbproject/configurations.xml	Thu Mar 16 16:34:35 2017 +0000
+++ b/common/nb_native/nbproject/configurations.xml	Thu Mar 16 20:47:03 2017 +0000
@@ -1223,7 +1223,7 @@
                   <in>check_format.c</in>
                 </df>
                 <df name="libzip">
-                  <df name="zlib-1.2.8">
+                  <df name="zlib">
                     <in>compress.c</in>
                     <in>deflate.c</in>
                     <in>gzclose.c</in>
@@ -38283,7 +38283,7 @@
             <pElem>../../jdk/src/java.base/unix/native/include</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../build/support/headers/java.base</pElem>
             <pElem>../../make</pElem>
           </incDir>
@@ -38304,7 +38304,7 @@
             <pElem>../../jdk/src/java.base/unix/native/include</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../build/support/headers/java.base</pElem>
             <pElem>../../make</pElem>
           </incDir>
@@ -38325,7 +38325,7 @@
             <pElem>../../jdk/src/java.base/unix/native/include</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../build/support/headers/java.base</pElem>
             <pElem>../../make</pElem>
           </incDir>
@@ -38346,7 +38346,7 @@
             <pElem>../../jdk/src/java.base/unix/native/include</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../build/support/headers/java.base</pElem>
             <pElem>../../make</pElem>
           </incDir>
@@ -38367,7 +38367,7 @@
             <pElem>../../jdk/src/java.base/unix/native/include</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../build/support/headers/java.base</pElem>
             <pElem>../../make</pElem>
           </incDir>
@@ -38377,14 +38377,14 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/compress.c"
-            ex="false"
-            tool="0"
-            flavor2="0">
-        <cTool flags="4">
-        </cTool>
-      </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/deflate.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/compress.c"
+            ex="false"
+            tool="0"
+            flavor2="0">
+        <cTool flags="4">
+        </cTool>
+      </item>
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/deflate.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38394,7 +38394,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzclose.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/gzclose.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38404,7 +38404,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzlib.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/gzlib.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38414,7 +38414,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzread.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/gzread.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38424,7 +38424,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzwrite.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/gzwrite.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38434,7 +38434,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/infback.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/infback.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38444,7 +38444,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/inffast.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/inffast.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38454,7 +38454,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/inflate.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/inflate.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38464,7 +38464,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/inftrees.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/inftrees.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38474,7 +38474,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/trees.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/trees.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38484,7 +38484,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/uncompr.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/uncompr.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38494,7 +38494,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/zadler32.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/zadler32.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38504,7 +38504,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/zcrc32.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/zcrc32.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -38514,7 +38514,7 @@
           </preprocessorList>
         </cTool>
       </item>
-      <item path="../../jdk/src/java.base/share/native/libzip/zlib-1.2.8/zutil.c"
+      <item path="../../jdk/src/java.base/share/native/libzip/zlib/zutil.c"
             ex="false"
             tool="0"
             flavor2="0">
@@ -41203,7 +41203,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41232,7 +41232,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41261,7 +41261,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41290,7 +41290,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41319,7 +41319,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41348,7 +41348,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41377,7 +41377,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41406,7 +41406,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41435,7 +41435,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41464,7 +41464,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41493,7 +41493,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41522,7 +41522,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41551,7 +41551,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41580,7 +41580,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41609,7 +41609,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41638,7 +41638,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41667,7 +41667,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41696,7 +41696,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41725,7 +41725,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41754,7 +41754,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41783,7 +41783,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41812,7 +41812,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41841,7 +41841,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41870,7 +41870,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41899,7 +41899,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41928,7 +41928,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41957,7 +41957,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -41986,7 +41986,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42015,7 +42015,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42044,7 +42044,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42073,7 +42073,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42102,7 +42102,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42131,7 +42131,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42160,7 +42160,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42189,7 +42189,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42218,7 +42218,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42247,7 +42247,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42276,7 +42276,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42305,7 +42305,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42334,7 +42334,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42363,7 +42363,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42413,7 +42413,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42442,7 +42442,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -42471,7 +42471,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -46557,7 +46557,7 @@
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjli</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjli</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../make</pElem>
           </incDir>
           <preprocessorList>
@@ -46639,15 +46639,15 @@
           </preprocessorList>
         </cTool>
       </folder>
-      <folder path="0/jdk/src/java.base/share/native/libzip/zlib-1.2.8">
-        <cTool>
-          <incDir>
-            <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/giflib</pElem>
-            <pElem>../../jdk/src/java.desktop/share/native/libjavajpeg</pElem>
-            <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
-            <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+      <folder path="0/jdk/src/java.base/share/native/libzip/zlib">
+        <cTool>
+          <incDir>
+            <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/giflib</pElem>
+            <pElem>../../jdk/src/java.desktop/share/native/libjavajpeg</pElem>
+            <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
+            <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
+            <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -46712,7 +46712,7 @@
           <incDir>
             <pElem>../../jdk/src/java.base/unix/native/libjli</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjli</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../make</pElem>
           </incDir>
           <preprocessorList>
@@ -47250,7 +47250,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -47598,7 +47598,7 @@
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen</pElem>
             <pElem>../../jdk/src/java.desktop/share/native/libsplashscreen/libpng</pElem>
             <pElem>../../jdk/src/java.desktop/unix/native/libsplashscreen</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/linux/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
@@ -47996,7 +47996,7 @@
             <pElem>../../jdk/src/jdk.pack/share/native/common-unpack</pElem>
             <pElem>../../jdk/src/java.base/share/native/libjava</pElem>
             <pElem>../../jdk/src/java.base/unix/native/libjava</pElem>
-            <pElem>../../jdk/src/java.base/share/native/libzip/zlib-1.2.8</pElem>
+            <pElem>../../jdk/src/java.base/share/native/libzip/zlib</pElem>
             <pElem>../../jdk/src/java.base/share/native/include</pElem>
             <pElem>../../jdk/src/java.base/linux/native/include</pElem>
             <pElem>../../jdk/src/java.base/unix/native/include</pElem>
--- a/corba/.hgtags	Thu Mar 16 16:34:35 2017 +0000
+++ b/corba/.hgtags	Thu Mar 16 20:47:03 2017 +0000
@@ -396,5 +396,9 @@
 77f827f5bbad3ef795664bc675f72d98d156b9f8 jdk-9+151
 ff8cb43c07c069b1debdee44cb88ca22db1ec757 jdk-9+152
 68a8e8658511093b322a46ed04b2a321e1da2a43 jdk-9+153
+d66f97a610a6beac987740edc2bf6a70f46ba574 jdk-10+0
 078ebe23b584466dc8346e620d7821d91751e5a9 jdk-9+154
 a545f54babfa31aa7eb611f36031609acd617cbc jdk-9+155
+907c26240cd481579e919bfd23740797ff8ce1c8 jdk-9+156
+9383da04b385cca46b7ca67f3a39ac1b673e09fe jdk-9+157
+de6bdf38935fa753183ca288bed5c06a23c0bb12 jdk-9+158
--- a/corba/.jcheck/conf	Thu Mar 16 16:34:35 2017 +0000
+++ b/corba/.jcheck/conf	Thu Mar 16 20:47:03 2017 +0000
@@ -1,1 +1,1 @@
-project=jdk9
+project=jdk10
--- a/corba/src/java.corba/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/corba/src/java.corba/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines the Java binding of the OMG CORBA APIs, and the RMI-IIOP API.
+ *
+ * @since 9
  */
 @Deprecated(since="9", forRemoval=true)
 module java.corba {
--- a/corba/src/java.corba/share/classes/org/omg/CORBA/ORB.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/corba/src/java.corba/share/classes/org/omg/CORBA/ORB.java	Thu Mar 16 20:47:03 2017 +0000
@@ -106,13 +106,13 @@
  *
  *     <LI>check in properties parameter, if any
  *
- *     <LI>check in the System properties
+ *     <LI>check in the System properties, if any
  *
  *     <LI>check in the orb.properties file located in the user.home
- *         directory (if any)
+ *         directory, if any
  *
- *     <LI>check in the orb.properties file located in the java.home/lib
- *         directory (if any)
+ *     <LI>check in the orb.properties file located in the run-time image,
+ *         if any
  *
  *     <LI>fall back on a hardcoded default behavior (use the Java&nbsp;IDL
  *         implementation)
@@ -170,9 +170,15 @@
  * Thus, where appropriate, it is necessary that
  * the classes for this alternative ORBSingleton are available on the application's class path.
  * It should be noted that the singleton ORB is system wide.
- *
+ * <P>
  * When a per-application ORB is created via the 2-arg init methods,
  * then it will be located using the thread context class loader.
+ * <P>
+ * The IDL to Java Language OMG specification documents the ${java.home}/lib directory as the location,
+ * in the Java run-time image, to search for orb.properties.
+ * This location is not intended for user editable configuration files.
+ * Therefore, the implementation first checks the ${java.home}/conf directory for orb.properties,
+ * and thereafter the ${java.home}/lib directory.
  *
  * @since   JDK1.2
  */
@@ -271,14 +277,25 @@
                     }
 
                     String javaHome = System.getProperty("java.home");
-                    fileName = javaHome + File.separator
-                        + "lib" + File.separator + "orb.properties";
-                    props = getFileProperties( fileName ) ;
+
+                    fileName = javaHome + File.separator + "conf"
+                            + File.separator + "orb.properties";
+                    props = getFileProperties(fileName);
+
+                    if (props != null) {
+                        String value = props.getProperty(name);
+                        if (value != null)
+                            return value;
+                    }
+
+                    fileName = javaHome + File.separator + "lib"
+                            + File.separator + "orb.properties";
+                    props = getFileProperties(fileName);
 
                     if (props == null)
-                        return null ;
+                        return null;
                     else
-                        return props.getProperty( name ) ;
+                        return props.getProperty(name);
                 }
             }
         );
--- a/hotspot/.hgtags	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/.hgtags	Thu Mar 16 20:47:03 2017 +0000
@@ -556,5 +556,9 @@
 2a2ac7d9f52c8cb2b80077e515b5840b947e640c jdk-9+151
 31f1d26c60df7b2e516a4f84160d76ba017d4e09 jdk-9+152
 217ba81b9a4ce8698200370175aa2db86a39f66c jdk-9+153
+fc7e94cb748507366b839e859f865f724467446a jdk-10+0
 a9fdfd55835ef9dccb7f317b07249bd66653b874 jdk-9+154
 f3b3d77a1751897413aae43ac340a130b6fa2ae1 jdk-9+155
+43139c588ea48b6504e52b6c3dec530b17b1fdb4 jdk-9+156
+b2d0a906afd73dcf27f572217eb1be0f196ec16c jdk-9+157
+4e78f30935229f13ce7c43089621cf7169f5abac jdk-9+158
--- a/hotspot/.jcheck/conf	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/.jcheck/conf	Thu Mar 16 20:47:03 2017 +0000
@@ -1,1 +1,1 @@
-project=jdk9
+project=jdk10
--- a/hotspot/src/cpu/aarch64/vm/c1_LIRAssembler_aarch64.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/cpu/aarch64/vm/c1_LIRAssembler_aarch64.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1922,12 +1922,17 @@
     }
 
     if (opr2->is_constant()) {
+      bool is_32bit = false; // width of register operand
       jlong imm;
+
       switch(opr2->type()) {
+      case T_INT:
+        imm = opr2->as_constant_ptr()->as_jint();
+        is_32bit = true;
+        break;
       case T_LONG:
         imm = opr2->as_constant_ptr()->as_jlong();
         break;
-      case T_INT:
       case T_ADDRESS:
         imm = opr2->as_constant_ptr()->as_jint();
         break;
@@ -1942,14 +1947,14 @@
       }
 
       if (Assembler::operand_valid_for_add_sub_immediate(imm)) {
-        if (type2aelembytes(opr1->type()) <= 4)
+        if (is_32bit)
           __ cmpw(reg1, imm);
         else
           __ cmp(reg1, imm);
         return;
       } else {
         __ mov(rscratch1, imm);
-        if (type2aelembytes(opr1->type()) <= 4)
+        if (is_32bit)
           __ cmpw(reg1, rscratch1);
         else
           __ cmp(reg1, rscratch1);
--- a/hotspot/src/cpu/aarch64/vm/c1_globals_aarch64.hpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/cpu/aarch64/vm/c1_globals_aarch64.hpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2014, Red Hat Inc. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -45,10 +45,8 @@
 // We compile very aggressively with the builtin simulator because
 // doing so greatly reduces run times and tests more code.
 define_pd_global(intx, CompileThreshold,             150 );
-define_pd_global(intx, BackEdgeThreshold,            500);
 #else
 define_pd_global(intx, CompileThreshold,             1500 );
-define_pd_global(intx, BackEdgeThreshold,            100000);
 #endif
 
 define_pd_global(intx, OnStackReplacePercentage,     933  );
@@ -76,6 +74,4 @@
 define_pd_global(bool, CSEArrayLength,               false);
 define_pd_global(bool, TwoOperandLIRForm,            false );
 
-define_pd_global(intx, SafepointPollOffset,          0  );
-
 #endif // CPU_AARCH64_VM_C1_GLOBALS_AARCH64_HPP
--- a/hotspot/src/cpu/aarch64/vm/c2_globals_aarch64.hpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/cpu/aarch64/vm/c2_globals_aarch64.hpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, Oracle and/or its affiliates. All rights reserved.
  * Copyright (c) 2014, Red Hat Inc. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
@@ -43,7 +43,6 @@
 define_pd_global(bool, ProfileInterpreter,           true);
 define_pd_global(bool, TieredCompilation,            trueInTiered);
 define_pd_global(intx, CompileThreshold,             10000);
-define_pd_global(intx, BackEdgeThreshold,            100000);
 
 define_pd_global(intx, OnStackReplacePercentage,     140);
 define_pd_global(intx, ConditionalMoveLimit,         3);
--- a/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTStub.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/jdk.aot/share/classes/jdk.tools.jaotc/src/jdk/tools/jaotc/AOTStub.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,7 @@
 
 import org.graalvm.compiler.code.CompilationResult;
 import org.graalvm.compiler.core.target.Backend;
+import org.graalvm.compiler.hotspot.HotSpotCompiledCodeBuilder;
 import org.graalvm.compiler.hotspot.stubs.Stub;
 
 import jdk.vm.ci.hotspot.HotSpotCompiledCode;
@@ -48,7 +49,7 @@
     }
 
     public HotSpotCompiledCode compiledCode(CompilationResult result) {
-        return stub.getCompiledCode(backend);
+        return HotSpotCompiledCodeBuilder.createCompiledCode(null, null, result);
     }
 
 }
--- a/hotspot/src/jdk.hotspot.agent/linux/native/libsaproc/libproc_impl.c	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/jdk.hotspot.agent/linux/native/libsaproc/libproc_impl.c	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -50,7 +50,7 @@
   }
 
 
-  if (strlen(alt_root) + strlen(name) < PATH_MAX) {
+  if (strlen(alt_root) + strlen(name) > PATH_MAX) {
     // Buffer too small.
     return -1;
   }
--- a/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/tools/HeapSummary.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/tools/HeapSummary.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -150,13 +150,7 @@
    // Helper methods
 
    private void printGCAlgorithm(Map flagMap) {
-       // print about new generation
-       long l = getFlagValue("UseParNewGC", flagMap);
-       if (l == 1L) {
-          System.out.println("using parallel threads in the new generation.");
-       }
-
-       l = getFlagValue("UseTLAB", flagMap);
+       long l = getFlagValue("UseTLAB", flagMap);
        if (l == 1L) {
           System.out.println("using thread-local object allocation.");
        }
--- a/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/utilities/AbstractHeapGraphWriter.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/utilities/AbstractHeapGraphWriter.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2017, 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
@@ -114,6 +114,8 @@
                     }
                 });
 
+                writeHeapRecordPrologue();
+
                 // write JavaThreads
                 writeJavaThreads();
 
--- a/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/utilities/HeapHprofBinWriter.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/jdk.hotspot.agent/share/classes/sun/jvm/hotspot/utilities/HeapHprofBinWriter.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2017, 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
@@ -45,8 +45,8 @@
  * WARNING: This format is still under development, and is subject to
  * change without notice.
  *
- * header    "JAVA PROFILE 1.0.1" or "JAVA PROFILE 1.0.2" (0-terminated)
- * u4        size of identifiers. Identifiers are used to represent
+ * header     "JAVA PROFILE 1.0.2" (0-terminated)
+ * u4         size of identifiers. Identifiers are used to represent
  *            UTF8 strings, objects, stack traces, etc. They usually
  *            have the same size as host pointers. For example, on
  *            Solaris and Win32, the size is 4.
@@ -294,10 +294,9 @@
  *                u2        stack trace depth
  *
  *
- * When the header is "JAVA PROFILE 1.0.2" a heap dump can optionally
- * be generated as a sequence of heap dump segments. This sequence is
- * terminated by an end record. The additional tags allowed by format
- * "JAVA PROFILE 1.0.2" are:
+ * A heap dump can optionally be generated as a sequence of heap dump
+ * segments. This sequence is terminated by an end record. The additional
+ * tags allowed by format "JAVA PROFILE 1.0.2" are:
  *
  * HPROF_HEAP_DUMP_SEGMENT  denote a heap dump segment
  *
@@ -310,8 +309,6 @@
 
 public class HeapHprofBinWriter extends AbstractHeapGraphWriter {
 
-    // The heap size threshold used to determine if segmented format
-    // ("JAVA PROFILE 1.0.2") should be used.
     private static final long HPROF_SEGMENTED_HEAP_DUMP_THRESHOLD = 2L * 0x40000000;
 
     // The approximate size of a heap segment. Used to calculate when to create
@@ -319,7 +316,6 @@
     private static final long HPROF_SEGMENTED_HEAP_DUMP_SEGMENT_SIZE = 1L * 0x40000000;
 
     // hprof binary file header
-    private static final String HPROF_HEADER_1_0_1 = "JAVA PROFILE 1.0.1";
     private static final String HPROF_HEADER_1_0_2 = "JAVA PROFILE 1.0.2";
 
     // constants in enum HprofTag
@@ -380,6 +376,7 @@
     private static final int JVM_SIGNATURE_ARRAY   = '[';
     private static final int JVM_SIGNATURE_CLASS   = 'L';
 
+    private static final long MAX_U4_VALUE = 0xFFFFFFFFL;
     int serialNum = 1;
 
     public synchronized void write(String fileName) throws IOException {
@@ -469,7 +466,6 @@
             // length later - hprof format requires length.
             out.flush();
             currentSegmentStart = fos.getChannel().position();
-
             // write dummy length of 0 and we'll fix it later.
             out.writeInt(0);
         }
@@ -479,7 +475,7 @@
     protected void writeHeapRecordEpilogue() throws IOException {
         if (useSegmentedHeapDump) {
             out.flush();
-            if ((fos.getChannel().position() - currentSegmentStart - 4) >= HPROF_SEGMENTED_HEAP_DUMP_SEGMENT_SIZE) {
+            if ((fos.getChannel().position() - currentSegmentStart - 4L) >= HPROF_SEGMENTED_HEAP_DUMP_SEGMENT_SIZE) {
                 fillInHeapRecordLength();
                 currentSegmentStart = 0;
             }
@@ -488,14 +484,14 @@
 
     private void fillInHeapRecordLength() throws IOException {
 
-        // now get current position to calculate length
+        // now get the current position to calculate length
         long dumpEnd = fos.getChannel().position();
 
-        // calculate length of heap data
+        // calculate the length of heap data
         long dumpLenLong = (dumpEnd - currentSegmentStart - 4L);
 
         // Check length boundary, overflow could happen but is _very_ unlikely
-        if(dumpLenLong >= (4L * 0x40000000)){
+        if (dumpLenLong >= (4L * 0x40000000)) {
             throw new RuntimeException("Heap segment size overflow.");
         }
 
@@ -517,6 +513,71 @@
         fos.getChannel().position(currentPosition);
     }
 
+    // get the size in bytes for the requested type
+    private long getSizeForType(int type) throws IOException {
+        switch (type) {
+            case TypeArrayKlass.T_BOOLEAN:
+                return BOOLEAN_SIZE;
+            case TypeArrayKlass.T_INT:
+                return INT_SIZE;
+            case TypeArrayKlass.T_CHAR:
+                return CHAR_SIZE;
+            case TypeArrayKlass.T_SHORT:
+                return SHORT_SIZE;
+            case TypeArrayKlass.T_BYTE:
+                return BYTE_SIZE;
+            case TypeArrayKlass.T_LONG:
+                return LONG_SIZE;
+            case TypeArrayKlass.T_FLOAT:
+                return FLOAT_SIZE;
+            case TypeArrayKlass.T_DOUBLE:
+                return DOUBLE_SIZE;
+            default:
+                throw new RuntimeException(
+                    "Should not reach here: Unknown type: " + type);
+         }
+    }
+
+    private int getArrayHeaderSize(boolean isObjectAarray) {
+        return isObjectAarray?
+            ((int) BYTE_SIZE + 2 * (int) INT_SIZE + 2 * (int) OBJ_ID_SIZE):
+            (2 * (int) BYTE_SIZE + 2 * (int) INT_SIZE + (int) OBJ_ID_SIZE);
+    }
+
+    // Check if we need to truncate an array
+    private int calculateArrayMaxLength(long originalArrayLength,
+                                        int headerSize,
+                                        long typeSize,
+                                        String typeName) throws IOException {
+
+        long length = originalArrayLength;
+
+        // now get the current position to calculate length
+        long dumpEnd = fos.getChannel().position();
+        long originalLengthInBytes = originalArrayLength * typeSize;
+
+        // calculate the length of heap data
+        long currentRecordLength = (dumpEnd - currentSegmentStart - 4L);
+        if (currentRecordLength > 0 &&
+            (currentRecordLength + headerSize + originalLengthInBytes) > MAX_U4_VALUE) {
+            fillInHeapRecordLength();
+            currentSegmentStart = 0;
+            writeHeapRecordPrologue();
+            currentRecordLength = 0;
+        }
+
+        // Calculate the max bytes we can use.
+        long maxBytes = (MAX_U4_VALUE - (headerSize + currentRecordLength));
+
+        if (originalLengthInBytes > maxBytes) {
+            length = maxBytes/typeSize;
+            System.err.println("WARNING: Cannot dump array of type " + typeName
+                               + " with length " + originalArrayLength
+                               + "; truncating to length " + length);
+        }
+        return (int) length;
+    }
+
     private void writeClassDumpRecords() throws IOException {
         SystemDictionary sysDict = VM.getVM().getSystemDictionary();
         ClassLoaderDataGraph cldGraph = VM.getVM().getClassLoaderDataGraph();
@@ -694,12 +755,16 @@
     }
 
     protected void writeObjectArray(ObjArray array) throws IOException {
+        int headerSize = getArrayHeaderSize(true);
+        final int length = calculateArrayMaxLength(array.getLength(),
+                                                   headerSize,
+                                                   OBJ_ID_SIZE,
+                                                   "Object");
         out.writeByte((byte) HPROF_GC_OBJ_ARRAY_DUMP);
         writeObjectID(array);
         out.writeInt(DUMMY_STACK_TRACE_ID);
-        out.writeInt((int) array.getLength());
+        out.writeInt(length);
         writeObjectID(array.getKlass().getJavaMirror());
-        final int length = (int) array.getLength();
         for (int index = 0; index < length; index++) {
             OopHandle handle = array.getOopHandleAt(index);
             writeObjectID(getAddressValue(handle));
@@ -707,101 +772,101 @@
     }
 
     protected void writePrimitiveArray(TypeArray array) throws IOException {
+        int headerSize = getArrayHeaderSize(false);
+        TypeArrayKlass tak = (TypeArrayKlass) array.getKlass();
+        final int type = (int) tak.getElementType();
+        final String typeName = tak.getElementTypeName();
+        final long typeSize = getSizeForType(type);
+        final int length = calculateArrayMaxLength(array.getLength(),
+                                                   headerSize,
+                                                   typeSize,
+                                                   typeName);
         out.writeByte((byte) HPROF_GC_PRIM_ARRAY_DUMP);
         writeObjectID(array);
         out.writeInt(DUMMY_STACK_TRACE_ID);
-        out.writeInt((int) array.getLength());
-        TypeArrayKlass tak = (TypeArrayKlass) array.getKlass();
-        final int type = (int) tak.getElementType();
+        out.writeInt(length);
         out.writeByte((byte) type);
         switch (type) {
             case TypeArrayKlass.T_BOOLEAN:
-                writeBooleanArray(array);
+                writeBooleanArray(array, length);
                 break;
             case TypeArrayKlass.T_CHAR:
-                writeCharArray(array);
+                writeCharArray(array, length);
                 break;
             case TypeArrayKlass.T_FLOAT:
-                writeFloatArray(array);
+                writeFloatArray(array, length);
                 break;
             case TypeArrayKlass.T_DOUBLE:
-                writeDoubleArray(array);
+                writeDoubleArray(array, length);
                 break;
             case TypeArrayKlass.T_BYTE:
-                writeByteArray(array);
+                writeByteArray(array, length);
                 break;
             case TypeArrayKlass.T_SHORT:
-                writeShortArray(array);
+                writeShortArray(array, length);
                 break;
             case TypeArrayKlass.T_INT:
-                writeIntArray(array);
+                writeIntArray(array, length);
                 break;
             case TypeArrayKlass.T_LONG:
-                writeLongArray(array);
+                writeLongArray(array, length);
                 break;
             default:
-                throw new RuntimeException("should not reach here");
+                throw new RuntimeException(
+                    "Should not reach here: Unknown type: " + type);
         }
     }
 
-    private void writeBooleanArray(TypeArray array) throws IOException {
-        final int length = (int) array.getLength();
+    private void writeBooleanArray(TypeArray array, int length) throws IOException {
         for (int index = 0; index < length; index++) {
              long offset = BOOLEAN_BASE_OFFSET + index * BOOLEAN_SIZE;
              out.writeBoolean(array.getHandle().getJBooleanAt(offset));
         }
     }
 
-    private void writeByteArray(TypeArray array) throws IOException {
-        final int length = (int) array.getLength();
+    private void writeByteArray(TypeArray array, int length) throws IOException {
         for (int index = 0; index < length; index++) {
              long offset = BYTE_BASE_OFFSET + index * BYTE_SIZE;
              out.writeByte(array.getHandle().getJByteAt(offset));
         }
     }
 
-    private void writeShortArray(TypeArray array) throws IOException {
-        final int length = (int) array.getLength();
+    private void writeShortArray(TypeArray array, int length) throws IOException {
         for (int index = 0; index < length; index++) {
              long offset = SHORT_BASE_OFFSET + index * SHORT_SIZE;
              out.writeShort(array.getHandle().getJShortAt(offset));
         }
     }
 
-    private void writeIntArray(TypeArray array) throws IOException {
-        final int length = (int) array.getLength();
+    private void writeIntArray(TypeArray array, int length) throws IOException {
         for (int index = 0; index < length; index++) {
              long offset = INT_BASE_OFFSET + index * INT_SIZE;
              out.writeInt(array.getHandle().getJIntAt(offset));
         }
     }
 
-    private void writeLongArray(TypeArray array) throws IOException {
-        final int length = (int) array.getLength();
+    private void writeLongArray(TypeArray array, int length) throws IOException {
         for (int index = 0; index < length; index++) {
              long offset = LONG_BASE_OFFSET + index * LONG_SIZE;
              out.writeLong(array.getHandle().getJLongAt(offset));
         }
     }
 
-    private void writeCharArray(TypeArray array) throws IOException {
-        final int length = (int) array.getLength();
+    private void writeCharArray(TypeArray array, int length) throws IOException {
         for (int index = 0; index < length; index++) {
              long offset = CHAR_BASE_OFFSET + index * CHAR_SIZE;
              out.writeChar(array.getHandle().getJCharAt(offset));
         }
     }
 
-    private void writeFloatArray(TypeArray array) throws IOException {
-        final int length = (int) array.getLength();
+    private void writeFloatArray(TypeArray array, int length) throws IOException {
         for (int index = 0; index < length; index++) {
              long offset = FLOAT_BASE_OFFSET + index * FLOAT_SIZE;
              out.writeFloat(array.getHandle().getJFloatAt(offset));
         }
     }
 
-    private void writeDoubleArray(TypeArray array) throws IOException {
-        final int length = (int) array.getLength();
+    private void writeDoubleArray(TypeArray array, int length) throws IOException {
         for (int index = 0; index < length; index++) {
              long offset = DOUBLE_BASE_OFFSET + index * DOUBLE_SIZE;
              out.writeDouble(array.getHandle().getJDoubleAt(offset));
@@ -996,12 +1061,7 @@
     // writes hprof binary file header
     private void writeFileHeader() throws IOException {
         // version string
-        if(useSegmentedHeapDump) {
-            out.writeBytes(HPROF_HEADER_1_0_2);
-        }
-        else {
-            out.writeBytes(HPROF_HEADER_1_0_1);
-        }
+        out.writeBytes(HPROF_HEADER_1_0_2);
         out.writeByte((byte)'\0');
 
         // write identifier size. we use pointers as identifiers.
--- a/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotJVMCIMetaAccessContext.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/jdk.vm.ci/share/classes/jdk.vm.ci.hotspot/src/jdk/vm/ci/hotspot/HotSpotJVMCIMetaAccessContext.java	Thu Mar 16 20:47:03 2017 +0000
@@ -27,8 +27,6 @@
 import java.lang.ref.WeakReference;
 import java.util.Arrays;
 import java.util.Iterator;
-import java.util.Map;
-import java.util.WeakHashMap;
 
 import jdk.vm.ci.meta.JavaKind;
 import jdk.vm.ci.meta.ResolvedJavaType;
@@ -147,21 +145,34 @@
         }
     }
 
-    private final Map<Class<?>, WeakReference<ResolvedJavaType>> typeMap = new WeakHashMap<>();
+    private final ClassValue<WeakReference<ResolvedJavaType>> resolvedJavaType = new ClassValue<WeakReference<ResolvedJavaType>>() {
+        @Override
+        protected WeakReference<ResolvedJavaType> computeValue(Class<?> type) {
+            return new WeakReference<>(createClass(type));
+        }
+    };
 
     /**
      * Gets the JVMCI mirror for a {@link Class} object.
      *
      * @return the {@link ResolvedJavaType} corresponding to {@code javaClass}
      */
-    public synchronized ResolvedJavaType fromClass(Class<?> javaClass) {
-        WeakReference<ResolvedJavaType> typeRef = typeMap.get(javaClass);
-        ResolvedJavaType type = typeRef != null ? typeRef.get() : null;
-        if (type == null) {
-            type = createClass(javaClass);
-            typeMap.put(javaClass, new WeakReference<>(type));
+    public ResolvedJavaType fromClass(Class<?> javaClass) {
+        ResolvedJavaType javaType = null;
+        while (javaType == null) {
+            WeakReference<ResolvedJavaType> type = resolvedJavaType.get(javaClass);
+            javaType = type.get();
+            if (javaType == null) {
+                /*
+                 * If the referent has become null, clear out the current value
+                 * and let computeValue above create a new value.  Reload the
+                 * value in a loop because in theory the WeakReference referent
+                 * can be reclaimed at any point.
+                 */
+                resolvedJavaType.remove(javaClass);
+            }
         }
-        return type;
+        return javaType;
     }
 
     /**
--- a/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/stubs/Stub.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/jdk.vm.compiler/share/classes/org.graalvm.compiler.hotspot/src/org/graalvm/compiler/hotspot/stubs/Stub.java	Thu Mar 16 20:47:03 2017 +0000
@@ -90,17 +90,10 @@
     protected InstalledCode code;
 
     /**
-     * Compilation result from which {@link #code} was created.
-     */
-    protected CompilationResult compResult;
-
-    /**
      * The registers destroyed by this stub (from the caller's perspective).
      */
     private Set<Register> destroyedCallerRegisters;
 
-    private HotSpotCompiledCode compiledCode;
-
     public void initDestroyedCallerRegisters(Set<Register> registers) {
         assert registers != null;
         assert destroyedCallerRegisters == null || registers.equals(destroyedCallerRegisters) : "cannot redefine";
@@ -184,35 +177,13 @@
     public synchronized InstalledCode getCode(final Backend backend) {
         if (code == null) {
             try (Scope d = Debug.sandbox("CompilingStub", DebugScope.getConfig(), providers.getCodeCache(), debugScopeContext())) {
-                final StructuredGraph graph = getGraph(getStubCompilationId());
-
-                // Stubs cannot be recompiled so they cannot be compiled with assumptions
-                assert graph.getAssumptions() == null;
-
-                if (!(graph.start() instanceof StubStartNode)) {
-                    StubStartNode newStart = graph.add(new StubStartNode(Stub.this));
-                    newStart.setStateAfter(graph.start().stateAfter());
-                    graph.replaceFixed(graph.start(), newStart);
-                }
-
                 CodeCacheProvider codeCache = providers.getCodeCache();
-
-                compResult = new CompilationResult(toString(), GeneratePIC.getValue());
-                try (Scope s0 = Debug.scope("StubCompilation", graph, providers.getCodeCache())) {
-                    Suites suites = createSuites();
-                    emitFrontEnd(providers, backend, graph, providers.getSuites().getDefaultGraphBuilderSuite(), OptimisticOptimizations.ALL, DefaultProfilingInfo.get(TriState.UNKNOWN), suites);
-                    LIRSuites lirSuites = createLIRSuites();
-                    emitBackEnd(graph, Stub.this, getInstalledCodeOwner(), backend, compResult, CompilationResultBuilderFactory.Default, getRegisterConfig(), lirSuites);
-                    assert checkStubInvariants();
-                } catch (Throwable e) {
-                    throw Debug.handle(e);
-                }
-
-                assert destroyedCallerRegisters != null;
+                CompilationResult compResult = buildCompilationResult(backend);
                 try (Scope s = Debug.scope("CodeInstall", compResult)) {
+                    assert destroyedCallerRegisters != null;
                     // Add a GeneratePIC check here later, we don't want to install
                     // code if we don't have a corresponding VM global symbol.
-                    compiledCode = HotSpotCompiledCodeBuilder.createCompiledCode(null, null, compResult);
+                    HotSpotCompiledCode compiledCode = HotSpotCompiledCodeBuilder.createCompiledCode(null, null, compResult);
                     code = codeCache.installCode(null, compiledCode, null, null, false);
                 } catch (Throwable e) {
                     throw Debug.handle(e);
@@ -226,6 +197,44 @@
         return code;
     }
 
+    @SuppressWarnings("try")
+    private CompilationResult buildCompilationResult(final Backend backend) {
+        CompilationResult compResult = new CompilationResult(toString(), GeneratePIC.getValue());
+        final StructuredGraph graph = getGraph(getStubCompilationId());
+
+        // Stubs cannot be recompiled so they cannot be compiled with assumptions
+        assert graph.getAssumptions() == null;
+
+        if (!(graph.start() instanceof StubStartNode)) {
+            StubStartNode newStart = graph.add(new StubStartNode(Stub.this));
+            newStart.setStateAfter(graph.start().stateAfter());
+            graph.replaceFixed(graph.start(), newStart);
+        }
+
+        try (Scope s0 = Debug.scope("StubCompilation", graph, providers.getCodeCache())) {
+            Suites suites = createSuites();
+            emitFrontEnd(providers, backend, graph, providers.getSuites().getDefaultGraphBuilderSuite(), OptimisticOptimizations.ALL, DefaultProfilingInfo.get(TriState.UNKNOWN), suites);
+            LIRSuites lirSuites = createLIRSuites();
+            emitBackEnd(graph, Stub.this, getInstalledCodeOwner(), backend, compResult, CompilationResultBuilderFactory.Default, getRegisterConfig(), lirSuites);
+            assert checkStubInvariants(compResult);
+        } catch (Throwable e) {
+            throw Debug.handle(e);
+        }
+        return compResult;
+    }
+
+    /**
+     * Gets a {@link CompilationResult} that can be used for code generation. Required for AOT.
+     */
+    @SuppressWarnings("try")
+    public CompilationResult getCompilationResult(final Backend backend) {
+        try (Scope d = Debug.sandbox("CompilingStub", DebugScope.getConfig(), providers.getCodeCache(), debugScopeContext())) {
+            return buildCompilationResult(backend);
+        } catch (Throwable e) {
+            throw Debug.handle(e);
+        }
+    }
+
     public CompilationIdentifier getStubCompilationId() {
         return new StubCompilationIdentifier(this);
     }
@@ -233,7 +242,7 @@
     /**
      * Checks the conditions a compilation must satisfy to be installed as a RuntimeStub.
      */
-    private boolean checkStubInvariants() {
+    private boolean checkStubInvariants(CompilationResult compResult) {
         assert compResult.getExceptionHandlers().isEmpty() : this;
 
         // Stubs cannot be recompiled so they cannot be compiled with
@@ -278,24 +287,4 @@
         }
         return lirSuites;
     }
-
-    /**
-     * Gets the HotSpotCompiledCode that was created during installation.
-     */
-    public synchronized HotSpotCompiledCode getCompiledCode(final Backend backend) {
-        getCompilationResult(backend);
-        assert compiledCode != null;
-        return compiledCode;
-    }
-
-    /**
-     * Gets the compilation result for this stub, compiling it first if necessary, and installing it
-     * in code.
-     */
-    public synchronized CompilationResult getCompilationResult(final Backend backend) {
-        if (code == null) {
-            getCode(backend);
-        }
-        return compResult;
-    }
 }
--- a/hotspot/src/os/solaris/vm/os_solaris.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/os/solaris/vm/os_solaris.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -3050,15 +3050,12 @@
   thr_yield();
 }
 
-// Interface for setting lwp priorities.  If we are using T2 libthread,
-// which forces the use of BoundThreads or we manually set UseBoundThreads,
-// all of our threads will be assigned to real lwp's.  Using the thr_setprio
-// function is meaningless in this mode so we must adjust the real lwp's priority
+// Interface for setting lwp priorities.  We are using T2 libthread,
+// which forces the use of bound threads, so all of our threads will
+// be assigned to real lwp's.  Using the thr_setprio function is
+// meaningless in this mode so we must adjust the real lwp's priority.
 // The routines below implement the getting and setting of lwp priorities.
 //
-// Note: T2 is now the only supported libthread. UseBoundThreads flag is
-//       being deprecated and all threads are now BoundThreads
-//
 // Note: There are three priority scales used on Solaris.  Java priotities
 //       which range from 1 to 10, libthread "thr_setprio" scale which range
 //       from 0 to 127, and the current scheduling class of the process we
--- a/hotspot/src/share/vm/c1/c1_Canonicalizer.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/c1/c1_Canonicalizer.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -248,7 +248,9 @@
   } else if ((lf = x->array()->as_LoadField()) != NULL) {
     ciField* field = lf->field();
     if (field->is_static_constant()) {
-      assert(PatchALot || ScavengeRootsInCode < 2, "Constant field loads are folded during parsing");
+      // Constant field loads are usually folded during parsing.
+      // But it doesn't happen with PatchALot, ScavengeRootsInCode < 2, or when
+      // holder class is being initialized during parsing (for static fields).
       ciObject* c = field->constant_value().as_object();
       if (!c->is_null_object()) {
         set_constant(c->as_array()->length());
--- a/hotspot/src/share/vm/c1/c1_LIR.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/c1/c1_LIR.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1413,6 +1413,17 @@
   append(c);
 }
 
+void LIR_List::null_check(LIR_Opr opr, CodeEmitInfo* info, bool deoptimize_on_null) {
+  if (deoptimize_on_null) {
+    // Emit an explicit null check and deoptimize if opr is null
+    CodeStub* deopt = new DeoptimizeStub(info, Deoptimization::Reason_null_check, Deoptimization::Action_none);
+    cmp(lir_cond_equal, opr, LIR_OprFact::oopConst(NULL));
+    branch(lir_cond_equal, T_OBJECT, deopt);
+  } else {
+    // Emit an implicit null check
+    append(new LIR_Op1(lir_null_check, opr, info));
+  }
+}
 
 void LIR_List::cas_long(LIR_Opr addr, LIR_Opr cmp_value, LIR_Opr new_value,
                         LIR_Opr t1, LIR_Opr t2, LIR_Opr result) {
--- a/hotspot/src/share/vm/c1/c1_LIR.hpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/c1/c1_LIR.hpp	Thu Mar 16 20:47:03 2017 +0000
@@ -2113,7 +2113,7 @@
   void   pack64(LIR_Opr src, LIR_Opr dst) { append(new LIR_Op1(lir_pack64,   src, dst, T_LONG, lir_patch_none, NULL)); }
   void unpack64(LIR_Opr src, LIR_Opr dst) { append(new LIR_Op1(lir_unpack64, src, dst, T_LONG, lir_patch_none, NULL)); }
 
-  void null_check(LIR_Opr opr, CodeEmitInfo* info)         { append(new LIR_Op1(lir_null_check, opr, info)); }
+  void null_check(LIR_Opr opr, CodeEmitInfo* info, bool deoptimize_on_null = false);
   void throw_exception(LIR_Opr exceptionPC, LIR_Opr exceptionOop, CodeEmitInfo* info) {
     append(new LIR_Op2(lir_throw, exceptionPC, exceptionOop, LIR_OprFact::illegalOpr, info));
   }
--- a/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/c1/c1_LIRGenerator.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1752,8 +1752,10 @@
   if (x->needs_null_check() &&
       (needs_patching ||
        MacroAssembler::needs_explicit_null_check(x->offset()))) {
-    // emit an explicit null check because the offset is too large
-    __ null_check(object.result(), new CodeEmitInfo(info));
+    // Emit an explicit null check because the offset is too large.
+    // If the class is not loaded and the object is NULL, we need to deoptimize to throw a
+    // NoClassDefFoundError in the interpreter instead of an implicit NPE from compiled code.
+    __ null_check(object.result(), new CodeEmitInfo(info), /* deoptimize */ needs_patching);
   }
 
   LIR_Address* address;
@@ -1838,8 +1840,10 @@
       obj = new_register(T_OBJECT);
       __ move(LIR_OprFact::oopConst(NULL), obj);
     }
-    // emit an explicit null check because the offset is too large
-    __ null_check(obj, new CodeEmitInfo(info));
+    // Emit an explicit null check because the offset is too large.
+    // If the class is not loaded and the object is NULL, we need to deoptimize to throw a
+    // NoClassDefFoundError in the interpreter instead of an implicit NPE from compiled code.
+    __ null_check(obj, new CodeEmitInfo(info), /* deoptimize */ needs_patching);
   }
 
   LIR_Opr reg = rlock_result(x, field_type);
--- a/hotspot/src/share/vm/ci/ciEnv.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/ci/ciEnv.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -101,6 +101,7 @@
   _debug_info = NULL;
   _dependencies = NULL;
   _failure_reason = NULL;
+  _inc_decompile_count_on_failure = true;
   _compilable = MethodCompilable;
   _break_at_compile = false;
   _compiler_data = NULL;
@@ -161,6 +162,7 @@
   _debug_info = NULL;
   _dependencies = NULL;
   _failure_reason = NULL;
+  _inc_decompile_count_on_failure = true;
   _compilable = MethodCompilable_never;
   _break_at_compile = false;
   _compiler_data = NULL;
@@ -902,7 +904,12 @@
     if (deps.is_klass_type())  continue;  // skip klass dependencies
     Klass* witness = deps.check_dependency();
     if (witness != NULL) {
-      record_failure("invalid non-klass dependency");
+      if (deps.type() == Dependencies::call_site_target_value) {
+        _inc_decompile_count_on_failure = false;
+        record_failure("call site target change");
+      } else {
+        record_failure("invalid non-klass dependency");
+      }
       return;
     }
   }
@@ -1017,7 +1024,7 @@
     if (failing()) {
       // While not a true deoptimization, it is a preemptive decompile.
       MethodData* mdo = method()->method_data();
-      if (mdo != NULL) {
+      if (mdo != NULL && _inc_decompile_count_on_failure) {
         mdo->inc_decompile_count();
       }
 
--- a/hotspot/src/share/vm/ci/ciEnv.hpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/ci/ciEnv.hpp	Thu Mar 16 20:47:03 2017 +0000
@@ -55,6 +55,7 @@
   DebugInformationRecorder* _debug_info;
   Dependencies*    _dependencies;
   const char*      _failure_reason;
+  bool             _inc_decompile_count_on_failure;
   int              _compilable;
   bool             _break_at_compile;
   int              _num_inlined_bytecodes;
--- a/hotspot/src/share/vm/classfile/javaClasses.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/classfile/javaClasses.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -2269,6 +2269,7 @@
   compute_offset(_monitors_offset,   k, vmSymbols::monitors_name(),    vmSymbols::object_array_signature());
   compute_offset(_locals_offset,     k, vmSymbols::locals_name(),      vmSymbols::object_array_signature());
   compute_offset(_operands_offset,   k, vmSymbols::operands_name(),    vmSymbols::object_array_signature());
+  compute_offset(_mode_offset,       k, vmSymbols::mode_name(),        vmSymbols::int_signature());
 }
 
 void java_lang_reflect_AccessibleObject::compute_offsets() {
@@ -3658,6 +3659,7 @@
 int java_lang_LiveStackFrameInfo::_monitors_offset;
 int java_lang_LiveStackFrameInfo::_locals_offset;
 int java_lang_LiveStackFrameInfo::_operands_offset;
+int java_lang_LiveStackFrameInfo::_mode_offset;
 int java_lang_AssertionStatusDirectives::classes_offset;
 int java_lang_AssertionStatusDirectives::classEnabled_offset;
 int java_lang_AssertionStatusDirectives::packages_offset;
@@ -3728,6 +3730,10 @@
   element->obj_field_put(_operands_offset, value);
 }
 
+void java_lang_LiveStackFrameInfo::set_mode(oop element, int value) {
+  element->int_field_put(_mode_offset, value);
+}
+
 // Support for java Assertions - java_lang_AssertionStatusDirectives.
 
 void java_lang_AssertionStatusDirectives::set_classes(oop o, oop val) {
--- a/hotspot/src/share/vm/classfile/javaClasses.hpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/classfile/javaClasses.hpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1380,11 +1380,13 @@
   static int _monitors_offset;
   static int _locals_offset;
   static int _operands_offset;
+  static int _mode_offset;
 
  public:
   static void set_monitors(oop info, oop value);
   static void set_locals(oop info, oop value);
   static void set_operands(oop info, oop value);
+  static void set_mode(oop info, int value);
 
   static void compute_offsets();
 
--- a/hotspot/src/share/vm/classfile/vmSymbols.hpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp	Thu Mar 16 20:47:03 2017 +0000
@@ -325,14 +325,8 @@
   template(java_lang_StackStreamFactory_AbstractStackWalker, "java/lang/StackStreamFactory$AbstractStackWalker") \
   template(doStackWalk_signature,                     "(JIIII)Ljava/lang/Object;")                \
   template(asPrimitive_name,                          "asPrimitive")                              \
-  template(asPrimitive_int_signature,                 "(I)Ljava/lang/LiveStackFrame$PrimitiveValue;") \
-  template(asPrimitive_long_signature,                "(J)Ljava/lang/LiveStackFrame$PrimitiveValue;") \
-  template(asPrimitive_short_signature,               "(S)Ljava/lang/LiveStackFrame$PrimitiveValue;") \
-  template(asPrimitive_byte_signature,                "(B)Ljava/lang/LiveStackFrame$PrimitiveValue;") \
-  template(asPrimitive_char_signature,                "(C)Ljava/lang/LiveStackFrame$PrimitiveValue;") \
-  template(asPrimitive_float_signature,               "(F)Ljava/lang/LiveStackFrame$PrimitiveValue;") \
-  template(asPrimitive_double_signature,              "(D)Ljava/lang/LiveStackFrame$PrimitiveValue;") \
-  template(asPrimitive_boolean_signature,             "(Z)Ljava/lang/LiveStackFrame$PrimitiveValue;") \
+  template(asPrimitive_int_signature,                 "(I)Ljava/lang/LiveStackFrame$PrimitiveSlot;") \
+  template(asPrimitive_long_signature,                "(J)Ljava/lang/LiveStackFrame$PrimitiveSlot;") \
                                                                                                   \
   /* common method and field names */                                                             \
   template(object_initializer_name,                   "<init>")                                   \
@@ -444,6 +438,7 @@
   template(monitors_name,                             "monitors")                                 \
   template(locals_name,                               "locals")                                   \
   template(operands_name,                             "operands")                                 \
+  template(mode_name,                                 "mode")                                     \
   template(oop_size_name,                             "oop_size")                                 \
   template(static_oop_field_count_name,               "static_oop_field_count")                   \
   template(protection_domain_name,                    "protection_domain")                        \
--- a/hotspot/src/share/vm/code/codeCache.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/code/codeCache.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1211,7 +1211,7 @@
   CompiledMethodIterator iter;
   while(iter.next_alive()) {
     CompiledMethod* nm = iter.method();
-    if (nm->is_marked_for_deoptimization()) {
+    if (nm->is_marked_for_deoptimization() && !nm->is_not_entrant()) {
       nm->make_not_entrant();
     }
   }
--- a/hotspot/src/share/vm/code/nmethod.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/code/nmethod.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1146,6 +1146,14 @@
   assert(state == zombie || state == not_entrant, "must be zombie or not_entrant");
   assert(!is_zombie(), "should not already be a zombie");
 
+  if (_state == state) {
+    // Avoid taking the lock if already in required state.
+    // This is safe from races because the state is an end-state,
+    // which the nmethod cannot back out of once entered.
+    // No need for fencing either.
+    return false;
+  }
+
   // Make sure neither the nmethod nor the method is flushed in case of a safepoint in code below.
   nmethodLocker nml(this);
   methodHandle the_method(method());
--- a/hotspot/src/share/vm/gc/cms/concurrentMarkSweepGeneration.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/gc/cms/concurrentMarkSweepGeneration.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2017, 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
@@ -488,9 +488,6 @@
   _gc_timer_cm(new (ResourceObj::C_HEAP, mtGC) ConcurrentGCTimer()),
   _cms_start_registered(false)
 {
-  if (ExplicitGCInvokesConcurrentAndUnloadsClasses) {
-    ExplicitGCInvokesConcurrent = true;
-  }
   // Now expand the span and allocate the collection support structures
   // (MUT, marking bit map etc.) to cover both generations subject to
   // collection.
@@ -2559,10 +2556,8 @@
 // Decide if we want to enable class unloading as part of the
 // ensuing concurrent GC cycle. We will collect and
 // unload classes if it's the case that:
-// (1) an explicit gc request has been made and the flag
-//     ExplicitGCInvokesConcurrentAndUnloadsClasses is set, OR
-// (2) (a) class unloading is enabled at the command line, and
-//     (b) old gen is getting really full
+//  (a) class unloading is enabled at the command line, and
+//  (b) old gen is getting really full
 // NOTE: Provided there is no change in the state of the heap between
 // calls to this method, it should have idempotent results. Moreover,
 // its results should be monotonically increasing (i.e. going from 0 to 1,
@@ -2575,11 +2570,7 @@
 // below.
 void CMSCollector::update_should_unload_classes() {
   _should_unload_classes = false;
-  // Condition 1 above
-  if (_full_gc_requested && ExplicitGCInvokesConcurrentAndUnloadsClasses) {
-    _should_unload_classes = true;
-  } else if (CMSClassUnloadingEnabled) { // Condition 2.a above
-    // Disjuncts 2.b.(i,ii,iii) above
+  if (CMSClassUnloadingEnabled) {
     _should_unload_classes = (concurrent_cycles_since_last_unload() >=
                               CMSClassUnloadingMaxInterval)
                            || _cmsGen->is_too_full();
--- a/hotspot/src/share/vm/gc/g1/heapRegionRemSet.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/gc/g1/heapRegionRemSet.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2017, 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
@@ -711,29 +711,6 @@
   guarantee(G1RSetSparseRegionEntries > 0 && G1RSetRegionEntries > 0 , "Sanity");
 }
 
-#ifndef PRODUCT
-void HeapRegionRemSet::print() {
-  HeapRegionRemSetIterator iter(this);
-  size_t card_index;
-  while (iter.has_next(card_index)) {
-    HeapWord* card_start = _bot->address_for_index(card_index);
-    tty->print_cr("  Card " PTR_FORMAT, p2i(card_start));
-  }
-  if (iter.n_yielded() != occupied()) {
-    tty->print_cr("Yielded disagrees with occupied:");
-    tty->print_cr("  " SIZE_FORMAT_W(6) " yielded (" SIZE_FORMAT_W(6)
-                  " coarse, " SIZE_FORMAT_W(6) " fine).",
-                  iter.n_yielded(),
-                  iter.n_yielded_coarse(), iter.n_yielded_fine());
-    tty->print_cr("  " SIZE_FORMAT_W(6) " occ     (" SIZE_FORMAT_W(6)
-                           " coarse, " SIZE_FORMAT_W(6) " fine).",
-                  occupied(), occ_coarse(), occ_fine());
-  }
-  guarantee(iter.n_yielded() == occupied(),
-            "We should have yielded all the represented cards.");
-}
-#endif
-
 void HeapRegionRemSet::cleanup() {
   SparsePRT::cleanup_all();
 }
@@ -917,10 +894,6 @@
     // Otherwise...
     break;
   }
-  assert(ParallelGCThreads > 1 ||
-         n_yielded() == _hrrs->occupied(),
-         "Should have yielded all the cards in the rem set "
-         "(in the non-par case).");
   return false;
 }
 
--- a/hotspot/src/share/vm/gc/g1/heapRegionRemSet.hpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/gc/g1/heapRegionRemSet.hpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2017, 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
@@ -290,8 +290,6 @@
   // consumed by the strong code roots.
   size_t strong_code_roots_mem_size();
 
-  void print() PRODUCT_RETURN;
-
   // Called during a stop-world phase to perform any deferred cleanups.
   static void cleanup();
 
--- a/hotspot/src/share/vm/oops/method.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/oops/method.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -2199,7 +2199,6 @@
   ResourceMark rm;
   assert(is_method(), "must be method");
   st->print_cr("%s", internal_name());
-  // get the effect of PrintOopAddress, always, for methods:
   st->print_cr(" - this oop:          " INTPTR_FORMAT, p2i(this));
   st->print   (" - method holder:     "); method_holder()->print_value_on(st); st->cr();
   st->print   (" - constants:         " INTPTR_FORMAT " ", p2i(constants()));
--- a/hotspot/src/share/vm/opto/type.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/opto/type.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -373,7 +373,7 @@
   if (con_type != NULL && field->is_call_site_target()) {
     ciCallSite* call_site = holder->as_call_site();
     if (!call_site->is_constant_call_site()) {
-      ciMethodHandle* target = call_site->get_target();
+      ciMethodHandle* target = con.as_object()->as_method_handle();
       Compile::current()->dependencies()->assert_call_site_target_value(call_site, target);
     }
   }
--- a/hotspot/src/share/vm/prims/jvm.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/prims/jvm.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -2967,14 +2967,7 @@
   JVMWrapper("JVM_Yield");
   if (os::dont_yield()) return;
   HOTSPOT_THREAD_YIELD();
-
-  // When ConvertYieldToSleep is off (default), this matches the classic VM use of yield.
-  // Critical for similar threading behaviour
-  if (ConvertYieldToSleep) {
-    os::sleep(thread, MinSleepInterval, false);
-  } else {
-    os::naked_yield();
-  }
+  os::naked_yield();
 JVM_END
 
 
@@ -2998,18 +2991,7 @@
   EventThreadSleep event;
 
   if (millis == 0) {
-    // When ConvertSleepToYield is on, this matches the classic VM implementation of
-    // JVM_Sleep. Critical for similar threading behaviour (Win32)
-    // It appears that in certain GUI contexts, it may be beneficial to do a short sleep
-    // for SOLARIS
-    if (ConvertSleepToYield) {
-      os::naked_yield();
-    } else {
-      ThreadState old_state = thread->osthread()->get_state();
-      thread->osthread()->set_state(SLEEPING);
-      os::sleep(thread, MinSleepInterval, false);
-      thread->osthread()->set_state(old_state);
-    }
+    os::naked_yield();
   } else {
     ThreadState old_state = thread->osthread()->get_state();
     thread->osthread()->set_state(SLEEPING);
--- a/hotspot/src/share/vm/prims/jvmtiExport.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/prims/jvmtiExport.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -1230,8 +1230,12 @@
     assert(thread->is_VM_thread(), "wrong thread");
 
     // get JavaThread for whom we are proxy
-    JavaThread *real_thread =
-        (JavaThread *)((VMThread *)thread)->vm_operation()->calling_thread();
+    Thread *calling_thread = ((VMThread *)thread)->vm_operation()->calling_thread();
+    if (!calling_thread->is_Java_thread()) {
+      // cannot post an event to a non-JavaThread
+      return;
+    }
+    JavaThread *real_thread = (JavaThread *)calling_thread;
 
     JvmtiEnvIterator it;
     for (JvmtiEnv* env = it.first(); env != NULL; env = it.next(env)) {
--- a/hotspot/src/share/vm/prims/methodHandles.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/prims/methodHandles.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2017, 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
@@ -1208,9 +1208,10 @@
     if (reference_klass != NULL && reference_klass->is_instance_klass()) {
       // Emulate LinkResolver::check_klass_accessability.
       Klass* caller = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(caller_jh));
-      if (Reflection::verify_class_access(caller,
-                                          reference_klass,
-                                          true) != Reflection::ACCESS_OK) {
+      if (caller != SystemDictionary::Object_klass()
+          && Reflection::verify_class_access(caller,
+                                             reference_klass,
+                                             true) != Reflection::ACCESS_OK) {
         THROW_MSG_NULL(vmSymbols::java_lang_InternalError(), reference_klass->external_name());
       }
     }
--- a/hotspot/src/share/vm/prims/stackwalk.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/prims/stackwalk.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -173,7 +173,11 @@
   }
 }
 
-oop LiveFrameStream::create_primitive_value_instance(StackValueCollection* values, int i, TRAPS) {
+// Create and return a LiveStackFrame.PrimitiveSlot (if needed) for the
+// StackValue at the given index. 'type' is expected to be T_INT, T_LONG,
+// T_OBJECT, or T_CONFLICT.
+oop LiveFrameStream::create_primitive_slot_instance(StackValueCollection* values,
+                                                    int i, BasicType type, TRAPS) {
   Klass* k = SystemDictionary::resolve_or_null(vmSymbols::java_lang_LiveStackFrameInfo(), CHECK_NULL);
   instanceKlassHandle ik (THREAD, k);
 
@@ -182,8 +186,8 @@
   Symbol* signature = NULL;
 
   // ## TODO: type is only available in LocalVariable table, if present.
-  // ## StackValue type is T_INT or T_OBJECT.
-  switch (values->at(i)->type()) {
+  // ## StackValue type is T_INT or T_OBJECT (or converted to T_LONG on 64-bit)
+  switch (type) {
     case T_INT:
       args.push_int(values->int_at(i));
       signature = vmSymbols::asPrimitive_int_signature();
@@ -195,42 +199,26 @@
       break;
 
     case T_FLOAT:
-      args.push_float(values->float_at(i));
-      signature = vmSymbols::asPrimitive_float_signature();
-      break;
-
     case T_DOUBLE:
-      args.push_double(values->double_at(i));
-      signature = vmSymbols::asPrimitive_double_signature();
-      break;
-
     case T_BYTE:
-      args.push_int(values->int_at(i));
-      signature = vmSymbols::asPrimitive_byte_signature();
-      break;
-
     case T_SHORT:
-      args.push_int(values->int_at(i));
-      signature = vmSymbols::asPrimitive_short_signature();
-      break;
-
     case T_CHAR:
-      args.push_int(values->int_at(i));
-      signature = vmSymbols::asPrimitive_char_signature();
-      break;
-
     case T_BOOLEAN:
-      args.push_int(values->int_at(i));
-      signature = vmSymbols::asPrimitive_boolean_signature();
-      break;
+      THROW_MSG_(vmSymbols::java_lang_InternalError(), "Unexpected StackValue type", NULL);
 
     case T_OBJECT:
       return values->obj_at(i)();
 
     case T_CONFLICT:
       // put a non-null slot
-      args.push_int(0);
-      signature = vmSymbols::asPrimitive_int_signature();
+      #ifdef _LP64
+        args.push_long(0);
+        signature = vmSymbols::asPrimitive_long_signature();
+      #else
+        args.push_int(0);
+        signature = vmSymbols::asPrimitive_int_signature();
+      #endif
+
       break;
 
     default: ShouldNotReachHere();
@@ -252,9 +240,19 @@
   objArrayHandle array_h(THREAD, array_oop);
   for (int i = 0; i < values->size(); i++) {
     StackValue* st = values->at(i);
-    oop obj = create_primitive_value_instance(values, i, CHECK_(empty));
-    if (obj != NULL)
+    BasicType type = st->type();
+    int index = i;
+#ifdef _LP64
+    if (type != T_OBJECT && type != T_CONFLICT) {
+        intptr_t ret = st->get_int(); // read full 64-bit slot
+        type = T_LONG;                // treat as long
+        index--;                      // undo +1 in StackValueCollection::long_at
+    }
+#endif
+    oop obj = create_primitive_slot_instance(values, index, type, CHECK_(empty));
+    if (obj != NULL) {
       array_h->obj_at_put(i, obj);
+    }
   }
   return array_h;
 }
@@ -286,6 +284,13 @@
     StackValueCollection* expressions = _jvf->expressions();
     GrowableArray<MonitorInfo*>* monitors = _jvf->monitors();
 
+    int mode = 0;
+    if (_jvf->is_interpreted_frame()) {
+      mode = MODE_INTERPRETED;
+    } else if (_jvf->is_compiled_frame()) {
+      mode = MODE_COMPILED;
+    }
+
     if (!locals->is_empty()) {
       objArrayHandle locals_h = values_to_object_array(locals, CHECK);
       java_lang_LiveStackFrameInfo::set_locals(stackFrame(), locals_h());
@@ -298,6 +303,7 @@
       objArrayHandle monitors_h = monitors_to_object_array(monitors, CHECK);
       java_lang_LiveStackFrameInfo::set_monitors(stackFrame(), monitors_h());
     }
+    java_lang_LiveStackFrameInfo::set_mode(stackFrame(), mode);
   }
 }
 
--- a/hotspot/src/share/vm/prims/stackwalk.hpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/prims/stackwalk.hpp	Thu Mar 16 20:47:03 2017 +0000
@@ -92,11 +92,16 @@
 
 class LiveFrameStream : public BaseFrameStream {
 private:
+  enum {
+    MODE_INTERPRETED = 0x01,
+    MODE_COMPILED    = 0x02
+  };
+
   javaVFrame*           _jvf;
 
   void fill_live_stackframe(Handle stackFrame, const methodHandle& method, TRAPS);
-  static oop create_primitive_value_instance(StackValueCollection* values,
-                                             int i, TRAPS);
+  static oop create_primitive_slot_instance(StackValueCollection* values,
+                                            int i, BasicType type, TRAPS);
   static objArrayHandle monitors_to_object_array(GrowableArray<MonitorInfo*>* monitors,
                                                  TRAPS);
   static objArrayHandle values_to_object_array(StackValueCollection* values, TRAPS);
--- a/hotspot/src/share/vm/runtime/arguments.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/runtime/arguments.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -375,53 +375,17 @@
   // -------------- Deprecated Flags --------------
   // --- Non-alias flags - sorted by obsolete_in then expired_in:
   { "MaxGCMinorPauseMillis",        JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },
-  { "AutoGCSelectPauseMillis",      JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
-  { "UseAutoGCSelectPolicy",        JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
-  { "UseParNewGC",                  JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
-  { "ExplicitGCInvokesConcurrentAndUnloadsClasses", JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
-  { "ConvertSleepToYield",          JDK_Version::jdk(9), JDK_Version::jdk(10),     JDK_Version::jdk(11) },
-  { "ConvertYieldToSleep",          JDK_Version::jdk(9), JDK_Version::jdk(10),     JDK_Version::jdk(11) },
 
   // --- Deprecated alias flags (see also aliased_jvm_flags) - sorted by obsolete_in then expired_in:
   { "DefaultMaxRAMFraction",        JDK_Version::jdk(8), JDK_Version::undefined(), JDK_Version::undefined() },
   { "CreateMinidumpOnCrash",        JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::undefined() },
-  { "CMSMarkStackSizeMax",          JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
-  { "CMSMarkStackSize",             JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
-  { "G1MarkStackSize",              JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
-  { "ParallelMarkingThreads",       JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
-  { "ParallelCMSThreads",           JDK_Version::jdk(9), JDK_Version::undefined(), JDK_Version::jdk(10) },
 
   // -------------- Obsolete Flags - sorted by expired_in --------------
-  { "UseOldInlining",                JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "SafepointPollOffset",           JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "UseBoundThreads",               JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "DefaultThreadPriority",         JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "NoYieldsInMicrolock",           JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "BackEdgeThreshold",             JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "UseNewReflection",              JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "ReflectionWrapResolutionErrors",JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "VerifyReflectionBytecodes",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "AutoShutdownNMT",               JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "NmethodSweepFraction",          JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "NmethodSweepCheckInterval",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "CodeCacheMinimumFreeSpace",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-#ifndef ZERO
-  { "UseFastAccessorMethods",        JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "UseFastEmptyMethods",           JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-#endif // ZERO
-  { "UseCompilerSafepoints",         JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "AdaptiveSizePausePolicy",       JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "ParallelGCRetainPLAB",          JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "ThreadSafetyMargin",            JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "LazyBootClassLoader",           JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "StarvationMonitorInterval",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "PreInflateSpin",                JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "JNIDetachReleasesMonitors",     JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "UseAltSigs",                    JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "SegmentedHeapDumpThreshold",    JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "PrintOopAddress",               JDK_Version::undefined(), JDK_Version::jdk(9), JDK_Version::jdk(10) },
-  { "PermSize",                      JDK_Version::undefined(), JDK_Version::jdk(8), JDK_Version::jdk(10) },
-  { "MaxPermSize",                   JDK_Version::undefined(), JDK_Version::jdk(8), JDK_Version::jdk(10) },
+  { "ConvertSleepToYield",           JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
+  { "ConvertYieldToSleep",           JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
+  { "MinSleepInterval",              JDK_Version::jdk(9),      JDK_Version::jdk(10), JDK_Version::jdk(11) },
+  { "PermSize",                      JDK_Version::undefined(), JDK_Version::jdk(8),  JDK_Version::undefined() },
+  { "MaxPermSize",                   JDK_Version::undefined(), JDK_Version::jdk(8),  JDK_Version::undefined() },
 
 #ifdef TEST_VERIFY_SPECIAL_JVM_FLAGS
   { "dep > obs",                    JDK_Version::jdk(9), JDK_Version::jdk(8), JDK_Version::undefined() },
@@ -444,11 +408,6 @@
 
 static AliasedFlag const aliased_jvm_flags[] = {
   { "DefaultMaxRAMFraction",    "MaxRAMFraction"    },
-  { "CMSMarkStackSizeMax",      "MarkStackSizeMax"  },
-  { "CMSMarkStackSize",         "MarkStackSize"     },
-  { "G1MarkStackSize",          "MarkStackSize"     },
-  { "ParallelMarkingThreads",   "ConcGCThreads"     },
-  { "ParallelCMSThreads",       "ConcGCThreads"     },
   { "CreateMinidumpOnCrash",    "CreateCoredumpOnCrash" },
   { NULL, NULL}
 };
@@ -1547,7 +1506,6 @@
   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC && !UseG1GC,
          "control point invariant");
   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
-  assert(UseParNewGC, "ParNew should always be used with CMS");
 
   if (FLAG_IS_DEFAULT(ParallelGCThreads)) {
     FLAG_SET_DEFAULT(ParallelGCThreads, Abstract_VM_Version::parallel_worker_threads());
@@ -1588,7 +1546,6 @@
 void Arguments::set_cms_and_parnew_gc_flags() {
   assert(!UseSerialGC && !UseParallelOldGC && !UseParallelGC, "Error");
   assert(UseConcMarkSweepGC, "CMS is expected to be on here");
-  assert(UseParNewGC, "ParNew should always be used with CMS");
 
   // Turn off AdaptiveSizePolicy by default for cms until it is complete.
   disable_adaptive_size_policy("UseConcMarkSweepGC");
@@ -1728,16 +1685,6 @@
   NOT_LP64(ShouldNotReachHere(); return 0);
 }
 
-bool Arguments::should_auto_select_low_pause_collector() {
-  if (UseAutoGCSelectPolicy &&
-      !FLAG_IS_DEFAULT(MaxGCPauseMillis) &&
-      (MaxGCPauseMillis <= AutoGCSelectPauseMillis)) {
-    log_trace(gc)("Automatic selection of the low pause collector based on pause goal of %d (ms)", (int) MaxGCPauseMillis);
-    return true;
-  }
-  return false;
-}
-
 void Arguments::set_use_compressed_oops() {
 #ifndef ZERO
 #ifdef _LP64
@@ -1841,16 +1788,7 @@
 void Arguments::select_gc_ergonomically() {
 #if INCLUDE_ALL_GCS
   if (os::is_server_class_machine()) {
-    if (!UseAutoGCSelectPolicy) {
-       FLAG_SET_ERGO_IF_DEFAULT(bool, UseG1GC, true);
-    } else {
-      if (should_auto_select_low_pause_collector()) {
-        FLAG_SET_ERGO_IF_DEFAULT(bool, UseConcMarkSweepGC, true);
-        FLAG_SET_ERGO_IF_DEFAULT(bool, UseParNewGC, true);
-      } else {
-        FLAG_SET_ERGO_IF_DEFAULT(bool, UseParallelGC, true);
-      }
-    }
+    FLAG_SET_ERGO_IF_DEFAULT(bool, UseG1GC, true);
   } else {
     FLAG_SET_ERGO_IF_DEFAULT(bool, UseSerialGC, true);
   }
@@ -1859,7 +1797,6 @@
   UNSUPPORTED_OPTION(UseParallelGC);
   UNSUPPORTED_OPTION(UseParallelOldGC);
   UNSUPPORTED_OPTION(UseConcMarkSweepGC);
-  UNSUPPORTED_OPTION(UseParNewGC);
   FLAG_SET_ERGO_IF_DEFAULT(bool, UseSerialGC, true);
 #endif // INCLUDE_ALL_GCS
 }
@@ -2073,7 +2010,6 @@
   if (!ClassUnloading) {
     FLAG_SET_CMDLINE(bool, CMSClassUnloadingEnabled, false);
     FLAG_SET_CMDLINE(bool, ClassUnloadingWithConcurrentMark, false);
-    FLAG_SET_CMDLINE(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false);
   }
 #endif // INCLUDE_ALL_GCS
 }
@@ -2428,18 +2364,6 @@
     return false;
   }
 
-  if (UseConcMarkSweepGC && !UseParNewGC) {
-    jio_fprintf(defaultStream::error_stream(),
-        "It is not possible to combine the DefNew young collector with the CMS collector.\n");
-    return false;
-  }
-
-  if (UseParNewGC && !UseConcMarkSweepGC) {
-    jio_fprintf(defaultStream::error_stream(),
-        "It is not possible to combine the ParNew young collector with any collector other than CMS.\n");
-    return false;
-  }
-
   return true;
 }
 
@@ -3726,11 +3650,6 @@
     }
   }
 
-  if (UseConcMarkSweepGC && FLAG_IS_DEFAULT(UseParNewGC) && !UseParNewGC) {
-    // CMS can only be used with ParNew
-    FLAG_SET_ERGO(bool, UseParNewGC, true);
-  }
-
   if (!check_vm_args_consistency()) {
     return JNI_ERR;
   }
--- a/hotspot/src/share/vm/runtime/arguments.hpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/runtime/arguments.hpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -480,9 +480,6 @@
   static julong limit_by_allocatable_memory(julong size);
   // Setup heap size
   static void set_heap_size();
-  // Based on automatic selection criteria, should the
-  // low pause collector be used.
-  static bool should_auto_select_low_pause_collector();
 
   // Bytecode rewriting
   static void set_bytecode_flags();
--- a/hotspot/src/share/vm/runtime/globals.hpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/src/share/vm/runtime/globals.hpp	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -1159,13 +1159,6 @@
   product_pd(bool, DontYieldALot,                                           \
           "Throw away obvious excess yield calls")                          \
                                                                             \
-  product(bool, ConvertSleepToYield, true,                                  \
-          "Convert sleep(0) to thread yield ")                              \
-                                                                            \
-  product(bool, ConvertYieldToSleep, false,                                 \
-          "Convert yield to a sleep of MinSleepInterval to simulate Win32 " \
-          "behavior")                                                       \
-                                                                            \
   develop(bool, UseDetachedThreads, true,                                   \
           "Use detached threads that are recycled upon termination "        \
           "(for Solaris only)")                                             \
@@ -1479,11 +1472,6 @@
           "A System.gc() request invokes a concurrent collection; "         \
           "(effective only when using concurrent collectors)")              \
                                                                             \
-  product(bool, ExplicitGCInvokesConcurrentAndUnloadsClasses, false,        \
-          "A System.gc() request invokes a concurrent collection and "      \
-          "also unloads classes during such a concurrent gc cycle "         \
-          "(effective only when UseConcMarkSweepGC)")                       \
-                                                                            \
   product(bool, GCLockerInvokesConcurrent, false,                           \
           "The exit of a JNI critical section necessitating a scavenge, "   \
           "also kicks off a background concurrent collection")              \
@@ -1501,9 +1489,6 @@
   product(bool, UseCMSBestFit, true,                                        \
           "Use CMS best fit allocation strategy")                           \
                                                                             \
-  product(bool, UseParNewGC, false,                                         \
-          "Use parallel threads in the new generation")                     \
-                                                                            \
   product(uintx, ParallelGCBufferWastePct, 10,                              \
           "Wasted fraction of parallel allocation buffer")                  \
           range(0, 100)                                                     \
@@ -2059,13 +2044,6 @@
           "Maximum fraction (1/n) of virtual memory used for ergonomically "\
           "determining maximum heap size")                                  \
                                                                             \
-  product(bool, UseAutoGCSelectPolicy, false,                               \
-          "Use automatic collection selection policy")                      \
-                                                                            \
-  product(uintx, AutoGCSelectPauseMillis, 5000,                             \
-          "Automatic GC selection pause threshold in milliseconds")         \
-          range(0, max_uintx)                                               \
-                                                                            \
   product(bool, UseAdaptiveSizePolicy, true,                                \
           "Use adaptive generation sizing policies")                        \
                                                                             \
@@ -3003,10 +2981,6 @@
   develop(intx, DontYieldALotInterval,    10,                               \
           "Interval between which yields will be dropped (milliseconds)")   \
                                                                             \
-  develop(intx, MinSleepInterval,     1,                                    \
-          "Minimum sleep() interval (milliseconds) when "                   \
-          "ConvertSleepToYield is off (used for Solaris)")                  \
-                                                                            \
   develop(intx, ProfilerPCTickThreshold,    15,                             \
           "Number of ticks in a PC buckets to be a hotspot")                \
                                                                             \
--- a/hotspot/test/ProblemList.txt	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/ProblemList.txt	Thu Mar 16 20:47:03 2017 +0000
@@ -73,6 +73,7 @@
 
 serviceability/jdwp/AllModulesCommandTest.java 8168478 generic-all
 serviceability/sa/sadebugd/SADebugDTest.java 8163805 generic-all
+serviceability/jvmti/ModuleAwareAgents/ClassFileLoadHook/MAAClassFileLoadHook.java 8173936 generic-all
 
 #############################################################################
 
--- a/hotspot/test/TEST.groups	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/TEST.groups	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2013, 2017, 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
@@ -209,11 +209,8 @@
   gc/g1/TestShrinkToOneRegion.java \
   gc/metaspace/G1AddMetaspaceDependency.java \
   gc/startup_warnings/TestCMS.java \
-  gc/startup_warnings/TestDefNewCMS.java \
   gc/startup_warnings/TestParallelGC.java \
   gc/startup_warnings/TestParallelScavengeSerialOld.java \
-  gc/startup_warnings/TestParNewCMS.java \
-  gc/startup_warnings/TestParNewSerialOld.java \
   runtime/SharedArchiveFile/SharedArchiveFile.java
 
 # Minimal VM on Compact 2 adds in some compact2 tests
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/c1/TestUnresolvedField.jasm	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 2017, 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.
+ *
+ */
+
+public class compiler/c1/TestUnresolvedField version 52:0 {
+    public static Method testGetField:"()V" stack 1 locals 1 {
+        aconst_null;
+        getfield Field T.f:I; // T does not exist
+        return;
+    }
+
+    public static Method testPutField:"()V" stack 2 locals 1 {
+        aconst_null;
+        iconst_0;
+        putfield Field T.f:I; // T does not exist
+        return;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/compiler/c1/TestUnresolvedFieldMain.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,48 @@
+/*
+ * Copyright (c) 2017, 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 8173373
+ * @compile TestUnresolvedField.jasm
+ * @run main/othervm -XX:TieredStopAtLevel=1 -Xcomp
+ *                   -XX:CompileCommand=compileonly,compiler.c1.TestUnresolvedField::test*
+ *                   compiler.c1.TestUnresolvedFieldMain
+ */
+
+package compiler.c1;
+
+public class TestUnresolvedFieldMain {
+    public static void main(String[] args) {
+        try {
+          TestUnresolvedField.testGetField();
+        } catch (java.lang.NoClassDefFoundError error) {
+          // Expected
+        }
+        try {
+          TestUnresolvedField.testPutField();
+        } catch (java.lang.NoClassDefFoundError error) {
+          // Expected
+        }
+    }
+}
--- a/hotspot/test/compiler/jsr292/ContinuousCallSiteTargetChange.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/compiler/jsr292/ContinuousCallSiteTargetChange.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,7 +23,6 @@
 
 /**
  * @test
- * @modules java.base/jdk.internal.misc
  * @library /test/lib /
  *
  * @run driver compiler.jsr292.ContinuousCallSiteTargetChange
@@ -31,6 +30,7 @@
 
 package compiler.jsr292;
 
+import jdk.test.lib.Asserts;
 import jdk.test.lib.process.OutputAnalyzer;
 import jdk.test.lib.process.ProcessTools;
 
@@ -39,15 +39,26 @@
 import java.lang.invoke.MethodHandles;
 import java.lang.invoke.MethodType;
 import java.lang.invoke.MutableCallSite;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
 
 public class ContinuousCallSiteTargetChange {
-    static void testServer() throws Exception {
+    static final int ITERATIONS = Integer.parseInt(System.getProperty("iterations", "50"));
+
+    static void runTest(Class<?> test, String... extraArgs) throws Exception {
+        List<String> argsList = new ArrayList<>(
+                List.of("-XX:+IgnoreUnrecognizedVMOptions",
+                    "-XX:PerBytecodeRecompilationCutoff=10", "-XX:PerMethodRecompilationCutoff=10",
+                    "-XX:+PrintCompilation", "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining"));
+
+        argsList.addAll(Arrays.asList(extraArgs));
+
+        argsList.add(test.getName());
+        argsList.add(Integer.toString(ITERATIONS));
+
         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
-                "-XX:+IgnoreUnrecognizedVMOptions",
-                "-server", "-XX:-TieredCompilation", "-Xbatch",
-                "-XX:PerBytecodeRecompilationCutoff=10", "-XX:PerMethodRecompilationCutoff=10",
-                "-XX:+PrintCompilation", "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining",
-                Test.class.getName(), "100");
+                argsList.toArray(new String[argsList.size()]));
 
         OutputAnalyzer analyzer = new OutputAnalyzer(pb.start());
 
@@ -55,30 +66,42 @@
 
         analyzer.shouldNotContain("made not compilable");
         analyzer.shouldNotContain("decompile_count > PerMethodRecompilationCutoff");
+
     }
 
-    static void testClient() throws Exception {
-        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
-                "-XX:+IgnoreUnrecognizedVMOptions",
-                "-client", "-XX:+TieredCompilation", "-XX:TieredStopAtLevel=1", "-Xbatch",
-                "-XX:PerBytecodeRecompilationCutoff=10", "-XX:PerMethodRecompilationCutoff=10",
-                "-XX:+PrintCompilation", "-XX:+UnlockDiagnosticVMOptions", "-XX:+PrintInlining",
-                Test.class.getName(), "100");
+    static void testServer(Class<?> test, String... args) throws Exception {
+        List<String> extraArgsList = new ArrayList<>(
+                List.of("-server", "-XX:-TieredCompilation"));
+        extraArgsList.addAll(Arrays.asList(args));
 
-        OutputAnalyzer analyzer = new OutputAnalyzer(pb.start());
+        runTest(test, extraArgsList.toArray(new String[extraArgsList.size()]));
+    }
 
-        analyzer.shouldHaveExitValue(0);
+    static void testClient(Class<?> test, String... args) throws Exception {
+        List<String> extraArgsList = new ArrayList<>(
+                List.of("-client", "-XX:+TieredCompilation", "-XX:TieredStopAtLevel=1"));
+        extraArgsList.addAll(Arrays.asList(args));
 
-        analyzer.shouldNotContain("made not compilable");
-        analyzer.shouldNotContain("decompile_count > PerMethodRecompilationCutoff");
+        runTest(test, extraArgsList.toArray(new String[extraArgsList.size()]));
     }
 
     public static void main(String[] args) throws Exception {
-        testServer();
-        testClient();
+        testServer(RecompilationTest.class, "-Xbatch");
+        testClient(RecompilationTest.class, "-Xbatch");
+
+        testServer(PingPongTest.class);
+        testClient(PingPongTest.class);
     }
 
-    static class Test {
+    static MethodHandle findStatic(Class<?> cls, String name, MethodType mt) {
+        try {
+            return MethodHandles.lookup().findStatic(cls, name, mt);
+        } catch (Exception e) {
+            throw new Error(e);
+        }
+    }
+
+    static class RecompilationTest {
         static final MethodType mt = MethodType.methodType(void.class);
         static final CallSite cs = new MutableCallSite(mt);
 
@@ -96,7 +119,7 @@
         }
 
         static void iteration() throws Throwable {
-            MethodHandle mh1 = MethodHandles.lookup().findStatic(ContinuousCallSiteTargetChange.Test.class, "f", mt);
+            MethodHandle mh1 = findStatic(RecompilationTest.class, "f", mt);
             cs.setTarget(mh1);
             for (int i = 0; i < 20_000; i++) {
                 test1();
@@ -111,4 +134,38 @@
             }
         }
     }
+
+    static class PingPongTest {
+        static final MethodType mt = MethodType.methodType(void.class);
+        static final CallSite cs = new MutableCallSite(mt);
+
+        static final MethodHandle mh = cs.dynamicInvoker();
+
+        static final MethodHandle ping = findStatic(PingPongTest.class, "ping", mt);
+        static final MethodHandle pong = findStatic(PingPongTest.class, "pong", mt);
+
+        static void ping() {
+            Asserts.assertEQ(cs.getTarget(), ping, "wrong call site target");
+            cs.setTarget(pong);
+        }
+
+        static void pong() {
+            Asserts.assertEQ(cs.getTarget(), pong, "wrong call site target");
+            cs.setTarget(ping);
+        }
+
+        static void iteration() throws Throwable {
+            cs.setTarget(ping);
+            for (int i = 0; i < 20_000; i++) {
+                mh.invokeExact();
+            }
+        }
+
+        public static void main(String[] args) throws Throwable {
+            int iterations = Integer.parseInt(args[0]);
+            for (int i = 0; i < iterations; i++) {
+                iteration();
+            }
+        }
+    }
 }
--- a/hotspot/test/compiler/jsr292/patches/java.base/java/lang/invoke/MethodHandleHelper.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/compiler/jsr292/patches/java.base/java/lang/invoke/MethodHandleHelper.java	Thu Mar 16 20:47:03 2017 +0000
@@ -84,7 +84,7 @@
 
         public static MethodHandle make(MethodHandle target) {
             LambdaForm lform = DelegatingMethodHandle.makeReinvokerForm(
-                    target, -1, DelegatingMethodHandle.class, "reinvoker.dontInline",
+                    target, -1, DelegatingMethodHandle.class,
                 /*forceInline=*/false, DelegatingMethodHandle.NF_getTarget, null);
             return new NonInlinedReinvoker(target, lform);
         }
--- a/hotspot/test/compiler/jvmci/compilerToVM/MaterializeVirtualObjectTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/compiler/jvmci/compilerToVM/MaterializeVirtualObjectTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -44,6 +44,8 @@
  *                   -XX:+UnlockExperimentalVMOptions -XX:+EnableJVMCI
  *                   -XX:CompileCommand=exclude,*::check
  *                   -XX:+DoEscapeAnalysis -XX:-UseCounterDecay
+ *                   -XX:CompileCommand=dontinline,compiler/jvmci/compilerToVM/MaterializeVirtualObjectTest,testFrame
+ *                   -XX:CompileCommand=inline,compiler/jvmci/compilerToVM/MaterializeVirtualObjectTest,recurse
  *                   -Xbatch
  *                   -Dcompiler.jvmci.compilerToVM.MaterializeVirtualObjectTest.invalidate=false
  *                   compiler.jvmci.compilerToVM.MaterializeVirtualObjectTest
@@ -119,14 +121,25 @@
         }
         Asserts.assertTrue(WB.isMethodCompiled(METHOD), getName()
                 + "Method unexpectedly not compiled");
+        Asserts.assertTrue(WB.getMethodCompilationLevel(METHOD) == 4, getName()
+                + "Method not compiled at level 4");
         testFrame("someString", COMPILE_THRESHOLD);
     }
 
     private void testFrame(String str, int iteration) {
         Helper helper = new Helper(str);
-        check(iteration);
+        recurse(2, iteration);
         Asserts.assertTrue((helper.string != null) && (this != null)
-                && (helper != null), getName() + " : some locals are null");
+                           && (helper != null), String.format("%s : some locals are null", getName()));
+    }
+    private void recurse(int depth, int iteration) {
+        if (depth == 0) {
+            check(iteration);
+        } else {
+            Integer s = new Integer(depth);
+            recurse(depth - 1, iteration);
+            Asserts.assertEQ(s.intValue(), depth, String.format("different values: %s != %s", s.intValue(), depth));
+        }
     }
 
     private void check(int iteration) {
--- a/hotspot/test/gc/arguments/TestExplicitGCInvokesConcurrentAndUnloadsClasses.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,48 +0,0 @@
-/*
- * 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.
- */
-
-/*
- * @test TestExplicitGCInvokesConcurrentAndUnloadsClasses
- * @summary Test that the flag ExplicitGCInvokesConcurrentAndUnloadsClasses is deprecated
- * @bug 8170388
- * @key gc
- * @library /test/lib
- * @modules java.base/jdk.internal.misc
- *          java.management
- * @run driver TestExplicitGCInvokesConcurrentAndUnloadsClasses
- */
-
-import jdk.test.lib.process.OutputAnalyzer;
-import jdk.test.lib.process.ProcessTools;
-
-public class TestExplicitGCInvokesConcurrentAndUnloadsClasses {
-    public static void main(String[] args) throws Exception {
-        ProcessBuilder pb =
-            ProcessTools.createJavaProcessBuilder("-XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses",
-                                                  "-Xlog:gc",
-                                                  "-version");
-        OutputAnalyzer output = new OutputAnalyzer(pb.start());
-        output.shouldContain("ExplicitGCInvokesConcurrentAndUnloadsClasses was deprecated");
-        output.shouldHaveExitValue(0);
-    }
-}
--- a/hotspot/test/gc/arguments/TestSelectDefaultGC.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/gc/arguments/TestSelectDefaultGC.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -66,7 +66,6 @@
         assertVMOption(output, "UseSerialGC",        !isServer);
         // CMS is never default
         assertVMOption(output, "UseConcMarkSweepGC", false);
-        assertVMOption(output, "UseParNewGC",        false);
     }
 
     public static void main(String[] args) throws Exception {
--- a/hotspot/test/gc/startup_warnings/TestDefNewCMS.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,47 +0,0 @@
-/*
- * 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
- * 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 TestDefNewCMS
-* @key gc
-* @bug 8065972
-* @summary Test that the unsupported DefNew+CMS combination does not start
-* @library /test/lib
-* @modules java.base/jdk.internal.misc
-*          java.management
-*/
-
-import jdk.test.lib.process.ProcessTools;
-import jdk.test.lib.process.OutputAnalyzer;
-
-public class TestDefNewCMS {
-
-  public static void main(String args[]) throws Exception {
-    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:-UseParNewGC", "-XX:+UseConcMarkSweepGC", "-version");
-    OutputAnalyzer output = new OutputAnalyzer(pb.start());
-    output.shouldContain("It is not possible to combine the DefNew young collector with the CMS collector.");
-    output.shouldContain("Error");
-    output.shouldHaveExitValue(1);
-  }
-
-}
--- a/hotspot/test/gc/startup_warnings/TestParNewCMS.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,48 +0,0 @@
-/*
- * 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
- * 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 TestParNewCMS
-* @key gc
-* @bug 8065972
-* @summary Test that specifying -XX:+UseParNewGC on the command line logs a warning message
-* @library /test/lib
-* @modules java.base/jdk.internal.misc
-*          java.management
-*/
-
-import jdk.test.lib.process.ProcessTools;
-import jdk.test.lib.process.OutputAnalyzer;
-
-
-public class TestParNewCMS {
-
-  public static void main(String args[]) throws Exception {
-    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseParNewGC", "-XX:+UseConcMarkSweepGC", "-version");
-    OutputAnalyzer output = new OutputAnalyzer(pb.start());
-    output.shouldContain("warning: Option UseParNewGC was deprecated in version");
-    output.shouldNotContain("error");
-    output.shouldHaveExitValue(0);
-  }
-
-}
--- a/hotspot/test/gc/startup_warnings/TestParNewSerialOld.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,48 +0,0 @@
-/*
- * 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
- * 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 TestParNewSerialOld
-* @key gc
-* @bug 8065972
-* @summary Test that the unsupported ParNew+SerialOld combination does not start
-* @library /test/lib
-* @modules java.base/jdk.internal.misc
-*          java.management
-*/
-
-import jdk.test.lib.process.ProcessTools;
-import jdk.test.lib.process.OutputAnalyzer;
-
-
-public class TestParNewSerialOld {
-
-  public static void main(String args[]) throws Exception {
-    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseParNewGC", "-version");
-    OutputAnalyzer output = new OutputAnalyzer(pb.start());
-    output.shouldContain("It is not possible to combine the ParNew young collector with any collector other than CMS.");
-    output.shouldContain("Error");
-    output.shouldHaveExitValue(1);
-  }
-
-}
--- a/hotspot/test/gc/startup_warnings/TestUseAutoGCSelectPolicy.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,47 +0,0 @@
-/*
- * 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.
- */
-
-/*
- * @test TestUseAutoGCSelectPolicy
- * @key gc
- * @bug 8166461 8167494
- * @summary Test that UseAutoGCSelectPolicy and AutoGCSelectPauseMillis do print a warning message
- * @library /test/lib
- * @modules java.base/jdk.internal.misc
- *          java.management
- */
-
-import jdk.test.lib.process.ProcessTools;
-import jdk.test.lib.process.OutputAnalyzer;
-
-public class TestUseAutoGCSelectPolicy {
-
-  public static void main(String args[]) throws Exception {
-    ProcessBuilder pb = ProcessTools.createJavaProcessBuilder("-XX:+UseAutoGCSelectPolicy", "-XX:AutoGCSelectPauseMillis=3000", "-version");
-    OutputAnalyzer output = new OutputAnalyzer(pb.start());
-    output.shouldContain("UseAutoGCSelectPolicy was deprecated in version 9.0");
-    output.shouldContain("AutoGCSelectPauseMillis was deprecated in version 9.0");
-    output.shouldNotContain("error");
-    output.shouldHaveExitValue(0);
-  }
-}
--- a/hotspot/test/runtime/CommandLine/ObsoleteFlagErrorMessage.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/CommandLine/ObsoleteFlagErrorMessage.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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,18 +37,18 @@
 
     // Case 1: Newly obsolete flags with extra junk appended should not be treated as newly obsolete (8060449)
     ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
-        "-XX:UseOldInliningPlusJunk", "-version");
+        "-XX:ConvertSleepToYieldPlusJunk", "-version");
 
     OutputAnalyzer output = new OutputAnalyzer(pb.start());
-    output.shouldContain("Unrecognized VM option 'UseOldInliningPlusJunk'"); // Must identify bad option.
+    output.shouldContain("Unrecognized VM option 'ConvertSleepToYieldPlusJunk'"); // Must identify bad option.
     output.shouldHaveExitValue(1);
 
-    // Case 2: Newly obsolete integer-valued flags should be recognized as newly obsolete (8073989)
+    // Case 2: Newly obsolete flags should be recognized as newly obsolete (8073989)
     ProcessBuilder pb2 = ProcessTools.createJavaProcessBuilder(
-        "-XX:NmethodSweepFraction=10", "-version");
+        "-XX:+ConvertSleepToYield", "-version");
 
     OutputAnalyzer output2 = new OutputAnalyzer(pb2.start());
     output2.shouldContain("Ignoring option").shouldContain("support was removed");
-    output2.shouldContain("NmethodSweepFraction");
+    output2.shouldContain("ConvertSleepToYield");
   }
 }
--- a/hotspot/test/runtime/CommandLine/VMAliasOptions.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/CommandLine/VMAliasOptions.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -40,11 +40,6 @@
      */
     public static final String[][] ALIAS_OPTIONS = {
         {"DefaultMaxRAMFraction",   "MaxRAMFraction", "1032"},
-        {"CMSMarkStackSizeMax",     "MarkStackSizeMax", "1032"},
-        {"CMSMarkStackSize",        "MarkStackSize", "1032"},
-        {"G1MarkStackSize",         "MarkStackSize", "1032"},
-        {"ParallelMarkingThreads",  "ConcGCThreads", "2"},
-        {"ParallelCMSThreads",      "ConcGCThreads", "2"},
         {"CreateMinidumpOnCrash",   "CreateCoredumpOnCrash", "false" },
     };
 
--- a/hotspot/test/runtime/CommandLine/VMDeprecatedOptions.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/CommandLine/VMDeprecatedOptions.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,17 +41,9 @@
     public static final String[][] DEPRECATED_OPTIONS = {
         // deprecated non-alias flags:
         {"MaxGCMinorPauseMillis", "1032"},
-        {"UseParNewGC", "false"},
-        {"ConvertSleepToYield", "false" },
-        {"ConvertYieldToSleep", "false" },
 
         // deprecated alias flags (see also aliased_jvm_flags):
         {"DefaultMaxRAMFraction", "4"},
-        {"CMSMarkStackSizeMax", "1032"},
-        {"CMSMarkStackSize", "1032"},
-        {"G1MarkStackSize", "1032"},
-        {"ParallelMarkingThreads", "2"},
-        {"ParallelCMSThreads", "2"},
         {"CreateMinidumpOnCrash", "false"}
     };
 
--- a/hotspot/test/runtime/LocalLong/LocalLongHelper.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/LocalLong/LocalLongHelper.java	Thu Mar 16 20:47:03 2017 +0000
@@ -30,10 +30,10 @@
 
 public class LocalLongHelper {
     static StackWalker sw;
-    static Method intValue;
+    static Method longValue;
     static Method getLocals;
     static Class<?> primitiveValueClass;
-    static Method primitiveType;
+    static Method primitiveSize;
     static Method getMethodType;
     static Field memberName;
     static Field offset;
@@ -43,27 +43,29 @@
         new LocalLongHelper().longArg(0xC0FFEE, 0x1234567890ABCDEFL);
     }
 
-    // locals[2] contains the high byte of the long argument.
+    // locals[2] contains the unused slot of the long argument.
     public long longArg(int i, long l) throws Throwable {
         List<StackFrame> frames = sw.walk(s -> s.collect(Collectors.toList()));
         Object[] locals = (Object[]) getLocals.invoke(frames.get(0));
 
-        int locals_2 = (int) intValue.invoke(locals[2]);
-        if (locals_2 != 0){
-            throw new RuntimeException("Expected locals_2 == 0");
+        if (8 == (int) primitiveSize.invoke(locals[2])) { // Only test 64-bit
+            long locals_2 = (long) longValue.invoke(locals[2]);
+            if (locals_2 != 0){
+                throw new RuntimeException("Expected locals_2 == 0");
+            }
         }
         return l; // Don't want l to become a dead var
     }
 
     private static void setupReflectionStatics() throws Throwable {
         Class<?> liveStackFrameClass = Class.forName("java.lang.LiveStackFrame");
-        primitiveValueClass = Class.forName("java.lang.LiveStackFrame$PrimitiveValue");
+        primitiveValueClass = Class.forName("java.lang.LiveStackFrame$PrimitiveSlot");
 
         getLocals = liveStackFrameClass.getDeclaredMethod("getLocals");
         getLocals.setAccessible(true);
 
-        intValue = primitiveValueClass.getDeclaredMethod("intValue");
-        intValue.setAccessible(true);
+        longValue = primitiveValueClass.getDeclaredMethod("longValue");
+        longValue.setAccessible(true);
 
         Class<?> stackFrameInfoClass = Class.forName("java.lang.StackFrameInfo");
         memberName = stackFrameInfoClass.getDeclaredField("memberName");
@@ -80,20 +82,8 @@
         f.setAccessible(true);
         Object localsAndOperandsOption = f.get(null);
 
-        primitiveType = primitiveValueClass.getDeclaredMethod("type");
-        primitiveType.setAccessible(true);
-
+        primitiveSize = primitiveValueClass.getDeclaredMethod("size");
+        primitiveSize.setAccessible(true);
         sw = (StackWalker) ewsNI.invoke(null, java.util.Collections.emptySet(), localsAndOperandsOption);
     }
-
-    private static String type(Object o) throws Throwable {
-        if (primitiveValueClass.isInstance(o)) {
-            final char c = (char) primitiveType.invoke(o);
-            return String.valueOf(c);
-        } else if (o != null) {
-            return o.getClass().getName();
-        } else {
-            return "null";
-        }
-    }
 }
--- a/hotspot/test/runtime/NMT/AutoshutdownNMT.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,47 +0,0 @@
-/*
- * 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
- * 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
- * @key nmt
- * @summary Test for deprecated message if -XX:-AutoShutdownNMT is specified
- * @library /test/lib
- * @modules java.base/jdk.internal.misc
- *          java.management
- */
-
-import jdk.test.lib.process.ProcessTools;
-import jdk.test.lib.process.OutputAnalyzer;
-
-public class AutoshutdownNMT {
-
-    public static void main(String args[]) throws Exception {
-
-        ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
-                "-XX:NativeMemoryTracking=detail",
-                "-XX:-AutoShutdownNMT",
-                "-version");
-        OutputAnalyzer output = new OutputAnalyzer(pb.start());
-        output.shouldContain("Ignoring option AutoShutdownNMT");
-    }
-}
--- a/hotspot/test/runtime/modules/AccessCheck/AccessExportTwice.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/AccessExportTwice.java	Thu Mar 16 20:47:03 2017 +0000
@@ -68,7 +68,7 @@
         // Packages:          none
         // Packages exported: none
         ModuleDescriptor descriptor_first_mod =
-                ModuleDescriptor.module("first_mod")
+                ModuleDescriptor.newModule("first_mod")
                         .requires("java.base")
                         .requires("second_mod")
                         .build();
@@ -78,7 +78,7 @@
         // Packages:          p2
         // Packages exported: p2 is exported to first_mod
         ModuleDescriptor descriptor_second_mod =
-                ModuleDescriptor.module("second_mod")
+                ModuleDescriptor.newModule("second_mod")
                         .requires("java.base")
                         .exports("p2", Set.of("first_mod"))
                         .build();
@@ -89,7 +89,7 @@
         // Resolves "first_mod"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("first_mod"));
+                .resolve(finder, ModuleFinder.of(), Set.of("first_mod"));
 
         // Map each module to the same class loader
         Map<String, ClassLoader> map = new HashMap<>();
--- a/hotspot/test/runtime/modules/AccessCheck/AccessReadTwice.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/AccessReadTwice.java	Thu Mar 16 20:47:03 2017 +0000
@@ -66,9 +66,9 @@
         // Packages:          p1, p4
         // Packages exported: none
         ModuleDescriptor descriptor_first_mod =
-                ModuleDescriptor.module("first_mod")
+                ModuleDescriptor.newModule("first_mod")
                         .requires("java.base")
-                        .contains(Set.of("p1", "p4"))
+                        .packages(Set.of("p1", "p4"))
                         .build();
 
         // Define module:     second_mod
@@ -76,7 +76,7 @@
         // Packages:          p2
         // Packages exported: p2 is exported to first_mod
         ModuleDescriptor descriptor_second_mod =
-                ModuleDescriptor.module("second_mod")
+                ModuleDescriptor.newModule("second_mod")
                         .requires("java.base")
                         .exports("p2", Set.of("first_mod"))
                         .build();
@@ -87,7 +87,7 @@
         // Resolves "first_mod" and "second_mod"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("first_mod", "second_mod"));
+                .resolve(finder, ModuleFinder.of(), Set.of("first_mod", "second_mod"));
 
         // Map each module to this class loader
         Map<String, ClassLoader> map = new HashMap<>();
--- a/hotspot/test/runtime/modules/AccessCheck/CheckRead.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/CheckRead.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test that if module m1 can not read module m2, then class p1.c1
- *          in module m1 can not access p2.c2 in module m2.
+ * @summary Test that if module m1x can not read module m2x, then class p1.c1
+ *          in module m1x can not access p2.c2 in module m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MySameClassLoader.java
@@ -47,15 +47,15 @@
 import myloaders.MySameClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> packages p1
-//                  defines m2 --> packages p2
-//                  defines m3 --> packages p3
+// ClassLoader1 --> defines m1x --> packages p1
+//                  defines m2x --> packages p2
+//                  defines m3x --> packages p3
 //
-// m1 can not read m2
-// package p2 in m2 is exported to m1
+// m1x can not read m2x
+// package p2 in m2x is exported to m1x
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in m2.
-// Access denied since m1 can not read m2.
+// class p1.c1 defined in m1x tries to access p2.c2 defined in m2x.
+// Access denied since m1x can not read m2x.
 //
 public class CheckRead {
 
@@ -64,65 +64,65 @@
     // publicly defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m3
+        // Define module:     m1x
+        // Can read:          java.base, m3x
         // Packages:          p1
         // Packages exported: p1 is exported unqualifiedly
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m3")
+                        .requires("m3x")
                         .exports("p1")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
-        // Packages exported: p2 is exported to m1
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        // Packages exported: p2 is exported to m1x
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .exports("p2", Set.of("m1"))
+                        .exports("p2", Set.of("m1x"))
                         .build();
 
-        // Define module:     m3
-        // Can read:          java.base, m2
+        // Define module:     m3x
+        // Can read:          java.base, m2x
         // Packages:          p3
         // Packages exported: none
-        ModuleDescriptor descriptor_m3 =
-                ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor_m3x =
+                ModuleDescriptor.newModule("m3x")
                         .requires("java.base")
-                        .requires("m2")
-                        .contains("p3")
+                        .requires("m2x")
+                        .packages(Set.of("p3"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2, descriptor_m3);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x, descriptor_m3x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MySameClassLoader.loader1);
-        map.put("m2", MySameClassLoader.loader1);
-        map.put("m3", MySameClassLoader.loader1);
+        map.put("m1x", MySameClassLoader.loader1);
+        map.put("m2x", MySameClassLoader.loader1);
+        map.put("m3x", MySameClassLoader.loader1);
 
-        // Create Layer that contains m1, m2 and m3
+        // Create Layer that contains m1x, m2x and m3x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m3") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m1x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m3x") == MySameClassLoader.loader1);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
         Class p1_c1_class = MySameClassLoader.loader1.loadClass("p1.c1");
         try {
             p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p2 in m2 is exported to m1 but m2 is not readable from m1)");
+            throw new RuntimeException("Failed to get IAE (p2 in m2x is exported to m1x but m2x is not readable from m1x)");
         } catch (IllegalAccessError e) {
             System.out.println(e.getMessage());
             if (!e.getMessage().contains("cannot access")) {
--- a/hotspot/test/runtime/modules/AccessCheck/DiffCL_CheckRead.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/DiffCL_CheckRead.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test that if module m1 can not read module m2, then class p1.c1
- *          in module m1 can not access p2.c2 in module m2.
+ * @summary Test that if module m1x can not read module m2x, then class p1.c1
+ *          in module m1x can not access p2.c2 in module m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MyDiffClassLoader.java
@@ -47,15 +47,15 @@
 import myloaders.MyDiffClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> packages p1
-// ClassLoader2 --> defines m2 --> packages p2
-//                  defines m3 --> packages p3
+// ClassLoader1 --> defines m1x --> packages p1
+// ClassLoader2 --> defines m2x --> packages p2
+//                  defines m3x --> packages p3
 //
-// m1 can not read m2
-// package p2 in m2 is exported to m1
+// m1x can not read m2x
+// package p2 in m2x is exported to m1x
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in m2.
-// Access denied since m1 can not read m2.
+// class p1.c1 defined in m1x tries to access p2.c2 defined in m2x.
+// Access denied since m1x can not read m2x.
 //
 public class DiffCL_CheckRead {
 
@@ -64,65 +64,65 @@
     // publicly defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m3
+        // Define module:     m1x
+        // Can read:          java.base, m3x
         // Packages:          p1
         // Packages exported: p1 is exported unqualifiedly
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m3")
+                        .requires("m3x")
                         .exports("p1")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
-        // Packages exported: p2 is exported to m1
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        // Packages exported: p2 is exported to m1x
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .exports("p2", Set.of("m1"))
+                        .exports("p2", Set.of("m1x"))
                         .build();
 
-        // Define module:     m3
-        // Can read:          java.base, m2
+        // Define module:     m3x
+        // Can read:          java.base, m2x
         // Packages:          p3
         // Packages exported: none
-        ModuleDescriptor descriptor_m3 =
-                ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor_m3x =
+                ModuleDescriptor.newModule("m3x")
                         .requires("java.base")
-                        .requires("m2")
-                        .contains("p3")
+                        .requires("m2x")
+                        .packages(Set.of("p3"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2, descriptor_m3);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x, descriptor_m3x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MyDiffClassLoader.loader1);
-        map.put("m2", MyDiffClassLoader.loader2);
-        map.put("m3", MyDiffClassLoader.loader2);
+        map.put("m1x", MyDiffClassLoader.loader1);
+        map.put("m2x", MyDiffClassLoader.loader2);
+        map.put("m3x", MyDiffClassLoader.loader2);
 
-        // Create Layer that contains m1, m2 and m3
+        // Create Layer that contains m1x, m2x and m3x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MyDiffClassLoader.loader2);
-        assertTrue(layer.findLoader("m3") == MyDiffClassLoader.loader2);
+        assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MyDiffClassLoader.loader2);
+        assertTrue(layer.findLoader("m3x") == MyDiffClassLoader.loader2);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
         Class p1_c1_class = MyDiffClassLoader.loader1.loadClass("p1.c1");
         try {
             p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p2 in m2 is exported to m1 but m2 is not readable from m1)");
+            throw new RuntimeException("Failed to get IAE (p2 in m2x is exported to m1x but m2x is not readable from m1x)");
         } catch (IllegalAccessError e) {
             System.out.println(e.getMessage());
             if (!e.getMessage().contains("cannot access")) {
--- a/hotspot/test/runtime/modules/AccessCheck/DiffCL_ExpQualOther.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/DiffCL_ExpQualOther.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,9 +25,9 @@
 
 /*
  * @test
- * @summary Test that if module m1 can read module m2, but package p2 in m2
- *          is exported specifically to module m3, then class p1.c1 in m1 can not
- *          access p2.c2 in m2.
+ * @summary Test that if module m1x can read module m2x, but package p2 in m2x
+ *          is exported specifically to module m3x, then class p1.c1 in m1x can not
+ *          access p2.c2 in m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MyDiffClassLoader.java
@@ -48,15 +48,15 @@
 import myloaders.MyDiffClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> packages p1
-// ClassLoader2 --> defines m2 --> packages p2
-//                  defines m3 --> packages p3
+// ClassLoader1 --> defines m1x --> packages p1
+// ClassLoader2 --> defines m2x --> packages p2
+//                  defines m3x --> packages p3
 //
-// m1 can read m2
-// package p2 in m2 is exported to m3
+// m1x can read m2x
+// package p2 in m2x is exported to m3x
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in m2
-// Access denied since although m1 can read m2, p2 is exported only to m3.
+// class p1.c1 defined in m1x tries to access p2.c2 defined in m2x
+// Access denied since although m1x can read m2x, p2 is exported only to m3x.
 //
 public class DiffCL_ExpQualOther {
 
@@ -65,66 +65,66 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2, m3
+        // Define module:     m1x
+        // Can read:          java.base, m2x, m3x
         // Packages:          p1
         // Packages exported: p1 is exported unqualifiedly
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
-                        .requires("m3")
+                        .requires("m2x")
+                        .requires("m3x")
                         .exports("p1")
                         .build();
 
-        // Define module:     m2
-        // Can read:          java.base, m3
+        // Define module:     m2x
+        // Can read:          java.base, m3x
         // Packages:          p2
-        // Packages exported: p2 is exported to m3
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        // Packages exported: p2 is exported to m3x
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .exports("p2", Set.of("m3"))
+                        .exports("p2", Set.of("m3x"))
                         .build();
 
-        // Define module:     m3
-        // Can read:          java.base, m2
+        // Define module:     m3x
+        // Can read:          java.base, m2x
         // Packages:          p3
         // Packages exported: none
-        ModuleDescriptor descriptor_m3 =
-                ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor_m3x =
+                ModuleDescriptor.newModule("m3x")
                         .requires("java.base")
-                        .requires("m2")
-                        .contains("p3")
+                        .requires("m2x")
+                        .packages(Set.of("p3"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2, descriptor_m3);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x, descriptor_m3x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MyDiffClassLoader.loader1);
-        map.put("m2", MyDiffClassLoader.loader2);
-        map.put("m3", MyDiffClassLoader.loader2);
+        map.put("m1x", MyDiffClassLoader.loader1);
+        map.put("m2x", MyDiffClassLoader.loader2);
+        map.put("m3x", MyDiffClassLoader.loader2);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MyDiffClassLoader.loader2);
-        assertTrue(layer.findLoader("m3") == MyDiffClassLoader.loader2);
+        assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MyDiffClassLoader.loader2);
+        assertTrue(layer.findLoader("m3x") == MyDiffClassLoader.loader2);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
         Class p1_c1_class = MyDiffClassLoader.loader1.loadClass("p1.c1");
         try {
             p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p2 in m2 is exported to m3 not to m1)");
+            throw new RuntimeException("Failed to get IAE (p2 in m2x is exported to m3x not to m1x)");
         } catch (IllegalAccessError e) {
             System.out.println(e.getMessage());
             if (!e.getMessage().contains("does not export")) {
--- a/hotspot/test/runtime/modules/AccessCheck/DiffCL_ExpQualToM1.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/DiffCL_ExpQualToM1.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary class p1.c1 defined in m1 tries to access p2.c2 defined in m2.
- *          Access allowed since m1 can read m2 and package p2 is exported to m1.
+ * @summary class p1.c1 defined in m1x tries to access p2.c2 defined in m2x.
+ *          Access allowed since m1x can read m2x and package p2 is exported to m1x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MyDiffClassLoader.java
@@ -47,14 +47,14 @@
 import myloaders.MyDiffClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> packages p1
-// ClassLoader2 --> defines m2 --> packages p2
+// ClassLoader1 --> defines m1x --> packages p1
+// ClassLoader2 --> defines m2x --> packages p2
 //
-// m1 can read m2
-// package p2 in m2 is exported to m1
+// m1x can read m2x
+// package p2 in m2x is exported to m1x
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in m2
-// Access allowed since m1 can read m2 and package p2 is exported to m1.
+// class p1.c1 defined in m1x tries to access p2.c2 defined in m2x
+// Access allowed since m1x can read m2x and package p2 is exported to m1x.
 //
 public class DiffCL_ExpQualToM1 {
 
@@ -63,45 +63,45 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          p1
         // Packages exported: p1 is exported to unqualifiedly
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .exports("p1")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
-        // Packages exported: package p2 is exported to m1
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        // Packages exported: package p2 is exported to m1x
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .exports("p2", Set.of("m1"))
+                        .exports("p2", Set.of("m1x"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MyDiffClassLoader.loader1);
-        map.put("m2", MyDiffClassLoader.loader2);
+        map.put("m1x", MyDiffClassLoader.loader1);
+        map.put("m2x", MyDiffClassLoader.loader2);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MyDiffClassLoader.loader2);
+        assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MyDiffClassLoader.loader2);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
@@ -109,7 +109,7 @@
         try {
             p1_c1_class.newInstance();
         } catch (IllegalAccessError e) {
-            throw new RuntimeException("Test Failed, an IAE should not be thrown since p2 is exported qualifiedly to m1");
+            throw new RuntimeException("Test Failed, an IAE should not be thrown since p2 is exported qualifiedly to m1x");
         }
     }
 
--- a/hotspot/test/runtime/modules/AccessCheck/DiffCL_ExpUnqual.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/DiffCL_ExpUnqual.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test that if module m1 can read module m2, and package p2 in m2 is
- *          exported unqualifiedly, then class p1.c1 in m1 can read p2.c2 in m2.
+ * @summary Test that if module m1x can read module m2x, and package p2 in m2x is
+ *          exported unqualifiedly, then class p1.c1 in m1x can read p2.c2 in m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MyDiffClassLoader.java
@@ -47,14 +47,14 @@
 import myloaders.MyDiffClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> packages p1
-// ClassLoader2 --> defines m2 --> packages p2
+// ClassLoader1 --> defines m1x --> packages p1
+// ClassLoader2 --> defines m2x --> packages p2
 //
-// m1 can read m2
-// package p2 in m2 is exported to m1
+// m1x can read m2x
+// package p2 in m2x is exported to m1x
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in m2
-// Access allowed since m1 can read m2 and package p2 is exported
+// class p1.c1 defined in m1x tries to access p2.c2 defined in m2x
+// Access allowed since m1x can read m2x and package p2 is exported
 // unqualifiedly.
 //
 public class DiffCL_ExpUnqual {
@@ -64,45 +64,45 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          p1
         // Packages exported: p1 is exported unqualifiedly
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .exports("p1")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
-        // Packages exported: package p2 is exported to m1
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        // Packages exported: package p2 is exported to m1x
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
                         .exports("p2")
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MyDiffClassLoader.loader1);
-        map.put("m2", MyDiffClassLoader.loader2);
+        map.put("m1x", MyDiffClassLoader.loader1);
+        map.put("m2x", MyDiffClassLoader.loader2);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MyDiffClassLoader.loader2);
+        assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MyDiffClassLoader.loader2);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
@@ -110,7 +110,7 @@
         try {
             p1_c1_class.newInstance();
         } catch (IllegalAccessError e) {
-            throw new RuntimeException("Test Failed, an IAE should not be thrown since p2 is exported qualifiedly to m1");
+            throw new RuntimeException("Test Failed, an IAE should not be thrown since p2 is exported qualifiedly to m1x");
         }
     }
 
--- a/hotspot/test/runtime/modules/AccessCheck/DiffCL_PkgNotExp.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/DiffCL_PkgNotExp.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test that if module m1 can read module m2, but package p2 in m2 is not
- *          exported, then class p1.c1 in m1 can not read p2.c2 in m2.
+ * @summary Test that if module m1x can read module m2x, but package p2 in m2x is not
+ *          exported, then class p1.c1 in m1x can not read p2.c2 in m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MyDiffClassLoader.java
@@ -47,13 +47,13 @@
 import myloaders.MyDiffClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> packages p1
-// ClassLoader2 --> defines m2 --> packages p2
+// ClassLoader1 --> defines m1x --> packages p1
+// ClassLoader2 --> defines m2x --> packages p2
 //
-// m1 can read m2
-// package p2 in m2 is not exported
+// m1x can read m2x
+// package p2 in m2x is not exported
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in m2
+// class p1.c1 defined in m1x tries to access p2.c2 defined in m2x
 // Access denied since p2 is not exported.
 //
 public class DiffCL_PkgNotExp {
@@ -63,52 +63,52 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          p1
         // Packages exported: p1 is exported unqualifiedly
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .exports("p1")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
         // Packages exported: none
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .contains("p2")
+                        .packages(Set.of("p2"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MyDiffClassLoader.loader1);
-        map.put("m2", MyDiffClassLoader.loader2);
+        map.put("m1x", MyDiffClassLoader.loader1);
+        map.put("m2x", MyDiffClassLoader.loader2);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MyDiffClassLoader.loader2);
+        assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MyDiffClassLoader.loader2);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
         Class p1_c1_class = MyDiffClassLoader.loader1.loadClass("p1.c1");
         try {
             p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p2 in m2 is not exported)");
+            throw new RuntimeException("Failed to get IAE (p2 in m2x is not exported)");
         } catch (IllegalAccessError e) {
           System.out.println(e.getMessage());
           if (!e.getMessage().contains("does not export")) {
--- a/hotspot/test/runtime/modules/AccessCheck/DiffCL_Umod.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/DiffCL_Umod.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,7 +25,7 @@
 
 /*
  * @test
- * @summary class p1.c1 defined in m1 tries to access p2.c2 defined in unnamed module.
+ * @summary class p1.c1 defined in m1x tries to access p2.c2 defined in unnamed module.
  * @library /test/lib
  * @modules java.base/jdk.internal.misc
  * @modules java.base/jdk.internal.module
@@ -50,10 +50,10 @@
 import myloaders.MyDiffClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> packages p1
-//                  package p1 in m1 is exported unqualifiedly
+// ClassLoader1 --> defines m1x --> packages p1
+//                  package p1 in m1x is exported unqualifiedly
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in
+// class p1.c1 defined in m1x tries to access p2.c2 defined in
 // in unnamed module.
 //
 // Three access attempts occur in this test:
@@ -62,7 +62,7 @@
 //   2. In this scenario a strict module establishes readability
 //      to the particular unnamed module it is trying to access.
 //      Access is allowed.
-//   3. Module m1 in the test_looseModuleLayer() method
+//   3. Module m1x in the test_looseModuleLayer() method
 //      is transitioned to a loose module, access
 //      to all unnamed modules is allowed.
 //
@@ -71,41 +71,41 @@
  // Create Layers over the boot layer to test different
  // accessing scenarios of a named module to an unnamed module.
 
- // Module m1 is a strict module and has not established
+ // Module m1x is a strict module and has not established
  // readability to an unnamed module that p2.c2 is defined in.
  public void test_strictModuleLayer() throws Throwable {
 
-     // Define module:     m1
+     // Define module:     m1x
      // Can read:          java.base
      // Packages:          p1
      // Packages exported: p1 is exported unqualifiedly
-     ModuleDescriptor descriptor_m1 =
-             ModuleDescriptor.module("m1")
+     ModuleDescriptor descriptor_m1x =
+             ModuleDescriptor.newModule("m1x")
                      .requires("java.base")
                      .exports("p1")
                      .build();
 
      // Set up a ModuleFinder containing all modules for this layer.
-     ModuleFinder finder = ModuleLibrary.of(descriptor_m1);
+     ModuleFinder finder = ModuleLibrary.of(descriptor_m1x);
 
-     // Resolves "m1"
+     // Resolves "m1x"
      Configuration cf = Layer.boot()
              .configuration()
-             .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+             .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
      MyDiffClassLoader.loader1 = new MyDiffClassLoader();
      MyDiffClassLoader.loader2 = new MyDiffClassLoader();
 
-     // map module m1 to class loader.
+     // map module m1x to class loader.
      // class c2 will be loaded in an unnamed module/loader2
      // to achieve differing class loaders.
      Map<String, ClassLoader> map = new HashMap<>();
-     map.put("m1", MyDiffClassLoader.loader1);
+     map.put("m1x", MyDiffClassLoader.loader1);
 
-     // Create Layer that contains m1
+     // Create Layer that contains m1x
      Layer layer = Layer.boot().defineModules(cf, map::get);
 
-     assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
+     assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
      assertTrue(layer.findLoader("java.base") == null);
 
      // now use the same loader to load class p1.c1
@@ -114,109 +114,109 @@
      // Attempt access
      try {
          p1_c1_class.newInstance();
-         throw new RuntimeException("Test Failed, strict module m1 should not be able " +
+         throw new RuntimeException("Test Failed, strict module m1x should not be able " +
                                     "to access public type p2.c2 defined in unnamed module");
      } catch (IllegalAccessError e) {
      }
 }
 
- // Module m1 is a strict module and has established
+ // Module m1x is a strict module and has established
  // readability to an unnamed module that p2.c2 is defined in.
  public void test_strictModuleUnnamedReadableLayer() throws Throwable {
 
-     // Define module:     m1
+     // Define module:     m1x
      // Can read:          java.base
      // Packages:          p1
      // Packages exported: p1 is exported unqualifiedly
-     ModuleDescriptor descriptor_m1 =
-             ModuleDescriptor.module("m1")
+     ModuleDescriptor descriptor_m1x =
+             ModuleDescriptor.newModule("m1x")
                      .requires("java.base")
                      .exports("p1")
                      .build();
 
      // Set up a ModuleFinder containing all modules for this layer.
-     ModuleFinder finder = ModuleLibrary.of(descriptor_m1);
+     ModuleFinder finder = ModuleLibrary.of(descriptor_m1x);
 
-     // Resolves "m1"
+     // Resolves "m1x"
      Configuration cf = Layer.boot()
              .configuration()
-             .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+             .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
      MyDiffClassLoader.loader1 = new MyDiffClassLoader();
      MyDiffClassLoader.loader2 = new MyDiffClassLoader();
 
-     // map module m1 to class loader.
+     // map module m1x to class loader.
      // class c2 will be loaded in an unnamed module/loader2
      // to achieve differing class loaders.
      Map<String, ClassLoader> map = new HashMap<>();
-     map.put("m1", MyDiffClassLoader.loader1);
+     map.put("m1x", MyDiffClassLoader.loader1);
 
-     // Create Layer that contains m1
+     // Create Layer that contains m1x
      Layer layer = Layer.boot().defineModules(cf, map::get);
 
-     assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
+     assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
      assertTrue(layer.findLoader("java.base") == null);
 
      // now use the same loader to load class p1.c1ReadEdgeDiffLoader
      Class p1_c1_class = MyDiffClassLoader.loader1.loadClass("p1.c1ReadEdgeDiffLoader");
 
      try {
-        // Read edge between m1 and the unnamed module that loads p2.c2 is established in
+        // Read edge between m1x and the unnamed module that loads p2.c2 is established in
         // c1ReadEdgeDiffLoader's ctor before attempting access.
         p1_c1_class.newInstance();
      } catch (IllegalAccessError e) {
-         throw new RuntimeException("Test Failed, module m1 has established readability to p2/c2 loader's " +
+         throw new RuntimeException("Test Failed, module m1x has established readability to p2/c2 loader's " +
                                     "unnamed module, access should be allowed: " + e.getMessage());
      }
  }
 
- // Module m1 is a loose module and thus can read all unnamed modules.
+ // Module m1x is a loose module and thus can read all unnamed modules.
  public void test_looseModuleLayer() throws Throwable {
 
-     // Define module:     m1
+     // Define module:     m1x
      // Can read:          java.base
      // Packages:          p1
      // Packages exported: p1 is exported unqualifiedly
-     ModuleDescriptor descriptor_m1 =
-             ModuleDescriptor.module("m1")
+     ModuleDescriptor descriptor_m1x =
+             ModuleDescriptor.newModule("m1x")
                      .requires("java.base")
                      .exports("p1")
                      .build();
 
      // Set up a ModuleFinder containing all modules for this layer.
-     ModuleFinder finder = ModuleLibrary.of(descriptor_m1);
+     ModuleFinder finder = ModuleLibrary.of(descriptor_m1x);
 
-     // Resolves "m1"
+     // Resolves "m1x"
      Configuration cf = Layer.boot()
              .configuration()
-             .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+             .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
      MyDiffClassLoader.loader1 = new MyDiffClassLoader();
      MyDiffClassLoader.loader2 = new MyDiffClassLoader();
 
-     // map module m1 to class loader.
+     // map module m1x to class loader.
      // class c2 will be loaded in an unnamed module/loader2
      // to achieve differing class loaders.
      Map<String, ClassLoader> map = new HashMap<>();
-     map.put("m1", MyDiffClassLoader.loader1);
+     map.put("m1x", MyDiffClassLoader.loader1);
 
-     // Create Layer that contains m1
+     // Create Layer that contains m1x
      Layer layer = Layer.boot().defineModules(cf, map::get);
 
-     assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
+     assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
      assertTrue(layer.findLoader("java.base") == null);
 
      // now use the same loader to load class p1.c1Loose
      Class p1_c1_class = MyDiffClassLoader.loader1.loadClass("p1.c1Loose");
 
-     // change m1 to read all unnamed modules
-     Module m1 = layer.findModule("m1").get();
-     jdk.internal.module.Modules.addReadsAllUnnamed(m1);
+     // change m1x to read all unnamed modules
+     Module m1x = layer.findModule("m1x").get();
+     jdk.internal.module.Modules.addReadsAllUnnamed(m1x);
 
      try {
          p1_c1_class.newInstance();
      } catch (IllegalAccessError e) {
-         throw new RuntimeException("Test Failed, loose module m1 should be able to access " +
+         throw new RuntimeException("Test Failed, loose module m1x should be able to access " +
                                     "public type p2.c2 defined in unnamed module: " + e.getMessage());
      }
  }
--- a/hotspot/test/runtime/modules/AccessCheck/DiffCL_UmodUpkg.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/DiffCL_UmodUpkg.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,7 +25,7 @@
 
 /*
  * @test
- * @summary class p3.c3 defined in module m1 tries to access c4 defined in an unnamed package
+ * @summary class p3.c3 defined in module m1x tries to access c4 defined in an unnamed package
  *          and an unnamed module.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
@@ -48,10 +48,10 @@
 import myloaders.MyDiffClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> packages p3
-//                  package p3 in m1 is exported unqualifiedly
+// ClassLoader1 --> defines m1x --> packages p3
+//                  package p3 in m1x is exported unqualifiedly
 //
-// class p3.c3 defined in m1 tries to access c4 defined in
+// class p3.c3 defined in m1x tries to access c4 defined in
 // in unnamed module.
 //
 // Two access attempts occur in this test:
@@ -66,41 +66,41 @@
  // Create Layers over the boot layer to test different
  // accessing scenarios of a named module to an unnamed module.
 
- // Module m1 is a strict module and has not established
+ // Module m1x is a strict module and has not established
  // readability to an unnamed module that c4 is defined in.
  public void test_strictModuleLayer() throws Throwable {
 
-     // Define module:     m1
+     // Define module:     m1x
      // Can read:          java.base
      // Packages:          p3
      // Packages exported: p3 is exported unqualifiedly
-     ModuleDescriptor descriptor_m1 =
-             ModuleDescriptor.module("m1")
+     ModuleDescriptor descriptor_m1x =
+             ModuleDescriptor.newModule("m1x")
                      .requires("java.base")
                      .exports("p3")
                      .build();
 
      // Set up a ModuleFinder containing all modules for this layer.
-     ModuleFinder finder = ModuleLibrary.of(descriptor_m1);
+     ModuleFinder finder = ModuleLibrary.of(descriptor_m1x);
 
-     // Resolves "m1"
+     // Resolves "m1x"
      Configuration cf = Layer.boot()
              .configuration()
-             .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+             .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
      MyDiffClassLoader.loader1 = new MyDiffClassLoader();
      MyDiffClassLoader.loader2 = new MyDiffClassLoader();
 
-     // map module m1 to class loader.
+     // map module m1x to class loader.
      // class c2 will be loaded in an unnamed module/loader2
      // to achieve differing class loaders.
      Map<String, ClassLoader> map = new HashMap<>();
-     map.put("m1", MyDiffClassLoader.loader1);
+     map.put("m1x", MyDiffClassLoader.loader1);
 
-     // Create Layer that contains m1
+     // Create Layer that contains m1x
      Layer layer = Layer.boot().defineModules(cf, map::get);
 
-     assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
+     assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
      assertTrue(layer.findLoader("java.base") == null);
 
      // now use the same loader to load class p3.c3
@@ -109,58 +109,58 @@
      // Attempt access
      try {
          p3_c3_class.newInstance();
-         throw new RuntimeException("Test Failed, strict module m1 should not be able to access " +
+         throw new RuntimeException("Test Failed, strict module m1x should not be able to access " +
                                     "public type c4 defined in unnamed module");
      } catch (IllegalAccessError e) {
      }
 }
 
- // Module m1 is a strict module and has established
+ // Module m1x is a strict module and has established
  // readability to an unnamed module that c4 is defined in.
  public void test_strictModuleUnnamedReadableLayer() throws Throwable {
 
-     // Define module:     m1
+     // Define module:     m1x
      // Can read:          java.base
      // Packages:          p3
      // Packages exported: p3 is exported unqualifiedly
-     ModuleDescriptor descriptor_m1 =
-             ModuleDescriptor.module("m1")
+     ModuleDescriptor descriptor_m1x =
+             ModuleDescriptor.newModule("m1x")
                      .requires("java.base")
                      .exports("p3")
                      .build();
 
      // Set up a ModuleFinder containing all modules for this layer.
-     ModuleFinder finder = ModuleLibrary.of(descriptor_m1);
+     ModuleFinder finder = ModuleLibrary.of(descriptor_m1x);
 
-     // Resolves "m1"
+     // Resolves "m1x"
      Configuration cf = Layer.boot()
              .configuration()
-             .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+             .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
      MyDiffClassLoader.loader1 = new MyDiffClassLoader();
      MyDiffClassLoader.loader2 = new MyDiffClassLoader();
 
-     // map module m1 to class loader.
+     // map module m1x to class loader.
      // class c2 will be loaded in an unnamed module/loader2
      // to achieve differing class loaders.
      Map<String, ClassLoader> map = new HashMap<>();
-     map.put("m1", MyDiffClassLoader.loader1);
+     map.put("m1x", MyDiffClassLoader.loader1);
 
-     // Create Layer that contains m1
+     // Create Layer that contains m1x
      Layer layer = Layer.boot().defineModules(cf, map::get);
 
-     assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
+     assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
      assertTrue(layer.findLoader("java.base") == null);
 
      // now use the same loader to load class p3.c3ReadEdgeDiffLoader
      Class p3_c3_class = MyDiffClassLoader.loader1.loadClass("p3.c3ReadEdgeDiffLoader");
 
      try {
-        // Read edge between m1 and the unnamed module that loads c4 is established in
+        // Read edge between m1x and the unnamed module that loads c4 is established in
         // C3ReadEdgeDiffLoader's ctor before attempting access.
         p3_c3_class.newInstance();
      } catch (IllegalAccessError e) {
-         throw new RuntimeException("Test Failed, module m1 has established readability to " +
+         throw new RuntimeException("Test Failed, module m1x has established readability to " +
                                     "c4 loader's unnamed module, access should be allowed: " + e.getMessage());
      }
  }
--- a/hotspot/test/runtime/modules/AccessCheck/ExpQualOther.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/ExpQualOther.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,9 +25,9 @@
 
 /*
  * @test
- * @summary Test that if module m1 can read module m2, but package p2 in m2
- *          is exported specifically to module m3, then class p1.c1 in m1 can not
- *          access p2.c2 in m2.
+ * @summary Test that if module m1x can read module m2x, but package p2 in m2x
+ *          is exported specifically to module m3x, then class p1.c1 in m1x can not
+ *          access p2.c2 in m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MySameClassLoader.java
@@ -48,15 +48,15 @@
 import myloaders.MySameClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> packages p1
-//                  defines m2 --> packages p2
-//                  defines m3 --> packages p3
+// ClassLoader1 --> defines m1x --> packages p1
+//                  defines m2x --> packages p2
+//                  defines m3x --> packages p3
 //
-// m1 can read m2
-// package p2 in m2 is exported to m3
+// m1x can read m2x
+// package p2 in m2x is exported to m3x
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in m2
-// Access denied since although m1 can read m2, p2 is exported only to m3.
+// class p1.c1 defined in m1x tries to access p2.c2 defined in m2x
+// Access denied since although m1x can read m2x, p2 is exported only to m3x.
 //
 public class ExpQualOther {
 
@@ -65,66 +65,66 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2, m3
+        // Define module:     m1x
+        // Can read:          java.base, m2x, m3x
         // Packages:          p1
         // Packages exported: p1 is exported unqualifiedly
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
-                        .requires("m3")
+                        .requires("m2x")
+                        .requires("m3x")
                         .exports("p1")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
-        // Packages exported: p2 is exported to m3
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        // Packages exported: p2 is exported to m3x
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .exports("p2", Set.of("m3"))
+                        .exports("p2", Set.of("m3x"))
                         .build();
 
-        // Define module:     m3
-        // Can read:          java.base, m2
+        // Define module:     m3x
+        // Can read:          java.base, m2x
         // Packages:          p3
         // Packages exported: none
-        ModuleDescriptor descriptor_m3 =
-                ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor_m3x =
+                ModuleDescriptor.newModule("m3x")
                         .requires("java.base")
-                        .requires("m2")
-                        .contains("p3")
+                        .requires("m2x")
+                        .packages(Set.of("p3"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2, descriptor_m3);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x, descriptor_m3x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MySameClassLoader.loader1);
-        map.put("m2", MySameClassLoader.loader1);
-        map.put("m3", MySameClassLoader.loader1);
+        map.put("m1x", MySameClassLoader.loader1);
+        map.put("m2x", MySameClassLoader.loader1);
+        map.put("m3x", MySameClassLoader.loader1);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m3") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m1x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m3x") == MySameClassLoader.loader1);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
         Class p1_c1_class = MySameClassLoader.loader1.loadClass("p1.c1");
         try {
             p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p2 in m2 is exported to m3 not to m1)");
+            throw new RuntimeException("Failed to get IAE (p2 in m2x is exported to m3x not to m1x)");
         } catch (IllegalAccessError e) {
             System.out.println(e.getMessage());
             if (!e.getMessage().contains("does not export")) {
--- a/hotspot/test/runtime/modules/AccessCheck/ExpQualToM1.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/ExpQualToM1.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test that if module m1 can read module m2, AND package p2 in m2 is
- *          exported qualifiedly to m1, then class p1.c1 in m1 can read p2.c2 in m2.
+ * @summary Test that if module m1x can read module m2x, AND package p2 in m2x is
+ *          exported qualifiedly to m1x, then class p1.c1 in m1x can read p2.c2 in m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MySameClassLoader.java
@@ -53,52 +53,52 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          p1
         // Packages exported: p1 is exported unqualifiedly
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .exports("p1")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
-        // Packages exported: p2 is exported qualifiedly to m1
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        // Packages exported: p2 is exported qualifiedly to m1x
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .exports("p2", Set.of("m1"))
+                        .exports("p2", Set.of("m1x"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to the same class loader for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MySameClassLoader.loader1);
-        map.put("m2", MySameClassLoader.loader1);
+        map.put("m1x", MySameClassLoader.loader1);
+        map.put("m2x", MySameClassLoader.loader1);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m1x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MySameClassLoader.loader1);
 
         // now use the same loader to load class p1.c1
         Class p1_c1_class = MySameClassLoader.loader1.loadClass("p1.c1");
         try {
             p1_c1_class.newInstance();
         } catch (IllegalAccessError e) {
-            throw new RuntimeException("Test Failed, an IAE should not be thrown since p2 is exported qualifiedly to m1");
+            throw new RuntimeException("Test Failed, an IAE should not be thrown since p2 is exported qualifiedly to m1x");
         }
     }
 
--- a/hotspot/test/runtime/modules/AccessCheck/ExpUnqual.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/ExpUnqual.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test that if module m1 can read module m2, AND package p2 in module2 is
- *          exported unqualifiedly, then class p1.c1 in m1 can read p2.c2 in m2.
+ * @summary Test that if module m1x can read module m2x, AND package p2 in module_two is
+ *          exported unqualifiedly, then class p1.c1 in m1x can read p2.c2 in m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MySameClassLoader.java
@@ -53,45 +53,45 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          p1
         // Packages exported: p1 is exported unqualifiedly
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .exports("p1")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
         // Packages exported: p2 is exported unqualifiedly
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
                         .exports("p2")
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to the same class loader for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MySameClassLoader.loader1);
-        map.put("m2", MySameClassLoader.loader1);
+        map.put("m1x", MySameClassLoader.loader1);
+        map.put("m2x", MySameClassLoader.loader1);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m1x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MySameClassLoader.loader1);
 
         // now use the same loader to load class p1.c1
         Class p1_c1_class = MySameClassLoader.loader1.loadClass("p1.c1");
--- a/hotspot/test/runtime/modules/AccessCheck/ExportAllUnnamed.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/ExportAllUnnamed.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test if package p2 in module m2 is exported to all unnamed,
- *          then class p1.c1 in an unnamed module can read p2.c2 in module m2.
+ * @summary Test if package p2 in module m2x is exported to all unnamed,
+ *          then class p1.c1 in an unnamed module can read p2.c2 in module m2x.
  * @library /test/lib
  * @modules java.base/jdk.internal.misc
  * @modules java.base/jdk.internal.module
@@ -49,15 +49,15 @@
 import myloaders.MySameClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> no packages
-//                  defines m2 --> packages p2
+// ClassLoader1 --> defines m1x --> no packages
+//                  defines m2x --> packages p2
 //
-// m1 can read m2
-// package p2 in m2 is exported unqualifiedly
+// m1x can read m2x
+// package p2 in m2x is exported unqualifiedly
 //
-// class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2
+// class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2x
 // Access allowed, an unnamed module can read all modules and p2 in module
-//           m2 is exported to all unnamed modules.
+//           m2x is exported to all unnamed modules.
 
 public class ExportAllUnnamed {
 
@@ -66,51 +66,51 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          none
         // Packages exported: none
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
         // Packages exported: p2 is exported unqualifiedly
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .exports("p2", Set.of("m1"))
+                        .exports("p2", Set.of("m1x"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MySameClassLoader.loader1);
-        map.put("m2", MySameClassLoader.loader1);
+        map.put("m1x", MySameClassLoader.loader1);
+        map.put("m2x", MySameClassLoader.loader1);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m1x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MySameClassLoader.loader1);
         assertTrue(layer.findLoader("java.base") == null);
 
         Class p2_c2_class = MySameClassLoader.loader1.loadClass("p2.c2");
-        Module m2 = p2_c2_class.getModule();
+        Module m2x = p2_c2_class.getModule();
 
-        // Export m2/p2 to all unnamed modules.
-        jdk.internal.module.Modules.addExportsToAllUnnamed(m2, "p2");
+        // Export m2x/p2 to all unnamed modules.
+        jdk.internal.module.Modules.addExportsToAllUnnamed(m2x, "p2");
 
         // now use the same loader to load class p1.c1
         Class p1_c1_class = MySameClassLoader.loader1.loadClass("p1.c1");
--- a/hotspot/test/runtime/modules/AccessCheck/PkgNotExp.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/PkgNotExp.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test that if module m1 can read module m2, but package p2 in m2 is not
- *          exported, then class p1.c1 in m1 can not read p2.c2 in m2.
+ * @summary Test that if module m1x can read module m2x, but package p2 in m2x is not
+ *          exported, then class p1.c1 in m1x can not read p2.c2 in m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MySameClassLoader.java
@@ -47,13 +47,13 @@
 import myloaders.MySameClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> packages p1
-//                  defines m2 --> packages p2
+// ClassLoader1 --> defines m1x --> packages p1
+//                  defines m2x --> packages p2
 //
-// m1 can read m2
-// package p2 in m2 is not exported
+// m1x can read m2x
+// package p2 in m2x is not exported
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in m2
+// class p1.c1 defined in m1x tries to access p2.c2 defined in m2x
 // Access denied since p2 is not exported.
 //
 public class PkgNotExp {
@@ -63,51 +63,51 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          p1
         // Packages exported: p1 is exported unqualifiedly
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .exports("p1")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
         // Packages exported: none
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .contains("p2")
+                        .packages(Set.of("p2"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to the same class loader for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MySameClassLoader.loader1);
-        map.put("m2", MySameClassLoader.loader1);
+        map.put("m1x", MySameClassLoader.loader1);
+        map.put("m2x", MySameClassLoader.loader1);
 
-        // Create Layer that contains m1 and m2
+        // Create Layer that contains m1x and m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m1x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MySameClassLoader.loader1);
 
         // now use the same loader to load class p1.c1
         Class p1_c1_class = MySameClassLoader.loader1.loadClass("p1.c1");
         try {
             p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p2 in m2 is not exported)");
+            throw new RuntimeException("Failed to get IAE (p2 in m2x is not exported)");
         } catch (IllegalAccessError e) {
           System.out.println(e.getMessage());
           if (!e.getMessage().contains("does not export")) {
--- a/hotspot/test/runtime/modules/AccessCheck/Umod.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/Umod.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,7 +25,7 @@
 
 /*
  * @test
- * @summary class p1.c1 defined in m1 tries to access p2.c2 defined in unnamed module.
+ * @summary class p1.c1 defined in m1x tries to access p2.c2 defined in unnamed module.
  * @library /test/lib
  * @modules java.base/jdk.internal.misc
  * @modules java.base/jdk.internal.module
@@ -50,10 +50,10 @@
 import myloaders.MySameClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> packages p1
-//                  package p1 in m1 is exported unqualifiedly
+// ClassLoader1 --> defines m1x --> packages p1
+//                  package p1 in m1x is exported unqualifiedly
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in
+// class p1.c1 defined in m1x tries to access p2.c2 defined in
 // in unnamed module.
 //
 // Three access attempts occur in this test:
@@ -62,7 +62,7 @@
 //   2. In this scenario a strict module establishes readability
 //      to the particular unnamed module it is trying to access.
 //      Access is allowed.
-//   3. Module m1 in the test_looseModuleLayer() method
+//   3. Module m1x in the test_looseModuleLayer() method
 //      is transitioned to a loose module, access
 //      to all unnamed modules is allowed.
 //
@@ -71,38 +71,38 @@
  // Create Layers over the boot layer to test different
  // accessing scenarios of a named module to an unnamed module.
 
- // Module m1 is a strict module and has not established
+ // Module m1x is a strict module and has not established
  // readability to an unnamed module that p2.c2 is defined in.
  public void test_strictModuleLayer() throws Throwable {
 
-     // Define module:     m1
+     // Define module:     m1x
      // Can read:          java.base
      // Packages:          p1
      // Packages exported: p1 is exported unqualifiedly
-     ModuleDescriptor descriptor_m1 =
-             ModuleDescriptor.module("m1")
+     ModuleDescriptor descriptor_m1x =
+             ModuleDescriptor.newModule("m1x")
                      .requires("java.base")
                      .exports("p1")
                      .build();
 
      // Set up a ModuleFinder containing all modules for this layer.
-     ModuleFinder finder = ModuleLibrary.of(descriptor_m1);
+     ModuleFinder finder = ModuleLibrary.of(descriptor_m1x);
 
-     // Resolves "m1"
+     // Resolves "m1x"
      Configuration cf = Layer.boot()
              .configuration()
-             .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+             .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
-     // map module m1 to class loader.
+     // map module m1x to class loader.
      // class c2 will be loaded in an unnamed module/loader.
      MySameClassLoader loader = new MySameClassLoader();
      Map<String, ClassLoader> map = new HashMap<>();
-     map.put("m1", loader);
+     map.put("m1x", loader);
 
-     // Create Layer that contains m1
+     // Create Layer that contains m1x
      Layer layer = Layer.boot().defineModules(cf, map::get);
 
-     assertTrue(layer.findLoader("m1") == loader);
+     assertTrue(layer.findLoader("m1x") == loader);
      assertTrue(layer.findLoader("java.base") == null);
 
      // now use the same loader to load class p1.c1
@@ -111,103 +111,103 @@
      // Attempt access
      try {
          p1_c1_class.newInstance();
-         throw new RuntimeException("Test Failed, strict module m1, type p1.c1, should not be able " +
+         throw new RuntimeException("Test Failed, strict module m1x, type p1.c1, should not be able " +
                                     "to access public type p2.c2 defined in unnamed module");
      } catch (IllegalAccessError e) {
      }
  }
 
- // Module m1 is a strict module and has established
+ // Module m1x is a strict module and has established
  // readability to an unnamed module that p2.c2 is defined in.
  public void test_strictModuleUnnamedReadableLayer() throws Throwable {
 
-     // Define module:     m1
+     // Define module:     m1x
      // Can read:          java.base
      // Packages:          p1
      // Packages exported: p1 is exported unqualifiedly
-     ModuleDescriptor descriptor_m1 =
-             ModuleDescriptor.module("m1")
+     ModuleDescriptor descriptor_m1x =
+             ModuleDescriptor.newModule("m1x")
                      .requires("java.base")
                      .exports("p1")
                      .build();
 
      // Set up a ModuleFinder containing all modules for this layer.
-     ModuleFinder finder = ModuleLibrary.of(descriptor_m1);
+     ModuleFinder finder = ModuleLibrary.of(descriptor_m1x);
 
-     // Resolves "m1"
+     // Resolves "m1x"
      Configuration cf = Layer.boot()
              .configuration()
-             .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+             .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
      MySameClassLoader loader = new MySameClassLoader();
-     // map module m1 to class loader.
+     // map module m1x to class loader.
      // class c2 will be loaded in an unnamed module/loader.
      Map<String, ClassLoader> map = new HashMap<>();
-     map.put("m1", loader);
+     map.put("m1x", loader);
 
-     // Create Layer that contains m1
+     // Create Layer that contains m1x
      Layer layer = Layer.boot().defineModules(cf, map::get);
 
-     assertTrue(layer.findLoader("m1") == loader);
+     assertTrue(layer.findLoader("m1x") == loader);
      assertTrue(layer.findLoader("java.base") == null);
 
      // now use the same loader to load class p1.c1ReadEdge
      Class p1_c1_class = loader.loadClass("p1.c1ReadEdge");
 
      try {
-       // Read edge between m1 and the unnamed module that loads p2.c2 is established in
+       // Read edge between m1x and the unnamed module that loads p2.c2 is established in
        // c1ReadEdge's ctor before attempting access.
        p1_c1_class.newInstance();
      } catch (IllegalAccessError e) {
-         throw new RuntimeException("Test Failed, strict module m1, type p1.c1ReadEdge, should be able to acccess public type " +
+         throw new RuntimeException("Test Failed, strict module m1x, type p1.c1ReadEdge, should be able to acccess public type " +
                                     "p2.c2 defined in unnamed module: " + e.getMessage());
      }
 }
 
- // Module m1 is a loose module and thus can read all unnamed modules.
+ // Module m1x is a loose module and thus can read all unnamed modules.
  public void test_looseModuleLayer() throws Throwable {
 
-     // Define module:     m1
+     // Define module:     m1x
      // Can read:          java.base
      // Packages:          p1
      // Packages exported: p1 is exported unqualifiedly
-     ModuleDescriptor descriptor_m1 =
-             ModuleDescriptor.module("m1")
+     ModuleDescriptor descriptor_m1x =
+             ModuleDescriptor.newModule("m1x")
                      .requires("java.base")
                      .exports("p1")
                      .build();
 
      // Set up a ModuleFinder containing all modules for this layer.
-     ModuleFinder finder = ModuleLibrary.of(descriptor_m1);
+     ModuleFinder finder = ModuleLibrary.of(descriptor_m1x);
 
-     // Resolves "m1"
+     // Resolves "m1x"
      Configuration cf = Layer.boot()
              .configuration()
-             .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+             .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
      MySameClassLoader loader = new MySameClassLoader();
-     // map module m1 to class loader.
+     // map module m1x to class loader.
      // class c2 will be loaded in an unnamed module/loader.
      Map<String, ClassLoader> map = new HashMap<>();
-     map.put("m1", loader);
+     map.put("m1x", loader);
 
-     // Create Layer that contains m1
+     // Create Layer that contains m1x
      Layer layer = Layer.boot().defineModules(cf, map::get);
 
-     assertTrue(layer.findLoader("m1") == loader);
+     assertTrue(layer.findLoader("m1x") == loader);
      assertTrue(layer.findLoader("java.base") == null);
 
      // now use the same loader to load class p1.c1Loose
      Class p1_c1_class = loader.loadClass("p1.c1Loose");
 
-     // change m1 to read all unnamed modules
-     Module m1 = layer.findModule("m1").get();
-     jdk.internal.module.Modules.addReadsAllUnnamed(m1);
+     // change m1x to read all unnamed modules
+     Module m1x = layer.findModule("m1x").get();
+     jdk.internal.module.Modules.addReadsAllUnnamed(m1x);
 
      try {
          p1_c1_class.newInstance();
      } catch (IllegalAccessError e) {
-         throw new RuntimeException("Test Failed, strict module m1, type p1.c1Loose, should be able to acccess public type " +
+         throw new RuntimeException("Test Failed, strict module m1x, type p1.c1Loose, should be able to acccess public type " +
                                     "p2.c2 defined in unnamed module: " + e.getMessage());
      }
  }
--- a/hotspot/test/runtime/modules/AccessCheck/UmodDiffCL_ExpQualOther.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/UmodDiffCL_ExpQualOther.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,9 +25,9 @@
 
 /*
  * @test
- * @summary class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2.
+ * @summary class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2x.
  *          Access is denied, since an unnamed module can read all modules but p2 in module
- *          m2 is exported specifically to module m1, not to all modules.
+ *          m2x is exported specifically to module m1x, not to all modules.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MyDiffClassLoader.java
@@ -48,15 +48,15 @@
 import myloaders.MyDiffClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> no packages
-// ClassLoader2 --> defines m2 --> packages p2
+// ClassLoader1 --> defines m1x --> no packages
+// ClassLoader2 --> defines m2x --> packages p2
 //
-// m1 can read m2
-// package p2 in m2 is not exported
+// m1x can read m2x
+// package p2 in m2x is not exported
 //
-// class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2
+// class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2x
 // Access denied, an unnamed module can read all modules but p2 in module
-//             m2 is exported specifically to module m1 not to all modules.
+//             m2x is exported specifically to module m1x not to all modules.
 //
 public class UmodDiffCL_ExpQualOther {
 
@@ -65,53 +65,53 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
+        // Define module:     m1x
         // Can read:          java.base
         // Packages:          none
         // Packages exported: none
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
         // Packages exported: none
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .exports("p2", Set.of("m1"))
+                        .exports("p2", Set.of("m1x"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MyDiffClassLoader.loader1);
-        map.put("m2", MyDiffClassLoader.loader2);
+        map.put("m1x", MyDiffClassLoader.loader1);
+        map.put("m2x", MyDiffClassLoader.loader2);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MyDiffClassLoader.loader2);
+        assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MyDiffClassLoader.loader2);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
-        // NOTE: module m1 does not define a package named p1.
+        // NOTE: module m1x does not define a package named p1.
         //       p1 will be loaded in an unnamed module.
         Class p1_c1_class = MyDiffClassLoader.loader1.loadClass("p1.c1");
         try {
             p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p2 in m2 is exported to m1, not unqualifiedly");
+            throw new RuntimeException("Failed to get IAE (p2 in m2x is exported to m1x, not unqualifiedly");
         } catch (IllegalAccessError e) {
             System.out.println(e.getMessage());
             if (!e.getMessage().contains("does not export")) {
--- a/hotspot/test/runtime/modules/AccessCheck/UmodDiffCL_ExpUnqual.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/UmodDiffCL_ExpUnqual.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2.
- *          Access allowed, an unnamed module can read all modules and p2 in module m2
+ * @summary class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2x.
+ *          Access allowed, an unnamed module can read all modules and p2 in module m2x
  *          which is exported unqualifiedly.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
@@ -48,15 +48,15 @@
 import myloaders.MyDiffClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> no packages
-// ClassLoader2 --> defines m2 --> packages p2
+// ClassLoader1 --> defines m1x --> no packages
+// ClassLoader2 --> defines m2x --> packages p2
 //
-// m1 can read m2
-// package p2 in m2 is exported unqualifiedly.
+// m1x can read m2x
+// package p2 in m2x is exported unqualifiedly.
 //
-// class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2
+// class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2x
 // Access allowed, an unnamed module can read all modules and p2 in module
-//              m2 which is exported unqualifiedly.
+//              m2x which is exported unqualifiedly.
 //
 public class UmodDiffCL_ExpUnqual {
 
@@ -65,53 +65,53 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          none
         // Packages exported: none
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
         // Packages exported: none
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
                         .exports("p2")
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MyDiffClassLoader.loader1);
-        map.put("m2", MyDiffClassLoader.loader2);
+        map.put("m1x", MyDiffClassLoader.loader1);
+        map.put("m2x", MyDiffClassLoader.loader2);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MyDiffClassLoader.loader2);
+        assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MyDiffClassLoader.loader2);
         assertTrue(layer.findLoader("java.base") == null);
 
-        // NOTE: module m1 does not define a package named p1.
+        // NOTE: module m1x does not define a package named p1.
         //       p1 will be loaded in an unnamed module.
         Class p1_c1_class = MyDiffClassLoader.loader1.loadClass("p1.c1");
         try {
             p1_c1_class.newInstance();
         } catch (IllegalAccessError e) {
-            throw new RuntimeException("Test Failed, p1.c1 defined in unnamed module can access p2.c2 in module m2");
+            throw new RuntimeException("Test Failed, p1.c1 defined in unnamed module can access p2.c2 in module m2x");
         }
     }
 
--- a/hotspot/test/runtime/modules/AccessCheck/UmodDiffCL_PkgNotExp.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/UmodDiffCL_PkgNotExp.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,9 +25,9 @@
 
 /*
  * @test
- * @summary class p1.c1 defined in unnamed module tries to access p2.c2 defined in m2.
+ * @summary class p1.c1 defined in unnamed module tries to access p2.c2 defined in m2x.
  *          Access is denied since even though unnamed module can read all modules, p2
- *          in module m2 is not exported at all.
+ *          in module m2x is not exported at all.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MyDiffClassLoader.java
@@ -47,15 +47,15 @@
 import myloaders.MyDiffClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> no packages
-// ClassLoader2 --> defines m2 --> packages p2
+// ClassLoader1 --> defines m1x --> no packages
+// ClassLoader2 --> defines m2x --> packages p2
 //
-// m1 can read m2
-// package p2 in m2 is not exported
+// m1x can read m2x
+// package p2 in m2x is not exported
 //
-// class p1.c1 defined in unnamed module tries to access p2.c2 defined in m2
+// class p1.c1 defined in unnamed module tries to access p2.c2 defined in m2x
 // Access denied since even though unnamed module can read all modules, p2
-// in module m2 is not exported at all.
+// in module m2x is not exported at all.
 //
 public class UmodDiffCL_PkgNotExp {
 
@@ -64,53 +64,53 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          none
         // Packages exported: none
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
         // Packages exported: none
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .contains("p2")
+                        .packages(Set.of("p2"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MyDiffClassLoader.loader1);
-        map.put("m2", MyDiffClassLoader.loader2);
+        map.put("m1x", MyDiffClassLoader.loader1);
+        map.put("m2x", MyDiffClassLoader.loader2);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MyDiffClassLoader.loader2);
+        assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MyDiffClassLoader.loader2);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
-        // NOTE: module m1 does not define a package named p1.
+        // NOTE: module m1x does not define a package named p1.
         //       p1 will be loaded in an unnamed module.
         Class p1_c1_class = MyDiffClassLoader.loader1.loadClass("p1.c1");
         try {
             p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p2 in m2 is not exported to an unnamed module)");
+            throw new RuntimeException("Failed to get IAE (p2 in m2x is not exported to an unnamed module)");
         } catch (IllegalAccessError e) {
           System.out.println(e.getMessage());
           if (!e.getMessage().contains("does not export")) {
--- a/hotspot/test/runtime/modules/AccessCheck/UmodUPkg.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/UmodUPkg.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,7 +25,7 @@
 
 /*
  * @test
- * @summary class p3.c3 defined in module m1 tries to access c4 defined in unnamed module.
+ * @summary class p3.c3 defined in module m1x tries to access c4 defined in unnamed module.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MySameClassLoader.java
@@ -48,10 +48,10 @@
 import myloaders.MySameClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> packages p3
-//                  package p3 in m1 is exported unqualifiedly
+// ClassLoader1 --> defines m1x --> packages p3
+//                  package p3 in m1x is exported unqualifiedly
 //
-// class p3.c3 defined in m1 tries to access c4 defined in
+// class p3.c3 defined in m1x tries to access c4 defined in
 // in unnamed module.
 //
 // Two access attempts occur in this test:
@@ -66,38 +66,38 @@
  // Create Layers over the boot layer to test different
  // accessing scenarios of a named module to an unnamed module.
 
- // Module m1 is a strict module and has not established
+ // Module m1x is a strict module and has not established
  // readability to an unnamed module that c4 is defined in.
  public void test_strictModuleLayer() throws Throwable {
 
-     // Define module:     m1
+     // Define module:     m1x
      // Can read:          java.base
      // Packages:          p3
      // Packages exported: p3 is exported unqualifiedly
-     ModuleDescriptor descriptor_m1 =
-             ModuleDescriptor.module("m1")
+     ModuleDescriptor descriptor_m1x =
+             ModuleDescriptor.newModule("m1x")
                      .requires("java.base")
                      .exports("p3")
                      .build();
 
      // Set up a ModuleFinder containing all modules for this layer.
-     ModuleFinder finder = ModuleLibrary.of(descriptor_m1);
+     ModuleFinder finder = ModuleLibrary.of(descriptor_m1x);
 
-     // Resolves "m1"
+     // Resolves "m1x"
      Configuration cf = Layer.boot()
              .configuration()
-             .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+             .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
-     // map module m1 to class loader.
+     // map module m1x to class loader.
      // class c4 will be loaded in an unnamed module/loader.
      MySameClassLoader loader = new MySameClassLoader();
      Map<String, ClassLoader> map = new HashMap<>();
-     map.put("m1", loader);
+     map.put("m1x", loader);
 
-     // Create Layer that contains m1
+     // Create Layer that contains m1x
      Layer layer = Layer.boot().defineModules(cf, map::get);
 
-     assertTrue(layer.findLoader("m1") == loader);
+     assertTrue(layer.findLoader("m1x") == loader);
      assertTrue(layer.findLoader("java.base") == null);
 
      // now use the same loader to load class p3.c3
@@ -106,55 +106,55 @@
      // Attempt access
      try {
          p3_c3_class.newInstance();
-         throw new RuntimeException("Test Failed, strict module m1, type p3.c3, should not be able to access " +
+         throw new RuntimeException("Test Failed, strict module m1x, type p3.c3, should not be able to access " +
                                     "public type c4 defined in unnamed module");
      } catch (IllegalAccessError e) {
      }
  }
 
- // Module m1 is a strict module and has established
+ // Module m1x is a strict module and has established
  // readability to an unnamed module that c4 is defined in.
  public void test_strictModuleUnnamedReadableLayer() throws Throwable {
 
-     // Define module:     m1
+     // Define module:     m1x
      // Can read:          java.base
      // Packages:          p3
      // Packages exported: p3 is exported unqualifiedly
-     ModuleDescriptor descriptor_m1 =
-             ModuleDescriptor.module("m1")
+     ModuleDescriptor descriptor_m1x =
+             ModuleDescriptor.newModule("m1x")
                      .requires("java.base")
                      .exports("p3")
                      .build();
 
      // Set up a ModuleFinder containing all modules for this layer.
-     ModuleFinder finder = ModuleLibrary.of(descriptor_m1);
+     ModuleFinder finder = ModuleLibrary.of(descriptor_m1x);
 
-     // Resolves "m1"
+     // Resolves "m1x"
      Configuration cf = Layer.boot()
              .configuration()
-             .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+             .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
      MySameClassLoader loader = new MySameClassLoader();
-     // map module m1 to class loader.
+     // map module m1x to class loader.
      // class c4 will be loaded in an unnamed module/loader.
      Map<String, ClassLoader> map = new HashMap<>();
-     map.put("m1", loader);
+     map.put("m1x", loader);
 
-     // Create Layer that contains m1
+     // Create Layer that contains m1x
      Layer layer = Layer.boot().defineModules(cf, map::get);
 
-     assertTrue(layer.findLoader("m1") == loader);
+     assertTrue(layer.findLoader("m1x") == loader);
      assertTrue(layer.findLoader("java.base") == null);
 
      // now use the same loader to load class p3.c3ReadEdge
      Class p3_c3_class = loader.loadClass("p3.c3ReadEdge");
 
      try {
-        // Read edge between m1 and the unnamed module that loads c4 is established in
+        // Read edge between m1x and the unnamed module that loads c4 is established in
         // c3ReadEdge's ctor before attempting access.
         p3_c3_class.newInstance();
      } catch (IllegalAccessError e) {
-         throw new RuntimeException("Test Failed, module m1, type p3.c3ReadEdge, has established readability to " +
+         throw new RuntimeException("Test Failed, module m1x, type p3.c3ReadEdge, has established readability to " +
                                     "c4 loader's unnamed module, access should be allowed: " + e.getMessage());
      }
  }
--- a/hotspot/test/runtime/modules/AccessCheck/UmodUpkgDiffCL_ExpQualOther.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/UmodUpkgDiffCL_ExpQualOther.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,9 +25,9 @@
 
 /*
  * @test
- * @summary class c5 defined in an unnamed module tries to access p6.c6 defined in m2.
+ * @summary class c5 defined in an unnamed module tries to access p6.c6 defined in m2x.
  *          Access is denied, since an unnamed module can read all modules but p6 in module
- *          m2 is exported specifically to module m1, not to all modules.
+ *          m2x is exported specifically to module m1x, not to all modules.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MyDiffClassLoader.java
@@ -48,15 +48,15 @@
 import myloaders.MyDiffClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> no packages
-// ClassLoader2 --> defines m2 --> packages p6
+// ClassLoader1 --> defines m1x --> no packages
+// ClassLoader2 --> defines m2x --> packages p6
 //
-// m1 can read m2
-// package p6 in m2 is not exported
+// m1x can read m2x
+// package p6 in m2x is not exported
 //
-// class c5 defined in an unnamed module tries to access p6.c6 defined in m2
+// class c5 defined in an unnamed module tries to access p6.c6 defined in m2x
 // Access denied, an unnamed module can read all modules but p6 in module
-//             m2 is exported specifically to module m1 not to all modules.
+//             m2x is exported specifically to module m1x not to all modules.
 //
 public class UmodUpkgDiffCL_ExpQualOther {
 
@@ -65,51 +65,51 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          none
         // Packages exported: none
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p6
-        // Packages exported: p6 exported to m1
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        // Packages exported: p6 exported to m1x
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .exports("p6", Set.of("m1"))
+                        .exports("p6", Set.of("m1x"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MyDiffClassLoader.loader1);
-        map.put("m2", MyDiffClassLoader.loader2);
+        map.put("m1x", MyDiffClassLoader.loader1);
+        map.put("m2x", MyDiffClassLoader.loader2);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MyDiffClassLoader.loader2);
+        assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MyDiffClassLoader.loader2);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class c5
         Class c5_class = MyDiffClassLoader.loader1.loadClass("c5");
         try {
             c5_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p6 in m2 is exported to m1, not unqualifiedly");
+            throw new RuntimeException("Failed to get IAE (p6 in m2x is exported to m1x, not unqualifiedly");
         } catch (IllegalAccessError e) {
             System.out.println(e.getMessage());
             if (!e.getMessage().contains("does not export")) {
--- a/hotspot/test/runtime/modules/AccessCheck/UmodUpkgDiffCL_NotExp.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/UmodUpkgDiffCL_NotExp.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary class c5 in an unnamed module can read module m2, but package p6 in module m2 is not exported.
- *          Access denied since even though unnamed module can read all modules, p6 in module m2 is not exported at all.
+ * @summary class c5 in an unnamed module can read module m2x, but package p6 in module m2x is not exported.
+ *          Access denied since even though unnamed module can read all modules, p6 in module m2x is not exported at all.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MyDiffClassLoader.java
@@ -47,15 +47,15 @@
 import myloaders.MyDiffClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> no packages
-// ClassLoader2 --> defines m2 --> packages p6
+// ClassLoader1 --> defines m1x --> no packages
+// ClassLoader2 --> defines m2x --> packages p6
 //
-// m1 can read m2
-// package p6 in m2 is not exported
+// m1x can read m2x
+// package p6 in m2x is not exported
 //
-// class c5 defined in unnamed module tries to access p6.c6 defined in m2
+// class c5 defined in unnamed module tries to access p6.c6 defined in m2x
 // Access denied since even though unnamed module can read all modules, p6
-// in module m2 is not exported at all.
+// in module m2x is not exported at all.
 //
 public class UmodUpkgDiffCL_NotExp {
 
@@ -64,53 +64,53 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          none
         // Packages exported: none
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p6
         // Packages exported: none
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .contains("p6")
+                        .packages(Set.of("p6"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MyDiffClassLoader.loader1);
-        map.put("m2", MyDiffClassLoader.loader2);
+        map.put("m1x", MyDiffClassLoader.loader1);
+        map.put("m2x", MyDiffClassLoader.loader2);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MyDiffClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MyDiffClassLoader.loader2);
+        assertTrue(layer.findLoader("m1x") == MyDiffClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MyDiffClassLoader.loader2);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class c5
-        // NOTE: module m1 does not define any packages.
+        // NOTE: module m1x does not define any packages.
         //       c5 will be loaded in an unnamed module.
         Class c5_class = MyDiffClassLoader.loader1.loadClass("c5");
         try {
             c5_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p6 in m2 is not exported to " +
+            throw new RuntimeException("Failed to get IAE (p6 in m2x is not exported to " +
                                        "an unnamed module that c5 is defined within)");
         } catch (IllegalAccessError e) {
           System.out.println(e.getMessage());
--- a/hotspot/test/runtime/modules/AccessCheck/UmodUpkg_ExpQualOther.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/UmodUpkg_ExpQualOther.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test that if class c5 in an unnamed module can read package p6 in module m2, but package p6 in module m2 is
- *          exported qualifiedly to module m3, then class c5 in an unnamed module can not read p6.c6 in module m2.
+ * @summary Test that if class c5 in an unnamed module can read package p6 in module m2x, but package p6 in module m2x is
+ *          exported qualifiedly to module m3x, then class c5 in an unnamed module can not read p6.c6 in module m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MySameClassLoader.java
@@ -47,15 +47,15 @@
 import myloaders.MySameClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> no packages
-//                  defines m2 --> packages p6
-//                  defines m3 --> packages p3
+// ClassLoader1 --> defines m1x --> no packages
+//                  defines m2x --> packages p6
+//                  defines m3x --> packages p3
 //
-// m1 can read m2
-// package p6 in m2 is exported to m3
+// m1x can read m2x
+// package p6 in m2x is exported to m3x
 //
-// class c5 defined in m1 tries to access p6.c6 defined in m2
-// Access denied since although m1 can read m2, p6 is exported only to m3.
+// class c5 defined in m1x tries to access p6.c6 defined in m2x
+// Access denied since although m1x can read m2x, p6 is exported only to m3x.
 //
 public class UmodUpkg_ExpQualOther {
 
@@ -64,63 +64,63 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1 (need to define m1 to establish the Layer successfully)
-        // Can read:          java.base, m2, m3
+        // Define module:     m1x (need to define m1x to establish the Layer successfully)
+        // Can read:          java.base, m2x, m3x
         // Packages:          none
         // Packages exported: none
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
-                        .requires("m3")
+                        .requires("m2x")
+                        .requires("m3x")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p6
-        // Packages exported: p6 is exported to m3
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        // Packages exported: p6 is exported to m3x
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .exports("p6", Set.of("m3"))
+                        .exports("p6", Set.of("m3x"))
                         .build();
 
-        // Define module:     m3
+        // Define module:     m3x
         // Can read:          java.base
         // Packages:          p3
         // Packages exported: none
-        ModuleDescriptor descriptor_m3 =
-                ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor_m3x =
+                ModuleDescriptor.newModule("m3x")
                         .requires("java.base")
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2, descriptor_m3);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x, descriptor_m3x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MySameClassLoader.loader1);
-        map.put("m2", MySameClassLoader.loader1);
-        map.put("m3", MySameClassLoader.loader1);
+        map.put("m1x", MySameClassLoader.loader1);
+        map.put("m2x", MySameClassLoader.loader1);
+        map.put("m3x", MySameClassLoader.loader1);
 
-        // Create Layer that contains m1, m2 and m3
+        // Create Layer that contains m1x, m2x and m3x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m3") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m1x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m3x") == MySameClassLoader.loader1);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class c5
         Class c5_class = MySameClassLoader.loader1.loadClass("c5");
         try {
             c5_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p6 in m2 is exported to m3, not unqualifiedly to everyone)");
+            throw new RuntimeException("Failed to get IAE (p6 in m2x is exported to m3x, not unqualifiedly to everyone)");
         } catch (IllegalAccessError e) {
             System.out.println(e.getMessage());
             if (!e.getMessage().contains("does not export")) {
--- a/hotspot/test/runtime/modules/AccessCheck/UmodUpkg_NotExp.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/UmodUpkg_NotExp.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test if package p6 in module m2 is not exported, then class c5
- *          in an unnamed module can not access p6.c2 in module m2.
+ * @summary Test if package p6 in module m2x is not exported, then class c5
+ *          in an unnamed module can not access p6.c2 in module m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MySameClassLoader.java
@@ -46,13 +46,13 @@
 import java.util.Set;
 import myloaders.MySameClassLoader;
 
-// ClassLoader1 --> defines m1 --> no packages
-//                  defines m2 --> packages p6
+// ClassLoader1 --> defines m1x --> no packages
+//                  defines m2x --> packages p6
 //
-// m1 can read m2
-// package p6 in m2 is not exported
+// m1x can read m2x
+// package p6 in m2x is not exported
 //
-// class c5 defined in an unnamed module tries to access p6.c2 defined in m2
+// class c5 defined in an unnamed module tries to access p6.c2 defined in m2x
 // Access denied since p6 is not exported.
 //
 public class UmodUpkg_NotExp {
@@ -62,51 +62,51 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          none
         // Packages exported: none
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p6
         // Packages exported: none
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .contains("p6")
+                        .packages(Set.of("p6"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to the same class loader for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MySameClassLoader.loader1);
-        map.put("m2", MySameClassLoader.loader1);
+        map.put("m1x", MySameClassLoader.loader1);
+        map.put("m2x", MySameClassLoader.loader1);
 
-        // Create Layer that contains m1 and m2
+        // Create Layer that contains m1x and m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m1x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MySameClassLoader.loader1);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class c5
         Class c5_class = MySameClassLoader.loader1.loadClass("c5");
         try {
             c5_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p6 in m2 is not exported)");
+            throw new RuntimeException("Failed to get IAE (p6 in m2x is not exported)");
         } catch (IllegalAccessError e) {
           System.out.println(e.getMessage());
           if (!e.getMessage().contains("does not export")) {
--- a/hotspot/test/runtime/modules/AccessCheck/Umod_ExpQualOther.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/Umod_ExpQualOther.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test that if package p2 in module m2 is exported to module m3,
- *          then class p1.c1 in an unnamed module can not read p2.c2 in module m2.
+ * @summary Test that if package p2 in module m2x is exported to module m3x,
+ *          then class p1.c1 in an unnamed module can not read p2.c2 in module m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MySameClassLoader.java
@@ -47,15 +47,15 @@
 import myloaders.MySameClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> no packages
-//                  defines m2 --> packages p2
-//                  defines m3 --> packages p3
+// ClassLoader1 --> defines m1x --> no packages
+//                  defines m2x --> packages p2
+//                  defines m3x --> packages p3
 //
-// m1 can read m2
-// package p2 in m2 is exported to m3
+// m1x can read m2x
+// package p2 in m2x is exported to m3x
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in m2
-// Access denied since although m1 can read m2, p2 is exported only to m3.
+// class p1.c1 defined in m1x tries to access p2.c2 defined in m2x
+// Access denied since although m1x can read m2x, p2 is exported only to m3x.
 //
 public class Umod_ExpQualOther {
 
@@ -64,63 +64,63 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1 (need to define m1 to establish the Layer successfully)
-        // Can read:          java.base, m2, m3
+        // Define module:     m1x (need to define m1x to establish the Layer successfully)
+        // Can read:          java.base, m2x, m3x
         // Packages:          none
         // Packages exported: none
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
-                        .requires("m3")
+                        .requires("m2x")
+                        .requires("m3x")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
-        // Packages exported: p2 is exported to m3
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        // Packages exported: p2 is exported to m3x
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .exports("p2", Set.of("m3"))
+                        .exports("p2", Set.of("m3x"))
                         .build();
 
-        // Define module:     m3
+        // Define module:     m3x
         // Can read:          java.base
         // Packages:          p3
         // Packages exported: none
-        ModuleDescriptor descriptor_m3 =
-                ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor_m3x =
+                ModuleDescriptor.newModule("m3x")
                         .requires("java.base")
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2, descriptor_m3);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x, descriptor_m3x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MySameClassLoader.loader1);
-        map.put("m2", MySameClassLoader.loader1);
-        map.put("m3", MySameClassLoader.loader1);
+        map.put("m1x", MySameClassLoader.loader1);
+        map.put("m2x", MySameClassLoader.loader1);
+        map.put("m3x", MySameClassLoader.loader1);
 
-        // Create Layer that contains m1, m2 and m3
+        // Create Layer that contains m1x, m2x and m3x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m3") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m1x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m3x") == MySameClassLoader.loader1);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
         Class p1_c1_class = MySameClassLoader.loader1.loadClass("p1.c1");
         try {
             p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p2 in m2 is exported to m3, not unqualifiedly to everyone)");
+            throw new RuntimeException("Failed to get IAE (p2 in m2x is exported to m3x, not unqualifiedly to everyone)");
         } catch (IllegalAccessError e) {
             System.out.println(e.getMessage());
             if (!e.getMessage().contains("does not export")) {
--- a/hotspot/test/runtime/modules/AccessCheck/Umod_ExpUnqual.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/Umod_ExpUnqual.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test if package p2 in module m2 is exported unqualifiedly,
- *          then class p1.c1 in an unnamed module can read p2.c2 in module m2.
+ * @summary Test if package p2 in module m2x is exported unqualifiedly,
+ *          then class p1.c1 in an unnamed module can read p2.c2 in module m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MySameClassLoader.java
@@ -47,15 +47,15 @@
 import myloaders.MySameClassLoader;
 
 //
-// ClassLoader1 --> defines m1 --> no packages
-//                  defines m2 --> packages p2
+// ClassLoader1 --> defines m1x --> no packages
+//                  defines m2x --> packages p2
 //
-// m1 can read m2
-// package p2 in m2 is exported unqualifiedly
+// m1x can read m2x
+// package p2 in m2x is exported unqualifiedly
 //
-// class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2
+// class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2x
 // Access allowed, an unnamed module can read all modules and p2 in module
-//           m2 which is exported unqualifiedly.
+//           m2x which is exported unqualifiedly.
 
 public class Umod_ExpUnqual {
 
@@ -64,44 +64,44 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          none
         // Packages exported: none
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
         // Packages exported: p2 is exported unqualifiedly
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
                         .exports("p2")
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MySameClassLoader.loader1);
-        map.put("m2", MySameClassLoader.loader1);
+        map.put("m1x", MySameClassLoader.loader1);
+        map.put("m2x", MySameClassLoader.loader1);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m1x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MySameClassLoader.loader1);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
--- a/hotspot/test/runtime/modules/AccessCheck/Umod_PkgNotExp.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/Umod_PkgNotExp.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +25,8 @@
 
 /*
  * @test
- * @summary Test if package p2 in module m2 is not exported, then class p1.c1
- *          in an unnamed module can not access p2.c2 in module m2.
+ * @summary Test if package p2 in module m2x is not exported, then class p1.c1
+ *          in an unnamed module can not access p2.c2 in module m2x.
  * @modules java.base/jdk.internal.misc
  * @library /test/lib
  * @compile myloaders/MySameClassLoader.java
@@ -46,13 +46,13 @@
 import java.util.Set;
 import myloaders.MySameClassLoader;
 
-// ClassLoader1 --> defines m1 --> no packages
-//                  defines m2 --> packages p2
+// ClassLoader1 --> defines m1x --> no packages
+//                  defines m2x --> packages p2
 //
-// m1 can read m2
-// package p2 in m2 is not exported
+// m1x can read m2x
+// package p2 in m2x is not exported
 //
-// class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2
+// class p1.c1 defined in an unnamed module tries to access p2.c2 defined in m2x
 // Access denied since p2 is not exported.
 //
 public class Umod_PkgNotExp {
@@ -62,51 +62,51 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          none
         // Packages exported: none
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
         // Packages exported: none
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .contains("p2")
+                        .packages(Set.of("p2"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to the same class loader for this test
         Map<String, ClassLoader> map = new HashMap<>();
-        map.put("m1", MySameClassLoader.loader1);
-        map.put("m2", MySameClassLoader.loader1);
+        map.put("m1x", MySameClassLoader.loader1);
+        map.put("m2x", MySameClassLoader.loader1);
 
-        // Create Layer that contains m1 and m2
+        // Create Layer that contains m1x and m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
 
-        assertTrue(layer.findLoader("m1") == MySameClassLoader.loader1);
-        assertTrue(layer.findLoader("m2") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m1x") == MySameClassLoader.loader1);
+        assertTrue(layer.findLoader("m2x") == MySameClassLoader.loader1);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
         Class p1_c1_class = MySameClassLoader.loader1.loadClass("p1.c1");
         try {
             p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p2 in m2 is not exported)");
+            throw new RuntimeException("Failed to get IAE (p2 in m2x is not exported)");
         } catch (IllegalAccessError e) {
           System.out.println(e.getMessage());
           if (!e.getMessage().contains("does not export")) {
--- a/hotspot/test/runtime/modules/AccessCheck/p1/c1Loose.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/p1/c1Loose.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -26,7 +26,7 @@
 
 public class c1Loose {
     public c1Loose() {
-        // Attempt access - access should succeed since m1 is a loose module
+        // Attempt access - access should succeed since m1x is a loose module
         p2.c2 c2_obj = new p2.c2();
         c2_obj.method2();
     }
--- a/hotspot/test/runtime/modules/AccessCheck/p1/c1ReadEdge.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/p1/c1ReadEdge.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,12 +27,12 @@
 
 public class c1ReadEdge {
     public c1ReadEdge() {
-        // Establish read edge from module m1, where c1ReadEdge is defined,
+        // Establish read edge from module m1x, where c1ReadEdge is defined,
         // to the unnamed module, where p2.c2 will be defined.
-        Module m1 = c1ReadEdge.class.getModule();
+        Module m1x = c1ReadEdge.class.getModule();
         ClassLoader loader = c1ReadEdge.class.getClassLoader();
         Module unnamed_module = loader.getUnnamedModule();
-        m1.addReads(unnamed_module);
+        m1x.addReads(unnamed_module);
 
         // Attempt access - access should succeed
         p2.c2 c2_obj = new p2.c2();
--- a/hotspot/test/runtime/modules/AccessCheck/p1/c1ReadEdgeDiffLoader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/p1/c1ReadEdgeDiffLoader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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,32 +28,32 @@
 
 public class c1ReadEdgeDiffLoader {
     public c1ReadEdgeDiffLoader() {
-        // The goal is to establish a read edge between module m1
+        // The goal is to establish a read edge between module m1x
         // which is the module where p1.c1ReadEdgeDiffLoader is defined,
         // and the unnamed module that defines p2.c2.  This must be
         // done in 2 steps:
         //
-        // Step #1: Establish a read edge between m1, where c1ReadEdgeDiffLoader
+        // Step #1: Establish a read edge between m1x, where c1ReadEdgeDiffLoader
         //          is defined, and the System ClassLoader's unnamed module,
         //          where MyDiffClassLoader is defined. This read edge
         //          is needed before we can obtain MyDiffClassLoader.loader2's unnamed module.
         //
-        // Step #2: Establish a read edge between m1, where c1ReadEdgeDiffLoader
+        // Step #2: Establish a read edge between m1x, where c1ReadEdgeDiffLoader
         //          is defined, and the MyDiffClassLoader.loader2's unnamed module,
         //          where p2.c2 will be defined.
 
-        // Step #1: read edge m1 -> System ClassLoader's unnamed module
-        Module m1 = c1ReadEdgeDiffLoader.class.getModule();
+        // Step #1: read edge m1x -> System ClassLoader's unnamed module
+        Module m1x = c1ReadEdgeDiffLoader.class.getModule();
         ClassLoader system_loader = ClassLoader.getSystemClassLoader();
-        Module unnamed_module1 = system_loader.getUnnamedModule();
-        m1.addReads(unnamed_module1);
+        Module unnamed_module_one = system_loader.getUnnamedModule();
+        m1x.addReads(unnamed_module_one);
 
-        // Step #2: read edge m1 -> MyDiffClassLoader.loader2's unnamed module
+        // Step #2: read edge m1x -> MyDiffClassLoader.loader2's unnamed module
         ClassLoader loader2 = MyDiffClassLoader.loader2;
-        Module unnamed_module2 = loader2.getUnnamedModule();
-        m1.addReads(unnamed_module2);
+        Module unnamed_module_two = loader2.getUnnamedModule();
+        m1x.addReads(unnamed_module_two);
 
-        // Attempt access - access should succeed since m1 can read
+        // Attempt access - access should succeed since m1x can read
         //                  MyDiffClassLoader.loader2's unnamed module
         p2.c2 c2_obj = new p2.c2();
         c2_obj.method2();
--- a/hotspot/test/runtime/modules/AccessCheck/p3/c3ReadEdge.jcod	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/p3/c3ReadEdge.jcod	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -26,12 +26,12 @@
  * import java.lang.reflect.*;
  * public class c3ReadEdge {
  *    public c3ReadEdge() {
- *       // Establish read edge from module m1, where c3ReadEdge is defined,
+ *       // Establish read edge from module m1x, where c3ReadEdge is defined,
  *       // to the unnamed module, where c4 will be defined.
- *       Module m1 = c3ReadEdge.class.getModule();
+ *       Module m1x = c3ReadEdge.class.getModule();
  *       ClassLoader loader = c3ReadEdge.class.getClassLoader();
  *       Module unnamed_module = loader.getUnnamedModule();
- *       m1.addReads(unnamed_module);
+ *       m1x.addReads(unnamed_module);
  *       // Attempt access - access should succeed
  *       c4 c4_obj = new c4();
  *       c4_obj.method4();
--- a/hotspot/test/runtime/modules/AccessCheck/p3/c3ReadEdgeDiffLoader.jcod	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheck/p3/c3ReadEdgeDiffLoader.jcod	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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,32 +28,32 @@
  *
  * public class c3ReadEdgeDiffLoader {
  *    public c3ReadEdgeDiffLoader() {
- *       // The goal is to establish a read edge between module m1
+ *       // The goal is to establish a read edge between module m1x
  *       // which is the module where p3.c3ReadEdgeDiffLoader is defined,
  *       // and the unnamed module that defines c4.  This must be
  *       // done in 2 steps:
  *       //
- *       // Step #1: Establish a read edge between m1, where c3ReadEdgeDiffLoader
+ *       // Step #1: Establish a read edge between m1x, where c3ReadEdgeDiffLoader
  *       //          is defined, and the System ClassLoader's unnamed module,
  *       //          where MyDiffClassLoader is defined. This read edge
  *       //          is needed before we can obtain MyDiffClassLoader.loader2's unnamed module.
  *       //
- *       // Step #2: Establish a read edge between m1, where c3ReadEdgeDiffLoader
+ *       // Step #2: Establish a read edge between m1x, where c3ReadEdgeDiffLoader
  *       //          is defined, and the MyDiffClassLoader.loader2's unnamed module,
  *       //          where c4 will be defined.
  *
- *       // Step #1: read edge m1 -> System ClassLoader's unnamed module
- *       Module m1 = c3ReadEdgeDiffLoader.class.getModule();
+ *       // Step #1: read edge m1x -> System ClassLoader's unnamed module
+ *       Module m1x = c3ReadEdgeDiffLoader.class.getModule();
  *       ClassLoader system_loader = ClassLoader.getSystemClassLoader();
- *       Module unnamed_module1 = system_loader.getUnnamedModule();
- *       m1.addReads(unnamed_module1);
+ *       Module unnamed_module_one = system_loader.getUnnamedModule();
+ *       m1x.addReads(unnamed_module_one);
  *
- *       // Step #2: read edge m1 -> MyDiffClassLoader.loader2's unnamed module
+ *       // Step #2: read edge m1x -> MyDiffClassLoader.loader2's unnamed module
  *       ClassLoader loader2 = MyDiffClassLoader.loader2;
- *       Module unnamed_module2 = loader2.getUnnamedModule();
- *       m1.addReads(unnamed_module2);
+ *       Module unnamed_module_two = loader2.getUnnamedModule();
+ *       m1x.addReads(unnamed_module_two);
  *
- *       // Attempt access - should succeed since m1 can read
+ *       // Attempt access - should succeed since m1x can read
  *       //                  MyDiffClassLoader.loader2's unnamed module
  *       c4 c4_obj = new c4();
  *       c4_obj.method4();
--- a/hotspot/test/runtime/modules/AccessCheckAllUnnamed.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheckAllUnnamed.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -43,7 +43,7 @@
     // and then test that a class in the unnamed module can access a package in a
     // named module that has been exported to all unnamed modules.
     public static void main(String args[]) throws Throwable {
-        Object m1, m2;
+        Object m1x, m2x;
 
         // Get the java.lang.reflect.Module object for module java.base.
         Class jlObject = Class.forName("java.lang.Object");
@@ -55,16 +55,16 @@
         ClassLoader this_cldr = AccessCheckAllUnnamed.class.getClassLoader();
 
         // Define a module for p3.
-        m1 = ModuleHelper.ModuleObject("module1", this_cldr, new String[] { "p3" });
-        assertNotNull(m1, "Module should not be null");
-        ModuleHelper.DefineModule(m1, "9.0", "m1/there", new String[] { "p3" });
-        ModuleHelper.AddReadsModule(m1, jlObject_jlrM);
+        m1x = ModuleHelper.ModuleObject("module_one", this_cldr, new String[] { "p3" });
+        assertNotNull(m1x, "Module should not be null");
+        ModuleHelper.DefineModule(m1x, "9.0", "m1x/there", new String[] { "p3" });
+        ModuleHelper.AddReadsModule(m1x, jlObject_jlrM);
 
         // Define a module for p2.
-        m2 = ModuleHelper.ModuleObject("module2", this_cldr, new String[] { "p2" });
-        assertNotNull(m2, "Module should not be null");
-        ModuleHelper.DefineModule(m2, "9.0", "m2/there", new String[] { "p2" });
-        ModuleHelper.AddReadsModule(m2, jlObject_jlrM);
+        m2x = ModuleHelper.ModuleObject("module_two", this_cldr, new String[] { "p2" });
+        assertNotNull(m2x, "Module should not be null");
+        ModuleHelper.DefineModule(m2x, "9.0", "m2x/there", new String[] { "p2" });
+        ModuleHelper.AddReadsModule(m2x, jlObject_jlrM);
 
         try {
             ModuleHelper.AddModuleExportsToAllUnnamed((Module)null, "p2");
@@ -74,7 +74,7 @@
         }
 
         try {
-            ModuleHelper.AddModuleExportsToAllUnnamed(m2, null);
+            ModuleHelper.AddModuleExportsToAllUnnamed(m2x, null);
             throw new RuntimeException("Failed to get the expected NPE for null package");
         } catch(NullPointerException e) {
             // Expected
@@ -88,21 +88,21 @@
         }
 
         try {
-            ModuleHelper.AddModuleExportsToAllUnnamed(m2, "p3");
+            ModuleHelper.AddModuleExportsToAllUnnamed(m2x, "p3");
             throw new RuntimeException("Failed to get the expected IAE for package in other module");
         } catch(IllegalArgumentException e) {
             // Expected
         }
 
         try {
-            ModuleHelper.AddModuleExportsToAllUnnamed(m2, "p4");
+            ModuleHelper.AddModuleExportsToAllUnnamed(m2x, "p4");
             throw new RuntimeException("Failed to get the expected IAE for package not in module");
         } catch(IllegalArgumentException e) {
             // Expected
         }
 
-        // Export package p2 in m2 to allUnnamed.
-        ModuleHelper.AddModuleExportsToAllUnnamed(m2, "p2");
+        // Export package p2 in m2x to allUnnamed.
+        ModuleHelper.AddModuleExportsToAllUnnamed(m2x, "p2");
 
         // p1.c1's ctor tries to call a method in p2.c2.  This should succeed because
         // p1 is in an unnamed module and p2.c2 is exported to all unnamed modules.
--- a/hotspot/test/runtime/modules/AccessCheckExp.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheckExp.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -39,10 +39,10 @@
 
 public class AccessCheckExp {
 
-    // Test that if module1 can read module2, but package p2 in module2 is not
-    // exported then class p1.c1 in module1 can not read p2.c2 in module2.
+    // Test that if module_one can read module_two, but package p2 in module_two is not
+    // exported then class p1.c1 in module_one can not read p2.c2 in module_two.
     public static void main(String args[]) throws Throwable {
-        Object m1, m2;
+        Object m1x, m2x;
 
         // Get the java.lang.reflect.Module object for module java.base.
         Class jlObject = Class.forName("java.lang.Object");
@@ -54,28 +54,28 @@
         ClassLoader this_cldr = AccessCheckExp.class.getClassLoader();
 
         // Define a module for p1.
-        m1 = ModuleHelper.ModuleObject("module1", this_cldr, new String[] { "p1" });
-        assertNotNull(m1, "Module should not be null");
-        ModuleHelper.DefineModule(m1, "9.0", "m1/here", new String[] { "p1" });
-        ModuleHelper.AddReadsModule(m1, jlObject_jlrM);
+        m1x = ModuleHelper.ModuleObject("module_one", this_cldr, new String[] { "p1" });
+        assertNotNull(m1x, "Module should not be null");
+        ModuleHelper.DefineModule(m1x, "9.0", "m1x/here", new String[] { "p1" });
+        ModuleHelper.AddReadsModule(m1x, jlObject_jlrM);
 
         // Define a module for p2.
-        m2 = ModuleHelper.ModuleObject("module2", this_cldr, new String[] { "p2" });
-        assertNotNull(m2, "Module should not be null");
-        ModuleHelper.DefineModule(m2, "9.0", "m2/there", new String[] { "p2" });
-        ModuleHelper.AddReadsModule(m2, jlObject_jlrM);
+        m2x = ModuleHelper.ModuleObject("module_two", this_cldr, new String[] { "p2" });
+        assertNotNull(m2x, "Module should not be null");
+        ModuleHelper.DefineModule(m2x, "9.0", "m2x/there", new String[] { "p2" });
+        ModuleHelper.AddReadsModule(m2x, jlObject_jlrM);
 
-        // Make package p1 in m1 visible to everyone.
-        ModuleHelper.AddModuleExportsToAll(m1, "p1");
+        // Make package p1 in m1x visible to everyone.
+        ModuleHelper.AddModuleExportsToAll(m1x, "p1");
 
         // p1.c1's ctor tries to call a method in p2.c2, but p2.c2 is not
         // exported.  So should get IllegalAccessError.
-        ModuleHelper.AddReadsModule(m1, m2);
+        ModuleHelper.AddReadsModule(m1x, m2x);
 
         Class p1_c1_class = Class.forName("p1.c1");
         try {
             p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p2 in m2 is not exported");
+            throw new RuntimeException("Failed to get IAE (p2 in m2x is not exported");
         } catch (IllegalAccessError f) {
             System.out.println(f.getMessage());
             if (!f.getMessage().contains("does not export")) {
--- a/hotspot/test/runtime/modules/AccessCheckJavaBase.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheckJavaBase.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,16 +38,16 @@
 
 public class AccessCheckJavaBase {
 
-    // Test that a class defined to module2 always can read java.base.
+    // Test that a class defined to module_two always can read java.base.
     public static void main(String args[]) throws Throwable {
         // Get the class loader for AccessCheckJavaBase and assume it's also used to
         // load class p2.c2.
         ClassLoader this_cldr = AccessCheckJavaBase.class.getClassLoader();
 
         // Define a module for p2.
-        Object m2 = ModuleHelper.ModuleObject("module2", this_cldr, new String[] { "p2" });
-        assertNotNull(m2, "Module should not be null");
-        ModuleHelper.DefineModule(m2, "9.0", "m2/there", new String[] { "p2" });
+        Object m2x = ModuleHelper.ModuleObject("module_two", this_cldr, new String[] { "p2" });
+        assertNotNull(m2x, "Module should not be null");
+        ModuleHelper.DefineModule(m2x, "9.0", "m2x/there", new String[] { "p2" });
 
         // p2.c2 can read its superclass java.lang.Object defined within java.base
         try {
--- a/hotspot/test/runtime/modules/AccessCheckRead.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheckRead.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -39,10 +39,10 @@
 
 public class AccessCheckRead {
 
-    // Test that a class in a package in module1 cannot access a class in
-    // a package n module2 if module1 cannot read module2.
+    // Test that a class in a package in module_one cannot access a class in
+    // a package in module_two if module_one cannot read module_two.
     public static void main(String args[]) throws Throwable {
-        Object m1, m2;
+        Object m1x, m2x;
 
         // Get the java.lang.reflect.Module object for module java.base.
         Class jlObject = Class.forName("java.lang.Object");
@@ -54,19 +54,19 @@
         ClassLoader this_cldr = AccessCheckRead.class.getClassLoader();
 
         // Define a module for p1.
-        m1 = ModuleHelper.ModuleObject("module1", this_cldr, new String[] { "p1" });
-        assertNotNull(m1, "Module should not be null");
-        ModuleHelper.DefineModule(m1, "9.0", "m1/here", new String[] { "p1" });
-        ModuleHelper.AddReadsModule(m1, jlObject_jlrM);
+        m1x = ModuleHelper.ModuleObject("module_one", this_cldr, new String[] { "p1" });
+        assertNotNull(m1x, "Module should not be null");
+        ModuleHelper.DefineModule(m1x, "9.0", "m1x/here", new String[] { "p1" });
+        ModuleHelper.AddReadsModule(m1x, jlObject_jlrM);
 
         // Define a module for p2.
-        m2 = ModuleHelper.ModuleObject("module2", this_cldr, new String[] { "p2" });
-        assertNotNull(m2, "Module should not be null");
-        ModuleHelper.DefineModule(m2, "9.0", "m2/there", new String[] { "p2" });
-        ModuleHelper.AddReadsModule(m2, jlObject_jlrM);
+        m2x = ModuleHelper.ModuleObject("module_two", this_cldr, new String[] { "p2" });
+        assertNotNull(m2x, "Module should not be null");
+        ModuleHelper.DefineModule(m2x, "9.0", "m2x/there", new String[] { "p2" });
+        ModuleHelper.AddReadsModule(m2x, jlObject_jlrM);
 
-        // Make package p1 in m1 visible to everyone.
-        ModuleHelper.AddModuleExportsToAll(m1, "p1");
+        // Make package p1 in m1x visible to everyone.
+        ModuleHelper.AddModuleExportsToAll(m1x, "p1");
 
         Class p1_c1_class = Class.forName("p1.c1");
 
@@ -74,7 +74,7 @@
         // cannot read p2's module.  So should get IllegalAccessError.
         try {
             p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (m1 can't read m2)");
+            throw new RuntimeException("Failed to get IAE (m1x can't read m2x)");
         } catch (IllegalAccessError e) {
             System.out.println(e.getMessage());
             if (!e.getMessage().contains("does not read") ||
--- a/hotspot/test/runtime/modules/AccessCheckSuper.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheckSuper.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -48,17 +48,17 @@
         ClassLoader this_cldr = AccessCheckSuper.class.getClassLoader();
 
         // Define a module for p2.
-        Object m2 = ModuleHelper.ModuleObject("module2", this_cldr, new String[] { "p2" });
-        assertNotNull(m2, "Module should not be null");
-        ModuleHelper.DefineModule(m2, "9.0", "m2/there", new String[] { "p2" });
+        Object m2x = ModuleHelper.ModuleObject("module_two", this_cldr, new String[] { "p2" });
+        assertNotNull(m2x, "Module should not be null");
+        ModuleHelper.DefineModule(m2x, "9.0", "m2x/there", new String[] { "p2" });
 
         // Define a module for p3.
-        Object m3 = ModuleHelper.ModuleObject("module3", this_cldr, new String[] { "p3" });
-        assertNotNull(m3, "Module should not be null");
-        ModuleHelper.DefineModule(m3, "9.0", "m3/there", new String[] { "p3" });
+        Object m3x = ModuleHelper.ModuleObject("module_three", this_cldr, new String[] { "p3" });
+        assertNotNull(m3x, "Module should not be null");
+        ModuleHelper.DefineModule(m3x, "9.0", "m3x/there", new String[] { "p3" });
 
-        // Since a readability edge has not been established between module2
-        // and module3, p3.c3 cannot read its superclass p2.c2.
+        // Since a readability edge has not been established between module_two
+        // and module_three, p3.c3 cannot read its superclass p2.c2.
         try {
             Class p3_c3_class = Class.forName("p3.c3");
             throw new RuntimeException("Failed to get IAE (can't read superclass)");
--- a/hotspot/test/runtime/modules/AccessCheckUnnamed.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheckUnnamed.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -42,7 +42,7 @@
     // Test that a class in the unnamed module can not access a package in a
     // named module that has not been unqualifiedly exported.
     public static void main(String args[]) throws Throwable {
-        Object m1, m2;
+        Object m1x, m2x;
 
         // Get the java.lang.reflect.Module object for module java.base.
         Class jlObject = Class.forName("java.lang.Object");
@@ -54,17 +54,17 @@
         ClassLoader this_cldr = AccessCheckUnnamed.class.getClassLoader();
 
         // Define a module for p2.
-        m2 = ModuleHelper.ModuleObject("module2", this_cldr, new String[] { "p2" });
-        assertNotNull(m2, "Module should not be null");
-        ModuleHelper.DefineModule(m2, "9.0", "m2/there", new String[] { "p2" });
-        ModuleHelper.AddReadsModule(m2, jlObject_jlrM);
+        m2x = ModuleHelper.ModuleObject("module_two", this_cldr, new String[] { "p2" });
+        assertNotNull(m2x, "Module should not be null");
+        ModuleHelper.DefineModule(m2x, "9.0", "m2x/there", new String[] { "p2" });
+        ModuleHelper.AddReadsModule(m2x, jlObject_jlrM);
 
         // p1.c1's ctor tries to call a method in p2.c2.  This should fail because
         // p1 is in the unnamed module and p2.c2 is not unqualifiedly exported.
         Class p1_c1_class = Class.forName("p1.c1");
         try {
             Object c1_obj = p1_c1_class.newInstance();
-            throw new RuntimeException("Failed to get IAE (p2 in m2 is not exported to unnamed module)");
+            throw new RuntimeException("Failed to get IAE (p2 in m2x is not exported to unnamed module)");
         } catch (IllegalAccessError f) {
             System.out.println(f.getMessage());
             if (!f.getMessage().contains("does not export p2 to unnamed module")) {
--- a/hotspot/test/runtime/modules/AccessCheckWorks.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/AccessCheckWorks.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -39,11 +39,11 @@
 
 public class AccessCheckWorks {
 
-    // Check that a class in a package in module1 can successfully access a
-    // class in module2 when module1 can read module2 and the class's package
+    // Check that a class in a package in module_one can successfully access a
+    // class in module_two when module_one can read module_two and the class's package
     // has been exported.
     public static void main(String args[]) throws Throwable {
-        Object m1, m2;
+        Object m1x, m2x;
 
         // Get the java.lang.reflect.Module object for module java.base.
         Class jlObject = Class.forName("java.lang.Object");
@@ -55,24 +55,24 @@
         ClassLoader this_cldr = AccessCheckWorks.class.getClassLoader();
 
         // Define a module for p1.
-        m1 = ModuleHelper.ModuleObject("module1", this_cldr, new String[] { "p1" });
-        assertNotNull(m1, "Module should not be null");
-        ModuleHelper.DefineModule(m1, "9.0", "m1/here", new String[] { "p1" });
-        ModuleHelper.AddReadsModule(m1, jlObject_jlrM);
+        m1x = ModuleHelper.ModuleObject("module_one", this_cldr, new String[] { "p1" });
+        assertNotNull(m1x, "Module should not be null");
+        ModuleHelper.DefineModule(m1x, "9.0", "m1x/here", new String[] { "p1" });
+        ModuleHelper.AddReadsModule(m1x, jlObject_jlrM);
 
         // Define a module for p2.
-        m2 = ModuleHelper.ModuleObject("module2", this_cldr, new String[] { "p2" });
-        assertNotNull(m2, "Module should not be null");
-        ModuleHelper.DefineModule(m2, "9.0", "m2/there", new String[] { "p2" });
-        ModuleHelper.AddReadsModule(m2, jlObject_jlrM);
+        m2x = ModuleHelper.ModuleObject("module_two", this_cldr, new String[] { "p2" });
+        assertNotNull(m2x, "Module should not be null");
+        ModuleHelper.DefineModule(m2x, "9.0", "m2x/there", new String[] { "p2" });
+        ModuleHelper.AddReadsModule(m2x, jlObject_jlrM);
 
-        // Make package p1 in m1 visible to everyone.
-        ModuleHelper.AddModuleExportsToAll(m1, "p1");
+        // Make package p1 in m1x visible to everyone.
+        ModuleHelper.AddModuleExportsToAll(m1x, "p1");
 
         // p1.c1's ctor tries to call a method in p2.c2.  This should work because
         // p1's module can read p2's module and p2 is exported to p1's module.
-        ModuleHelper.AddReadsModule(m1, m2);
-        ModuleHelper.AddModuleExports(m2, "p2", m1);
+        ModuleHelper.AddReadsModule(m1x, m2x);
+        ModuleHelper.AddModuleExports(m2x, "p2", m1x);
         Class p1_c1_class = Class.forName("p1.c1");
         p1_c1_class.newInstance();
     }
--- a/hotspot/test/runtime/modules/CCE_module_msg.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/CCE_module_msg.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -83,21 +83,21 @@
         ClassLoader this_cldr = CCE_module_msg.class.getClassLoader();
 
         // Define a module for p2.
-        Object m2 = ModuleHelper.ModuleObject("module2", this_cldr, new String[] { "p2" });
-        assertNotNull(m2, "Module should not be null");
-        ModuleHelper.DefineModule(m2, "9.0", "m2/there", new String[] { "p2" });
-        ModuleHelper.AddReadsModule(m2, jlObject_jlrM);
+        Object m2x = ModuleHelper.ModuleObject("module_two", this_cldr, new String[] { "p2" });
+        assertNotNull(m2x, "Module should not be null");
+        ModuleHelper.DefineModule(m2x, "9.0", "m2x/there", new String[] { "p2" });
+        ModuleHelper.AddReadsModule(m2x, jlObject_jlrM);
 
         try {
-            ModuleHelper.AddModuleExportsToAll(m2, "p2");
+            ModuleHelper.AddModuleExportsToAll(m2x, "p2");
             Object p2Obj = new p2.c2();
             System.out.println((String)p2Obj);
             throw new RuntimeException("ClassCastException wasn't thrown, test failed.");
         } catch (ClassCastException cce) {
             String exception = cce.getMessage();
             System.out.println(exception);
-            if (exception.contains("module2/p2.c2") ||
-                !(exception.contains("module2@") &&
+            if (exception.contains("module_two/p2.c2") ||
+                !(exception.contains("module_two@") &&
                   exception.contains("/p2.c2 cannot be cast to java.base/java.lang.String"))) {
                 throw new RuntimeException("Wrong message: " + exception);
             }
--- a/hotspot/test/runtime/modules/ExportTwice.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/ExportTwice.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -44,7 +44,7 @@
     // Also, check that a package can be exported to a specific package and then
     // exported unqualifiedly.
     public static void main(String args[]) throws Throwable {
-        Object m1, m2, m3;
+        Object m1x, m2x, m3x;
 
         // Get the java.lang.reflect.Module object for module java.base.
         Class jlObject = Class.forName("java.lang.Object");
@@ -56,37 +56,37 @@
         ClassLoader this_cldr = ExportTwice.class.getClassLoader();
 
         // Define a module for p1.
-        m1 = ModuleHelper.ModuleObject("module1", this_cldr, new String[] { "p1" });
-        assertNotNull(m1, "Module should not be null");
-        ModuleHelper.DefineModule(m1, "9.0", "m1/here", new String[] { "p1" });
-        ModuleHelper.AddReadsModule(m1, jlObject_jlrM);
+        m1x = ModuleHelper.ModuleObject("module_one", this_cldr, new String[] { "p1" });
+        assertNotNull(m1x, "Module should not be null");
+        ModuleHelper.DefineModule(m1x, "9.0", "m1x/here", new String[] { "p1" });
+        ModuleHelper.AddReadsModule(m1x, jlObject_jlrM);
 
         // Define a module for p2.
-        m2 = ModuleHelper.ModuleObject("module2", this_cldr, new String[] { "p2" });
-        assertNotNull(m2, "Module should not be null");
-        ModuleHelper.DefineModule(m2, "9.0", "m2/there", new String[] { "p2" });
-        ModuleHelper.AddReadsModule(m2, jlObject_jlrM);
+        m2x = ModuleHelper.ModuleObject("module_two", this_cldr, new String[] { "p2" });
+        assertNotNull(m2x, "Module should not be null");
+        ModuleHelper.DefineModule(m2x, "9.0", "m2x/there", new String[] { "p2" });
+        ModuleHelper.AddReadsModule(m2x, jlObject_jlrM);
 
         // Define a module for p3.
-        m3 = ModuleHelper.ModuleObject("module3", this_cldr, new String[] { "p3" });
-        assertNotNull(m3, "Module should not be null");
-        ModuleHelper.DefineModule(m3, "9.0", "m3/there", new String[] { "p3" });
-        ModuleHelper.AddReadsModule(m3, jlObject_jlrM);
+        m3x = ModuleHelper.ModuleObject("module_three", this_cldr, new String[] { "p3" });
+        assertNotNull(m3x, "Module should not be null");
+        ModuleHelper.DefineModule(m3x, "9.0", "m3x/there", new String[] { "p3" });
+        ModuleHelper.AddReadsModule(m3x, jlObject_jlrM);
 
-        // Make package p1 in m1 visible to everyone.
-        ModuleHelper.AddModuleExportsToAll(m1, "p1");
+        // Make package p1 in m1x visible to everyone.
+        ModuleHelper.AddModuleExportsToAll(m1x, "p1");
 
-        // Try to export p1 only to m2 after it was exported unqualifiedly.  It
+        // Try to export p1 only to m2x after it was exported unqualifiedly.  It
         // should silently succeed.
-        ModuleHelper.AddModuleExports(m1, "p1", m2);
+        ModuleHelper.AddModuleExports(m1x, "p1", m2x);
 
-        // Export p2 to m3 then export it again unqualifiedly.
-        ModuleHelper.AddModuleExports(m2, "p2", m3);
-        ModuleHelper.AddModuleExportsToAll(m2, "p2");
+        // Export p2 to m3x then export it again unqualifiedly.
+        ModuleHelper.AddModuleExports(m2x, "p2", m3x);
+        ModuleHelper.AddModuleExportsToAll(m2x, "p2");
 
         // p1.c1's ctor tries to call a method in p2.c2.  This should work because
         // p1's module can read p2's module and p2 is now exported unqualifiedly.
-        ModuleHelper.AddReadsModule(m1, m2);
+        ModuleHelper.AddReadsModule(m1x, m2x);
         Class p1_c1_class = Class.forName("p1.c1");
         p1_c1_class.newInstance();
     }
--- a/hotspot/test/runtime/modules/IgnoreModulePropertiesTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/IgnoreModulePropertiesTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -67,8 +67,8 @@
     }
 
     public static void main(String[] args) throws Exception {
-        testOption("--add-modules", "java.sqlx", "jdk.module.addmods.0", "java.lang.module.ResolutionException");
-        testOption("--limit-modules", "java.sqlx", "jdk.module.limitmods", "java.lang.module.ResolutionException");
+        testOption("--add-modules", "java.sqlx", "jdk.module.addmods.0", "java.lang.module.FindException");
+        testOption("--limit-modules", "java.sqlx", "jdk.module.limitmods", "java.lang.module.FindException");
         testOption("--add-reads", "xyzz=yyzd", "jdk.module.addreads.0", "WARNING: Unknown module: xyzz");
         testOption("--add-exports", "java.base/xyzz=yyzd", "jdk.module.addexports.0",
                    "WARNING: package xyzz not in java.base");
--- a/hotspot/test/runtime/modules/JVMAddModuleExportToAllUnnamed.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/JVMAddModuleExportToAllUnnamed.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -39,10 +39,10 @@
 
 public class JVMAddModuleExportToAllUnnamed {
 
-    // Check that a class in a package in module1 cannot access a class
+    // Check that a class in a package in module_one cannot access a class
     // that is in the unnamed module if the accessing package is strict.
     public static void main(String args[]) throws Throwable {
-        Object m1;
+        Object m1x;
 
         // Get the java.lang.reflect.Module object for module java.base.
         Class jlObject = Class.forName("java.lang.Object");
@@ -54,13 +54,13 @@
         ClassLoader this_cldr = JVMAddModuleExportToAllUnnamed.class.getClassLoader();
 
         // Define a module for p1.
-        m1 = ModuleHelper.ModuleObject("module1", this_cldr, new String[] { "p1" });
-        assertNotNull(m1, "Module should not be null");
-        ModuleHelper.DefineModule(m1, "9.0", "m1/here", new String[] { "p1" });
-        ModuleHelper.AddReadsModule(m1, jlObject_jlrM);
+        m1x = ModuleHelper.ModuleObject("module_one", this_cldr, new String[] { "p1" });
+        assertNotNull(m1x, "Module should not be null");
+        ModuleHelper.DefineModule(m1x, "9.0", "m1x/here", new String[] { "p1" });
+        ModuleHelper.AddReadsModule(m1x, jlObject_jlrM);
 
-        // Make package p1 in m1 visible to everyone.
-        ModuleHelper.AddModuleExportsToAll(m1, "p1");
+        // Make package p1 in m1x visible to everyone.
+        ModuleHelper.AddModuleExportsToAll(m1x, "p1");
 
         // p1.c1's ctor tries to call a method in p2.c2.  This should not work
         // because p2 is in the unnamed module and p1.c1 is strict.
--- a/hotspot/test/runtime/modules/JVMAddModuleExportsToAll.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/JVMAddModuleExportsToAll.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -43,7 +43,7 @@
     // and then test that a class in the unnamed module can access a package in
     // a named module that has been exported unqualifiedly.
     public static void main(String args[]) throws Throwable {
-        Object m1, m2, m3;
+        Object m1x, m2x, m3x;
 
         // Get the java.lang.reflect.Module object for module java.base.
         Class jlObject = Class.forName("java.lang.Object");
@@ -55,16 +55,16 @@
         ClassLoader this_cldr = JVMAddModuleExportsToAll.class.getClassLoader();
 
         // Define a module for p3.
-        m1 = ModuleHelper.ModuleObject("module1", this_cldr, new String[] { "p3" });
-        assertNotNull(m1, "Module should not be null");
-        ModuleHelper.DefineModule(m1, "9.0", "m1/there", new String[] { "p3" });
-        ModuleHelper.AddReadsModule(m1, jlObject_jlrM);
+        m1x = ModuleHelper.ModuleObject("module_one", this_cldr, new String[] { "p3" });
+        assertNotNull(m1x, "Module should not be null");
+        ModuleHelper.DefineModule(m1x, "9.0", "m1x/there", new String[] { "p3" });
+        ModuleHelper.AddReadsModule(m1x, jlObject_jlrM);
 
         // Define a module for p2.
-        m2 = ModuleHelper.ModuleObject("module2", this_cldr, new String[] { "p2" });
-        assertNotNull(m2, "Module should not be null");
-        ModuleHelper.DefineModule(m2, "9.0", "m2/there", new String[] { "p2" });
-        ModuleHelper.AddReadsModule(m2, jlObject_jlrM);
+        m2x = ModuleHelper.ModuleObject("module_two", this_cldr, new String[] { "p2" });
+        assertNotNull(m2x, "Module should not be null");
+        ModuleHelper.DefineModule(m2x, "9.0", "m2x/there", new String[] { "p2" });
+        ModuleHelper.AddReadsModule(m2x, jlObject_jlrM);
 
         try {
             ModuleHelper.AddModuleExportsToAll((Module)null, "p2");
@@ -74,7 +74,7 @@
         }
 
         try {
-            ModuleHelper.AddModuleExportsToAll(m2, null);
+            ModuleHelper.AddModuleExportsToAll(m2x, null);
             throw new RuntimeException("Failed to get the expected NPE for null package");
         } catch(NullPointerException e) {
             // Expected
@@ -88,26 +88,26 @@
         }
 
         try {
-            ModuleHelper.AddModuleExportsToAll(m2, "p3");
+            ModuleHelper.AddModuleExportsToAll(m2x, "p3");
             throw new RuntimeException("Failed to get the expected IAE for package that is in another module");
         } catch(IllegalArgumentException e) {
             // Expected
         }
 
         try {
-            ModuleHelper.AddModuleExportsToAll(m2, "p4");
+            ModuleHelper.AddModuleExportsToAll(m2x, "p4");
             throw new RuntimeException("Failed to get the expected IAE for package not in any module");
         } catch(IllegalArgumentException e) {
             // Expected
         }
 
-        // Export package p2 in m2 unqualifiedly. Then, do a qualified export
-        // of p2 in m2 to m3.  This should not affect the unqualified export.
-        m3 = ModuleHelper.ModuleObject("module3", this_cldr, new String[] { "p4" });
-        assertNotNull(m3, "Module m3 should not be null");
-        ModuleHelper.DefineModule(m3, "9.0", "m3/there", new String[] { "p4" });
-        ModuleHelper.AddModuleExportsToAll(m2, "p2");
-        ModuleHelper.AddModuleExports(m2, "p2", m3);
+        // Export package p2 in m2x unqualifiedly. Then, do a qualified export
+        // of p2 in m2x to m3x.  This should not affect the unqualified export.
+        m3x = ModuleHelper.ModuleObject("module_three", this_cldr, new String[] { "p4" });
+        assertNotNull(m3x, "Module m3x should not be null");
+        ModuleHelper.DefineModule(m3x, "9.0", "m3x/there", new String[] { "p4" });
+        ModuleHelper.AddModuleExportsToAll(m2x, "p2");
+        ModuleHelper.AddModuleExports(m2x, "p2", m3x);
 
         // p1.c1's ctor tries to call a method in p2.c2.  This should succeed because
         // p1 is in an unnamed module and p2.c2 is exported unqualifiedly.
--- a/hotspot/test/runtime/modules/JVMAddModulePackage.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/JVMAddModulePackage.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -40,25 +40,25 @@
     public static void main(String args[]) throws Throwable {
         MyClassLoader cl1 = new MyClassLoader();
         MyClassLoader cl3 = new MyClassLoader();
-        Object module1, module2, module3;
+        Object module_one, module_two, module_three;
         boolean result;
 
-        module1 = ModuleHelper.ModuleObject("module1", cl1, new String[] { "mypackage" });
-        assertNotNull(module1, "Module should not be null");
-        ModuleHelper.DefineModule(module1, "9.0", "module1/here", new String[] { "mypackage" });
-        module2 = ModuleHelper.ModuleObject("module2", cl1, new String[] { "yourpackage" });
-        assertNotNull(module2, "Module should not be null");
-        ModuleHelper.DefineModule(module2, "9.0", "module2/here", new String[] { "yourpackage" });
-        module3 = ModuleHelper.ModuleObject("module3", cl3, new String[] { "package/num3" });
-        assertNotNull(module3, "Module should not be null");
-        ModuleHelper.DefineModule(module3, "9.0", "module3/here", new String[] { "package/num3" });
+        module_one = ModuleHelper.ModuleObject("module_one", cl1, new String[] { "mypackage" });
+        assertNotNull(module_one, "Module should not be null");
+        ModuleHelper.DefineModule(module_one, "9.0", "module_one/here", new String[] { "mypackage" });
+        module_two = ModuleHelper.ModuleObject("module_two", cl1, new String[] { "yourpackage" });
+        assertNotNull(module_two, "Module should not be null");
+        ModuleHelper.DefineModule(module_two, "9.0", "module_two/here", new String[] { "yourpackage" });
+        module_three = ModuleHelper.ModuleObject("module_three", cl3, new String[] { "package/num3" });
+        assertNotNull(module_three, "Module should not be null");
+        ModuleHelper.DefineModule(module_three, "9.0", "module_three/here", new String[] { "package/num3" });
 
         // Simple call
-        ModuleHelper.AddModulePackage(module1, "new_package");
+        ModuleHelper.AddModulePackage(module_one, "new_package");
 
         // Add a package and export it
-        ModuleHelper.AddModulePackage(module1, "package/num3");
-        ModuleHelper.AddModuleExportsToAll(module1, "package/num3");
+        ModuleHelper.AddModulePackage(module_one, "package/num3");
+        ModuleHelper.AddModuleExportsToAll(module_one, "package/num3");
 
         // Null module argument, expect an NPE
         try {
@@ -78,7 +78,7 @@
 
         // Null package argument, expect an NPE
         try {
-            ModuleHelper.AddModulePackage(module1, null);
+            ModuleHelper.AddModulePackage(module_one, null);
             throw new RuntimeException("Failed to get the expected NPE");
         } catch(NullPointerException e) {
             // Expected
@@ -86,7 +86,7 @@
 
         // Existing package, expect an ISE
         try {
-            ModuleHelper.AddModulePackage(module1, "yourpackage");
+            ModuleHelper.AddModulePackage(module_one, "yourpackage");
             throw new RuntimeException("Failed to get the expected ISE");
         } catch(IllegalStateException e) {
             // Expected
@@ -94,7 +94,7 @@
 
         // Invalid package name, expect an IAE
         try {
-            ModuleHelper.AddModulePackage(module1, "your.package");
+            ModuleHelper.AddModulePackage(module_one, "your.package");
             throw new RuntimeException("Failed to get the expected IAE");
         } catch(IllegalArgumentException e) {
             // Expected
@@ -102,7 +102,7 @@
 
         // Invalid package name, expect an IAE
         try {
-            ModuleHelper.AddModulePackage(module1, ";your/package");
+            ModuleHelper.AddModulePackage(module_one, ";your/package");
             throw new RuntimeException("Failed to get the expected IAE");
         } catch(IllegalArgumentException e) {
             // Expected
@@ -110,7 +110,7 @@
 
         // Invalid package name, expect an IAE
         try {
-            ModuleHelper.AddModulePackage(module1, "7[743");
+            ModuleHelper.AddModulePackage(module_one, "7[743");
             throw new RuntimeException("Failed to get the expected IAE");
         } catch(IllegalArgumentException e) {
             // Expected
@@ -118,7 +118,7 @@
 
         // Empty package name, expect an IAE
         try {
-            ModuleHelper.AddModulePackage(module1, "");
+            ModuleHelper.AddModulePackage(module_one, "");
             throw new RuntimeException("Failed to get the expected IAE");
         } catch(IllegalArgumentException e) {
             // Expected
@@ -126,8 +126,8 @@
 
         // Add package named "java" to an module defined to a class loader other than the boot or platform loader.
         try {
-            // module1 is defined to a MyClassLoader class loader.
-            ModuleHelper.AddModulePackage(module1, "java/foo");
+            // module_one is defined to a MyClassLoader class loader.
+            ModuleHelper.AddModulePackage(module_one, "java/foo");
             throw new RuntimeException("Failed to get the expected IAE");
         } catch(IllegalArgumentException e) {
             if (!e.getMessage().contains("prohibited package name")) {
@@ -136,10 +136,10 @@
         }
 
         // Package "javabar" should be ok
-        ModuleHelper.AddModulePackage(module1, "javabar");
+        ModuleHelper.AddModulePackage(module_one, "javabar");
 
         // Package named "java" defined to the boot class loader, should be ok
-        Object module_javabase = module1.getClass().getModule();
+        Object module_javabase = module_one.getClass().getModule();
         ModuleHelper.AddModulePackage(module_javabase, "java/foo");
 
         // Package named "java" defined to the platform class loader, should be ok
--- a/hotspot/test/runtime/modules/JVMDefineModule.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/JVMDefineModule.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,7 +49,7 @@
 /* Invalid test, won't compile.
         // Invalid classloader argument, expect an IAE
         try {
-            m = ModuleHelper.ModuleObject("mymodule1", new Object(), new String[] { "mypackage1" });
+            m = ModuleHelper.ModuleObject("mymodule_one", new Object(), new String[] { "mypackage1" });
             ModuleHelper.DefineModule(m,  "9.0", "mymodule/here", new String[] { "mypackage1" });
             throw new RuntimeException("Failed to get expected IAE for bad loader");
         } catch(IllegalArgumentException e) {
--- a/hotspot/test/runtime/modules/JVMGetModuleByPkgName.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/JVMGetModuleByPkgName.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -79,10 +79,10 @@
         }
 
         MyClassLoader cl1 = new MyClassLoader();
-        Module module1 = (Module)ModuleHelper.ModuleObject("module1", cl1, new String[] { "mypackage" });
-        assertNotNull(module1, "Module should not be null");
-        ModuleHelper.DefineModule(module1, "9.0", "module1/here", new String[] { "mypackage" });
-        if (ModuleHelper.GetModuleByPackageName(cl1, "mypackage") != module1) {
+        Module module_one = (Module)ModuleHelper.ModuleObject("module_one", cl1, new String[] { "mypackage" });
+        assertNotNull(module_one, "Module should not be null");
+        ModuleHelper.DefineModule(module_one, "9.0", "module_one/here", new String[] { "mypackage" });
+        if (ModuleHelper.GetModuleByPackageName(cl1, "mypackage") != module_one) {
             throw new RuntimeException("Wrong module returned for cl1 mypackage");
         }
     }
--- a/hotspot/test/runtime/modules/ModuleHelper.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/ModuleHelper.java	Thu Mar 16 20:47:03 2017 +0000
@@ -84,7 +84,7 @@
         }
 
         ModuleDescriptor descriptor =
-            ModuleDescriptor.module(name).contains(pkg_set).build();
+            ModuleDescriptor.newModule(name).packages(pkg_set).build();
         URI uri = URI.create("module:/" + name);
 
         return java.lang.reflect.ModuleHelper.newModule(loader, descriptor);
--- a/hotspot/test/runtime/modules/ModuleOptionsTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/ModuleOptionsTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -43,7 +43,7 @@
         ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
             "--add-modules=i_dont_exist", "--add-modules=java.base", "-version");
         OutputAnalyzer output = new OutputAnalyzer(pb.start());
-        output.shouldContain("ResolutionException");
+        output.shouldContain("FindException");
         output.shouldContain("i_dont_exist");
         output.shouldHaveExitValue(1);
 
--- a/hotspot/test/runtime/modules/ModuleStress/CustomSystemClassLoader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/ModuleStress/CustomSystemClassLoader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,7 +22,7 @@
  */
 
 /**
- * A custom system ClassLoader to define the module "m2" to during iterations of
+ * A custom system ClassLoader to define the module "m2x" to during iterations of
  * differing test runs within the test ModuleStress.java
  */
 public class CustomSystemClassLoader extends ClassLoader {
--- a/hotspot/test/runtime/modules/ModuleStress/ModuleNonBuiltinCLMain.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/ModuleStress/ModuleNonBuiltinCLMain.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -35,15 +35,15 @@
 import java.util.Set;
 
 //
-// ClassLoader1 --> defines m1 --> packages p1
-// ClassLoader2 --> defines m2 --> packages p2
-// Java System Class Loader --> defines m3 --> packages p3
+// ClassLoader1 --> defines m1x --> packages p1
+// ClassLoader2 --> defines m2x --> packages p2
+// Java System Class Loader --> defines m3x --> packages p3
 //
-// m1 can read m2
-// package p2 in m2 is exported to m1 and m3
+// m1x can read m2x
+// package p2 in m2x is exported to m1x and m3x
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in m2
-// Access allowed since m1 can read m2 and package p2 is exported to m1.
+// class p1.c1 defined in m1x tries to access p2.c2 defined in m2x
+// Access allowed since m1x can read m2x and package p2 is exported to m1x.
 //
 public class ModuleNonBuiltinCLMain {
 
@@ -52,62 +52,62 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          p1
         // Packages exported: p1 is exported to unqualifiedly
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .exports("p1")
                         .build();
 
-        // Define module:     m2
-        // Can read:          java.base, m3
+        // Define module:     m2x
+        // Can read:          java.base, m3x
         // Packages:          p2
-        // Packages exported: package p2 is exported to m1 and m3
+        // Packages exported: package p2 is exported to m1x and m3x
         Set<String> targets = new HashSet<>();
-        targets.add("m1");
-        targets.add("m3");
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        targets.add("m1x");
+        targets.add("m3x");
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .requires("m3")
+                        .requires("m3x")
                         .exports("p2", targets)
                         .build();
 
-        // Define module:     m3
+        // Define module:     m3x
         // Can read:          java.base
         // Packages:          p3
         // Packages exported: none
-        ModuleDescriptor descriptor_m3 =
-                ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor_m3x =
+                ModuleDescriptor.newModule("m3x")
                         .requires("java.base")
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2, descriptor_m3);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x, descriptor_m3x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to differing user defined class loaders for this test
         Map<String, ClassLoader> map = new HashMap<>();
         Loader1 cl1 = new Loader1();
         Loader2 cl2 = new Loader2();
         ClassLoader cl3 = ClassLoader.getSystemClassLoader();
-        map.put("m1", cl1);
-        map.put("m2", cl2);
-        map.put("m3", cl3);
+        map.put("m1x", cl1);
+        map.put("m2x", cl2);
+        map.put("m3x", cl3);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
-        assertTrue(layer.findLoader("m1") == cl1);
-        assertTrue(layer.findLoader("m2") == cl2);
-        assertTrue(layer.findLoader("m3") == cl3);
+        assertTrue(layer.findLoader("m1x") == cl1);
+        assertTrue(layer.findLoader("m2x") == cl2);
+        assertTrue(layer.findLoader("m3x") == cl3);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
@@ -115,7 +115,7 @@
         try {
             p1_c1_class.newInstance();
         } catch (IllegalAccessError e) {
-            throw new RuntimeException("Test Failed, an IAE should not be thrown since p2 is exported qualifiedly to m1");
+            throw new RuntimeException("Test Failed, an IAE should not be thrown since p2 is exported qualifiedly to m1x");
         }
     }
 
--- a/hotspot/test/runtime/modules/ModuleStress/ModuleSameCLMain.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/ModuleStress/ModuleSameCLMain.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -34,14 +34,14 @@
 import java.util.Set;
 
 //
-// ClassLoader1 --> defines m1 --> packages p1
-// ClassLoader1 --> defines m2 --> packages p2
+// ClassLoader1 --> defines m1x --> packages p1
+// ClassLoader1 --> defines m2x --> packages p2
 //
-// m1 can read m2
-// package p2 in m2 is exported to m1
+// m1x can read m2x
+// package p2 in m2x is exported to m1x
 //
-// class p1.c1 defined in m1 tries to access p2.c2 defined in m2
-// Access allowed since m1 can read m2 and package p2 is exported to m1.
+// class p1.c1 defined in m1x tries to access p2.c2 defined in m2x
+// Access allowed since m1x can read m2x and package p2 is exported to m1x.
 //
 public class ModuleSameCLMain {
 
@@ -50,45 +50,45 @@
     // publically defined classes within packages of those modules.
     public void createLayerOnBoot() throws Throwable {
 
-        // Define module:     m1
-        // Can read:          java.base, m2
+        // Define module:     m1x
+        // Can read:          java.base, m2x
         // Packages:          p1
         // Packages exported: p1 is exported to unqualifiedly
-        ModuleDescriptor descriptor_m1 =
-                ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor_m1x =
+                ModuleDescriptor.newModule("m1x")
                         .requires("java.base")
-                        .requires("m2")
+                        .requires("m2x")
                         .exports("p1")
                         .build();
 
-        // Define module:     m2
+        // Define module:     m2x
         // Can read:          java.base
         // Packages:          p2
-        // Packages exported: package p2 is exported to m1
-        ModuleDescriptor descriptor_m2 =
-                ModuleDescriptor.module("m2")
+        // Packages exported: package p2 is exported to m1x
+        ModuleDescriptor descriptor_m2x =
+                ModuleDescriptor.newModule("m2x")
                         .requires("java.base")
-                        .exports("p2", Set.of("m1"))
+                        .exports("p2", Set.of("m1x"))
                         .build();
 
         // Set up a ModuleFinder containing all modules for this layer.
-        ModuleFinder finder = ModuleLibrary.of(descriptor_m1, descriptor_m2);
+        ModuleFinder finder = ModuleLibrary.of(descriptor_m1x, descriptor_m2x);
 
-        // Resolves "m1"
+        // Resolves "m1x"
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1x"));
 
         // map each module to the same class loader for this test
         Map<String, ClassLoader> map = new HashMap<>();
         Loader1 cl1 = new Loader1();
-        map.put("m1", cl1);
-        map.put("m2", cl1);
+        map.put("m1x", cl1);
+        map.put("m2x", cl1);
 
-        // Create Layer that contains m1 & m2
+        // Create Layer that contains m1x & m2x
         Layer layer = Layer.boot().defineModules(cf, map::get);
-        assertTrue(layer.findLoader("m1") == cl1);
-        assertTrue(layer.findLoader("m2") == cl1);
+        assertTrue(layer.findLoader("m1x") == cl1);
+        assertTrue(layer.findLoader("m2x") == cl1);
         assertTrue(layer.findLoader("java.base") == null);
 
         // now use the same loader to load class p1.c1
@@ -96,7 +96,7 @@
         try {
             p1_c1_class.newInstance();
         } catch (IllegalAccessError e) {
-            throw new RuntimeException("Test Failed, an IAE should not be thrown since p2 is exported qualifiedly to m1");
+            throw new RuntimeException("Test Failed, an IAE should not be thrown since p2 is exported qualifiedly to m1x");
         }
     }
 
--- a/hotspot/test/runtime/modules/ModuleStress/ModuleStress.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/ModuleStress/ModuleStress.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -83,7 +83,7 @@
              InMemoryJavaCompiler.compile("p1.c1", source1), System.getProperty("test.classes"));
 
         // Test #2: Load two modules defined to the same customer class loader.
-        //   m1's module readability list and package p2's exportability should
+        //   m1x's module readability list and package p2's exportability should
         //   not be walked at a GC safepoint since both modules are defined to
         //   the same loader and thus have the exact same life cycle.
         pb = ProcessTools.createJavaProcessBuilder(
@@ -97,7 +97,7 @@
           .shouldHaveExitValue(0);
 
         // Test #3: Load two modules in differing custom class loaders.
-        //   m1's module readability list and package p2's exportability list must
+        //   m1x's module readability list and package p2's exportability list must
         //   be walked at a GC safepoint since both modules are defined to non-builtin
         //   class loaders which could die and thus be unloaded.
         pb = ProcessTools.createJavaProcessBuilder(
@@ -106,15 +106,15 @@
              "ModuleNonBuiltinCLMain");
 
         oa = new OutputAnalyzer(pb.start());
-        oa.shouldContain("module m1 reads list must be walked")
-          .shouldContain("package p2 defined in module m2, exports list must be walked")
-          .shouldNotContain("module m2 reads list must be walked")
+        oa.shouldContain("module m1x reads list must be walked")
+          .shouldContain("package p2 defined in module m2x, exports list must be walked")
+          .shouldNotContain("module m2x reads list must be walked")
           .shouldHaveExitValue(0);
 
         // Test #4: Load two modules in differing custom class loaders,
         //   of which one has been designated as the custom system class loader
         //   via -Djava.system.class.loader=CustomSystemClassLoader. Since
-        //   m3 is defined to the system class loader, m2's module readability
+        //   m3x is defined to the system class loader, m2x's module readability
         //   list does not have to be walked at a GC safepoint, but package p2's
         //   exportability list does.
         pb = ProcessTools.createJavaProcessBuilder(
@@ -124,8 +124,8 @@
              "ModuleNonBuiltinCLMain");
 
         oa = new OutputAnalyzer(pb.start());
-        oa.shouldContain("package p2 defined in module m2, exports list must be walked")
-          .shouldNotContain("module m2 reads list must be walked")
+        oa.shouldContain("package p2 defined in module m2x, exports list must be walked")
+          .shouldNotContain("module m2x reads list must be walked")
           .shouldHaveExitValue(0);
 
     }
--- a/hotspot/test/runtime/modules/ModuleStress/src/jdk.test/test/Main.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/ModuleStress/src/jdk.test/test/Main.java	Thu Mar 16 20:47:03 2017 +0000
@@ -48,7 +48,7 @@
 
         Configuration cf = layerBoot
                 .configuration()
-                .resolveRequires(ModuleFinder.of(), finder, Set.of(MODULE_NAME));
+                .resolve(ModuleFinder.of(), finder, Set.of(MODULE_NAME));
 
         Module testModule = Main.class.getModule();
         ClassLoader scl = ClassLoader.getSystemClassLoader();
--- a/hotspot/test/runtime/modules/ModuleStress/src/jdk.test/test/MainGC.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/ModuleStress/src/jdk.test/test/MainGC.java	Thu Mar 16 20:47:03 2017 +0000
@@ -48,7 +48,7 @@
 
         Configuration cf = layerBoot
                 .configuration()
-                .resolveRequires(ModuleFinder.of(), finder, Set.of(MODULE_NAME));
+                .resolve(ModuleFinder.of(), finder, Set.of(MODULE_NAME));
 
         Module testModule = MainGC.class.getModule();
         ClassLoader scl = ClassLoader.getSystemClassLoader();
--- a/hotspot/test/runtime/modules/PatchModule/PatchModuleDupModule.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/runtime/modules/PatchModule/PatchModuleDupModule.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,8 +38,8 @@
 
   public static void main(String args[]) throws Exception {
     ProcessBuilder pb = ProcessTools.createJavaProcessBuilder(
-      "--patch-module=module1=module1_dir",
-      "--patch-module=module1=module1_dir",
+      "--patch-module=module_one=module_one_dir",
+      "--patch-module=module_one=module_one_dir",
       "-version");
     OutputAnalyzer output = new OutputAnalyzer(pb.start());
     output.shouldContain("java.lang.ExceptionInInitializerError");
--- a/hotspot/test/serviceability/jvmti/GetModulesInfo/JvmtiGetAllModulesTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/serviceability/jvmti/GetModulesInfo/JvmtiGetAllModulesTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -82,12 +82,11 @@
         Asserts.assertEquals(Layer.boot().modules(), getModulesJVMTI());
 
         // Load a new named module
-        ModuleDescriptor descriptor
-                = ModuleDescriptor.module(MY_MODULE_NAME).build();
+        ModuleDescriptor descriptor = ModuleDescriptor.newModule(MY_MODULE_NAME).build();
         ModuleFinder finder = finderOf(descriptor);
         ClassLoader loader = new ClassLoader() {};
         Configuration parent = Layer.boot().configuration();
-        Configuration cf = parent.resolveRequires(finder, ModuleFinder.of(), Set.of(MY_MODULE_NAME));
+        Configuration cf = parent.resolve(finder, ModuleFinder.of(), Set.of(MY_MODULE_NAME));
         Layer my = Layer.boot().defineModules(cf, m -> loader);
 
         // Verify that the loaded module is indeed reported by JVMTI
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/serviceability/sa/LingeredAppWithLargeArray.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2017, 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 jdk.test.lib.apps.LingeredApp;
+
+public class LingeredAppWithLargeArray extends LingeredApp {
+    public static void main(String args[]) {
+        int[] hugeArray = new int[Integer.MAX_VALUE/2];
+        LingeredApp.main(args);
+    }
+ }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/hotspot/test/serviceability/sa/TestHeapDumpForLargeArray.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,117 @@
+/*
+ * Copyright (c) 2017, 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.util.ArrayList;
+import java.util.List;
+import java.io.File;
+import java.nio.file.Files;
+import java.io.IOException;
+import java.io.BufferedInputStream;
+import java.util.stream.Collectors;
+import java.io.FileInputStream;
+
+import sun.jvm.hotspot.HotSpotAgent;
+import sun.jvm.hotspot.debugger.*;
+
+import jdk.test.lib.apps.LingeredApp;
+import jdk.test.lib.JDKToolLauncher;
+import jdk.test.lib.JDKToolFinder;
+import jdk.test.lib.Platform;
+import jdk.test.lib.process.ProcessTools;
+import jdk.test.lib.process.OutputAnalyzer;
+import jdk.test.lib.Utils;
+import jdk.test.lib.Asserts;
+
+/*
+ * @test
+ * @library /test/lib
+ * @bug 8171084
+ * @requires (vm.bits == "64" & os.maxMemory > 8g)
+ * @modules java.base/jdk.internal.misc
+ *          jdk.hotspot.agent/sun.jvm.hotspot
+ *          jdk.hotspot.agent/sun.jvm.hotspot.utilities
+ *          jdk.hotspot.agent/sun.jvm.hotspot.oops
+ *          jdk.hotspot.agent/sun.jvm.hotspot.debugger
+ * @run main/timeout=1800/othervm -Xmx8g TestHeapDumpForLargeArray
+ */
+
+public class TestHeapDumpForLargeArray {
+
+    private static LingeredAppWithLargeArray theApp = null;
+
+    private static void attachAndDump(String heapDumpFileName,
+                                      long lingeredAppPid) throws Exception {
+
+        JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jhsdb");
+        launcher.addToolArg("jmap");
+        launcher.addToolArg("--binaryheap");
+        launcher.addToolArg("--dumpfile");
+        launcher.addToolArg(heapDumpFileName);
+        launcher.addToolArg("--pid");
+        launcher.addToolArg(Long.toString(lingeredAppPid));
+
+        ProcessBuilder processBuilder = new ProcessBuilder();
+        processBuilder.command(launcher.getCommand());
+        System.out.println(
+            processBuilder.command().stream().collect(Collectors.joining(" ")));
+
+        OutputAnalyzer SAOutput = ProcessTools.executeProcess(processBuilder);
+        SAOutput.shouldHaveExitValue(0);
+        SAOutput.shouldNotContain("Heap segment size overflow");
+        SAOutput.shouldContain("truncating to");
+        SAOutput.shouldContain("heap written to");
+        SAOutput.shouldContain(heapDumpFileName);
+        System.out.println(SAOutput.getOutput());
+
+    }
+
+    public static void main (String... args) throws Exception {
+
+        String heapDumpFileName = "LargeArrayHeapDump.bin";
+
+        if (!Platform.shouldSAAttach()) {
+            System.out.println(
+               "SA attach not expected to work - test skipped.");
+            return;
+        }
+
+        File heapDumpFile = new File(heapDumpFileName);
+        if (heapDumpFile.exists()) {
+            heapDumpFile.delete();
+        }
+
+        try {
+            List<String> vmArgs = new ArrayList<String>();
+            vmArgs.add("-XX:+UsePerfData");
+            vmArgs.add("-Xmx8g");
+            vmArgs.addAll(Utils.getVmOptions());
+
+            theApp = new LingeredAppWithLargeArray();
+            LingeredApp.startApp(vmArgs, theApp);
+            attachAndDump(heapDumpFileName, theApp.getPid());
+        } finally {
+            LingeredApp.stopApp(theApp);
+            heapDumpFile.delete();
+        }
+    }
+}
--- a/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/serviceability/sa/jmap-hprof/JMapHProfLargeHeapTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -53,7 +53,6 @@
 
 public class JMapHProfLargeHeapTest {
     private static final String HEAP_DUMP_FILE_NAME = "heap.bin";
-    private static final String HPROF_HEADER_1_0_1 = "JAVA PROFILE 1.0.1";
     private static final String HPROF_HEADER_1_0_2 = "JAVA PROFILE 1.0.2";
     private static final long M = 1024L;
     private static final long G = 1024L * M;
@@ -65,9 +64,7 @@
         }
 
         // All heap dumps should create 1.0.2 file format
-        // Hotspot internal heapdumper always use HPROF_HEADER_1_0_2 format,
-        // but SA heapdumper still use HPROF_HEADER_1_0_1 for small heaps
-        testHProfFileFormat("-Xmx1g", 22 * M, HPROF_HEADER_1_0_1);
+        testHProfFileFormat("-Xmx1g", 22 * M, HPROF_HEADER_1_0_2);
 
         /**
          * This test was deliberately commented out since the test system lacks
--- a/hotspot/test/testlibrary/jittester/Makefile	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/testlibrary/jittester/Makefile	Thu Mar 16 20:47:03 2017 +0000
@@ -108,7 +108,7 @@
 	$(shell if [ ! -d $(CLASSES_DIR) ]; then mkdir -p $(CLASSES_DIR); fi)
 
 install: clean_testbase testgroup testroot copytestlibrary copyaot JAR cleantmp
-	$(JAVA) --add-exports=java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED -ea -jar $(DIST_JAR) $(APPLICATION_ARGS)
+	$(JAVA) --add-exports=java.base/jdk.internal.org.objectweb.asm=ALL-UNNAMED --add-opens java.base/java.util=ALL-UNNAMED -ea -jar $(DIST_JAR) $(APPLICATION_ARGS)
 
 clean_testbase:
 	@rm -rf $(TESTBASE_DIR)
--- a/hotspot/test/testlibrary/jittester/src/jdk/test/lib/jittester/TestsGenerator.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/hotspot/test/testlibrary/jittester/src/jdk/test/lib/jittester/TestsGenerator.java	Thu Mar 16 20:47:03 2017 +0000
@@ -43,6 +43,7 @@
     protected final Path generatorDir;
     protected final Function<String, String[]> preRunActions;
     protected final String jtDriverOptions;
+    private static final String DISABLE_WARNINGS = "-XX:-PrintWarnings";
 
     protected TestsGenerator(String suffix) {
         this(suffix, s -> new String[0], "");
@@ -57,8 +58,8 @@
 
     protected void generateGoldenOut(String mainClassName) {
         String classPath = getRoot() + File.pathSeparator + generatorDir;
-        ProcessBuilder pb = new ProcessBuilder(JAVA, "-Xint", "-Xverify", "-cp", classPath,
-                mainClassName);
+        ProcessBuilder pb = new ProcessBuilder(JAVA, "-Xint", DISABLE_WARNINGS, "-Xverify",
+                "-cp", classPath, mainClassName);
         String goldFile = mainClassName + ".gold";
         try {
             runProcess(pb, generatorDir.resolve(goldFile).toString());
@@ -128,6 +129,8 @@
                   .append("\n");
         }
         header.append(" * @run driver jdk.test.lib.jittester.jtreg.JitTesterDriver ")
+              .append(DISABLE_WARNINGS)
+              .append(" ")
               .append(jtDriverOptions)
               .append(" ")
               .append(mainClassName)
--- a/jaxp/.hgtags	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/.hgtags	Thu Mar 16 20:47:03 2017 +0000
@@ -396,5 +396,9 @@
 13c6906bfc861d99dc35a19c80b7a99f0b0ac58d jdk-9+151
 7e3da313b1746578da648155e37dd8526e83153d jdk-9+152
 1384504d2cd0e55c5e0becaeaf40ab05cae959d6 jdk-9+153
+0908877116d17c6e59092ec7d53ef687a96d3278 jdk-10+0
 7fa738305436d14c0926df0f04892890cacc766b jdk-9+154
 48fa77af153288b08ba794e1616a7b0685f3b67e jdk-9+155
+e930c373aaa4e0e712c9a25ba4b03d473b48c294 jdk-9+156
+412df235a8a229469a2cb9e7bb274d43277077d2 jdk-9+157
+60e670a65e07cc309951bd838b484401e6dd7847 jdk-9+158
--- a/jaxp/.jcheck/conf	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/.jcheck/conf	Thu Mar 16 20:47:03 2017 +0000
@@ -1,1 +1,1 @@
-project=jdk9
+project=jdk10
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -438,7 +438,7 @@
         Layer bootLayer = Layer.boot();
 
         Configuration cf = bootLayer.configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of(mn));
+                .resolve(finder, ModuleFinder.of(), Set.of(mn));
 
         PrivilegedAction<Layer> pa = () -> bootLayer.defineModules(cf, name -> loader);
         Layer layer = AccessController.doPrivileged(pa);
@@ -483,10 +483,11 @@
             String pn = _tfactory.getPackageName();
             assert pn != null && pn.length() > 0;
 
-            ModuleDescriptor descriptor = ModuleDescriptor.module(mn)
-                    .requires("java.xml")
-                    .exports(pn)
-                    .build();
+            ModuleDescriptor descriptor =
+                ModuleDescriptor.newModule(mn, Set.of(ModuleDescriptor.Modifier.SYNTHETIC))
+                                .requires("java.xml")
+                                .exports(pn)
+                                .build();
 
             Module m = createModule(descriptor, loader);
 
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  */
 
 /*
@@ -743,7 +743,7 @@
             // scan XMLDecl
             try {
                 if (fEntityScanner.skipString(XMLDECL)) {
-                    if (fEntityScanner.peekChar() == ' ') {
+                    if (XMLChar.isSpace(fEntityScanner.peekChar())) {
                         fMarkupDepth++;
                         scanXMLDeclOrTextDecl(false);
                     } else {
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xerces/internal/parsers/XML11Configuration.java	Thu Mar 16 20:47:03 2017 +0000
@@ -415,9 +415,15 @@
     /** Current DTD scanner. */
     protected XMLDTDScanner fCurrentDTDScanner;
 
-    /** Flag indiciating whether XML11 components have been initialized. */
+    /** Flag indicating whether XML11 components have been initialized. */
     private boolean f11Initialized = false;
 
+    /** Flag indicating whether the symbol table instance was specified during construction **/
+    private boolean fSymbolTableProvided = false;
+
+    /** Flag indicating if the symbol table was initialized and never used before that **/
+    private boolean fSymbolTableJustInitialized = true;
+
     //
     // Constructors
     //
@@ -566,15 +572,18 @@
         };
         addRecognizedProperties(recognizedProperties);
 
-        if (symbolTable == null) {
-                symbolTable = new SymbolTable();
+        // Remember if symbolTable was provided from outside
+        fSymbolTableProvided = symbolTable != null;
+        if (!fSymbolTableProvided) {
+            fSymbolTable = new SymbolTable();
+        } else {
+            fSymbolTable = symbolTable;
         }
-        fSymbolTable = symbolTable;
         fProperties.put(SYMBOL_TABLE, fSymbolTable);
 
         fGrammarPool = grammarPool;
         if (fGrammarPool != null) {
-                        fProperties.put(XMLGRAMMAR_POOL, fGrammarPool);
+            fProperties.put(XMLGRAMMAR_POOL, fGrammarPool);
         }
 
         fEntityManager = new XMLEntityManager();
@@ -840,6 +849,7 @@
                 fValidationManager.reset();
                 fVersionDetector.reset(this);
                 fConfigUpdated = true;
+                resetSymbolTable();
                 resetCommon();
 
                 short version = fVersionDetector.determineDocVersion(fInputSource);
@@ -858,15 +868,7 @@
                 // resets and sets the pipeline.
                 fVersionDetector.startDocumentParsing((XMLEntityHandler) fCurrentScanner, version);
                 fInputSource = null;
-            } catch (XNIException ex) {
-                if (PRINT_EXCEPTION_STACK_TRACE)
-                    ex.printStackTrace();
-                throw ex;
-            } catch (IOException ex) {
-                if (PRINT_EXCEPTION_STACK_TRACE)
-                    ex.printStackTrace();
-                throw ex;
-            } catch (RuntimeException ex) {
+            } catch (IOException | RuntimeException ex) {
                 if (PRINT_EXCEPTION_STACK_TRACE)
                     ex.printStackTrace();
                 throw ex;
@@ -879,15 +881,7 @@
 
         try {
             return fCurrentScanner.scanDocument(complete);
-        } catch (XNIException ex) {
-            if (PRINT_EXCEPTION_STACK_TRACE)
-                ex.printStackTrace();
-            throw ex;
-        } catch (IOException ex) {
-            if (PRINT_EXCEPTION_STACK_TRACE)
-                ex.printStackTrace();
-            throw ex;
-        } catch (RuntimeException ex) {
+        } catch (IOException | RuntimeException ex) {
             if (PRINT_EXCEPTION_STACK_TRACE)
                 ex.printStackTrace();
             throw ex;
@@ -1589,6 +1583,23 @@
         }
     }
 
+
+    /**
+     * Reset the symbol table if it wasn't provided during construction
+     * and its not the first time when parse is called after initialization
+     */
+    private void resetSymbolTable() {
+        if (!fSymbolTableProvided) {
+            if (fSymbolTableJustInitialized) {
+                // Skip symbol table reallocation for the first parsing process
+                fSymbolTableJustInitialized = false;
+            } else {
+                fSymbolTable = new SymbolTable();
+                fProperties.put(SYMBOL_TABLE, fSymbolTable);
+            }
+        }
+    }
+
     /**
      * Returns the state of a feature. This method calls getFeature()
      * on ParserConfigurationSettings, bypassing getFeature() on this
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToHTMLStream.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToHTMLStream.java	Thu Mar 16 20:47:03 2017 +0000
@@ -717,7 +717,9 @@
      */
     public final void endDocument() throws org.xml.sax.SAXException
     {
-        flushCharactersBuffer();
+        if (m_doIndent) {
+            flushCharactersBuffer();
+        }
         flushPending();
         if (m_doIndent && !m_isprevtext)
         {
@@ -776,9 +778,11 @@
         Attributes atts)
         throws SAXException
     {
-        // will add extra one if having namespace but no matter
-        m_childNodeNum++;
-        flushCharactersBuffer();
+        if (m_doIndent) {
+            // will add extra one if having namespace but no matter
+            m_childNodeNum++;
+            flushCharactersBuffer();
+        }
         ElemContext elemContext = m_elemContext;
 
         // clean up any pending things first
@@ -839,8 +843,10 @@
             writer.write('<');
             writer.write(name);
 
-            m_childNodeNumStack.push(m_childNodeNum);
-            m_childNodeNum = 0;
+            if (m_doIndent) {
+                m_childNodeNumStack.add(m_childNodeNum);
+                m_childNodeNum = 0;
+            }
 
             if (m_tracer != null)
                 firePseudoAttributes();
@@ -915,7 +921,9 @@
         final String name)
         throws org.xml.sax.SAXException
     {
-        flushCharactersBuffer();
+        if (m_doIndent) {
+            flushCharactersBuffer();
+        }
         // deal with any pending issues
         if (m_cdataTagOpen)
             closeCDATA();
@@ -997,12 +1005,11 @@
                 }
             }
 
-            m_childNodeNum = m_childNodeNumStack.pop();
-            // clean up because the element has ended
-            if ((elemFlags & ElemDesc.WHITESPACESENSITIVE) != 0)
-                m_ispreserve = true;
-            m_isprevtext = false;
-
+            if (m_doIndent) {
+                m_childNodeNum = m_childNodeNumStack.remove(m_childNodeNumStack.size() - 1);
+                // clean up because the element has ended
+                m_isprevtext = false;
+            }
             // fire off the end element event
             if (m_tracer != null)
                 super.fireEndElem(name);
@@ -1018,11 +1025,6 @@
             }
 
             // some more clean because the element has ended.
-            if (!elemContext.m_startTagOpen)
-            {
-                if (m_doIndent && !m_preserves.isEmpty())
-                    m_preserves.pop();
-            }
             m_elemContext = elemContext.m_prev;
 //            m_isRawStack.pop();
         }
@@ -1525,7 +1527,6 @@
                     closeStartTag();
                     m_elemContext.m_startTagOpen = false;
                 }
-                m_ispreserve = true;
 
 //              With m_ispreserve just set true it looks like shouldIndent()
 //              will always return false, so drop any possible indentation.
@@ -1602,8 +1603,6 @@
                     m_elemContext.m_startTagOpen = false;
                 }
 
-                m_ispreserve = true;
-
                 if (shouldIndent())
                     indent();
 
@@ -1640,8 +1639,10 @@
     public void processingInstruction(String target, String data)
         throws org.xml.sax.SAXException
     {
-        m_childNodeNum++;
-        flushCharactersBuffer();
+        if (m_doIndent) {
+            m_childNodeNum++;
+            flushCharactersBuffer();
+        }
         // Process any pending starDocument and startElement first.
         flushPending();
 
@@ -1790,11 +1791,6 @@
              */
             if (m_StringOfCDATASections != null)
                 m_elemContext.m_isCdataSection = isCdataSection();
-            if (m_doIndent)
-            {
-                m_isprevtext = false;
-                m_preserves.push(m_ispreserve);
-            }
 
             }
             catch(IOException e)
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToStream.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToStream.java	Thu Mar 16 20:47:03 2017 +0000
@@ -20,34 +20,36 @@
 
 package com.sun.org.apache.xml.internal.serializer;
 
-import com.sun.org.apache.xalan.internal.utils.SecuritySupport;
-import com.sun.org.apache.xml.internal.serializer.utils.MsgKey;
-import com.sun.org.apache.xml.internal.serializer.utils.Utils;
-import com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException;
 import java.io.IOException;
 import java.io.OutputStream;
 import java.io.OutputStreamWriter;
 import java.io.UnsupportedEncodingException;
 import java.io.Writer;
-import java.util.ArrayDeque;
 import java.util.ArrayList;
 import java.util.Arrays;
-import java.util.Deque;
 import java.util.EmptyStackException;
 import java.util.Enumeration;
+import java.util.Iterator;
+import java.util.List;
 import java.util.Properties;
-import java.util.Queue;
 import java.util.Set;
 import java.util.StringTokenizer;
+
 import javax.xml.transform.ErrorListener;
 import javax.xml.transform.OutputKeys;
 import javax.xml.transform.Transformer;
 import javax.xml.transform.TransformerException;
+
 import org.w3c.dom.Node;
 import org.xml.sax.Attributes;
 import org.xml.sax.ContentHandler;
 import org.xml.sax.SAXException;
 
+import com.sun.org.apache.xalan.internal.utils.SecuritySupport;
+import com.sun.org.apache.xml.internal.serializer.utils.MsgKey;
+import com.sun.org.apache.xml.internal.serializer.utils.Utils;
+import com.sun.org.apache.xml.internal.serializer.utils.WrappedRuntimeException;
+
 /**
  * This abstract class is a base class for other stream
  * serializers (xml, html, text ...) that write output to a stream.
@@ -103,7 +105,7 @@
      * If m_childNodeNum > 1, the text node will be indented.
      *
      */
-    protected Deque<Integer> m_childNodeNumStack = new ArrayDeque<>();
+    protected List<Integer> m_childNodeNumStack = new ArrayList<>();
 
     protected int m_childNodeNum = 0;
 
@@ -115,26 +117,6 @@
 
     protected boolean m_ispreserveSpace = false;
 
-    /**
-     * Stack to keep track of whether or not we need to
-     * preserve whitespace.
-     *
-     * Used to push/pop values used for the field m_ispreserve, but
-     * m_ispreserve is only relevant if m_doIndent is true.
-     * If m_doIndent is false this field has no impact.
-     *
-     */
-    protected BoolStack m_preserves = new BoolStack();
-
-    /**
-     * State flag to tell if preservation of whitespace
-     * is important.
-     *
-     * Used only in shouldIndent() but only if m_doIndent is true.
-     * If m_doIndent is false this flag has no impact.
-     *
-     */
-    protected boolean m_ispreserve = false;
 
     /**
      * State flag that tells if the previous node processed
@@ -1267,7 +1249,6 @@
                 closeStartTag();
                 m_elemContext.m_startTagOpen = false;
             }
-            m_ispreserve = true;
 
             if (shouldIndent())
                 indent();
@@ -1357,8 +1338,6 @@
                 m_elemContext.m_startTagOpen = false;
             }
 
-            m_ispreserve = true;
-
             m_writer.write(ch, start, length);
         }
         catch (IOException e)
@@ -1405,8 +1384,8 @@
         if (length == 0 || (isInEntityRef()))
             return;
 
-        final boolean shouldFormat = shouldFormatOutput();
-        if (m_elemContext.m_startTagOpen && !shouldFormat)
+        final boolean shouldNotFormat = !shouldFormatOutput();
+        if (m_elemContext.m_startTagOpen)
         {
             closeStartTag();
             m_elemContext.m_startTagOpen = false;
@@ -1432,8 +1411,12 @@
 
         if (m_disableOutputEscapingStates.peekOrFalse() || (!m_escaping))
         {
-            charactersRaw(chars, start, length);
-            m_isprevtext = true;
+            if (shouldNotFormat) {
+                charactersRaw(chars, start, length);
+                m_isprevtext = true;
+            } else {
+                m_charactersBuffer.addRawText(chars, start, length);
+            }
             // time to fire off characters generation event
             if (m_tracer != null)
                 super.fireCharEvent(chars, start, length);
@@ -1441,16 +1424,16 @@
             return;
         }
 
-        if (m_elemContext.m_startTagOpen && !shouldFormat)
+        if (m_elemContext.m_startTagOpen)
         {
             closeStartTag();
             m_elemContext.m_startTagOpen = false;
         }
 
-        if (shouldFormat) {
+        if (shouldNotFormat) {
+            outputCharacters(chars, start, length);
+        } else {
             m_charactersBuffer.addText(chars, start, length);
-        } else {
-            outputCharacters(chars, start, length);
         }
 
         // time to fire off characters generation event
@@ -1465,7 +1448,14 @@
      * @return True if the content should be formatted.
      */
     protected boolean shouldFormatOutput() {
-        return !m_ispreserveSpace && m_doIndent;
+        return m_doIndent && !m_ispreserveSpace;
+    }
+
+    /**
+     * @return True if the content in current element should be formatted.
+     */
+    public boolean getIndent() {
+        return shouldFormatOutput();
     }
 
     /**
@@ -1506,12 +1496,6 @@
                     i = lastDirty;
                 }
             }
-            /* If there is some non-whitespace, mark that we may need
-             * to preserve this. This is only important if we have indentation on.
-             */
-            if (i < end)
-                m_ispreserve = true;
-
 
 //          int lengthClean;    // number of clean characters in a row
 //          final boolean[] isAsciiClean = m_charInfo.getASCIIClean();
@@ -1577,12 +1561,7 @@
      */
     final protected void flushCharactersBuffer() throws SAXException {
         try {
-            if (shouldFormatOutput() && m_charactersBuffer.hasContent()) {
-                if (m_elemContext.m_startTagOpen) {
-                    closeStartTag();
-                    m_elemContext.m_startTagOpen = false;
-                }
-
+            if (shouldFormatOutput() && m_charactersBuffer.isAnyCharactersBuffered()) {
                 if (m_elemContext.m_isCdataSection) {
                     /*
                      * due to cdata-section-elements atribute, we need this as
@@ -1594,11 +1573,16 @@
                 }
 
                 m_childNodeNum++;
+                boolean skipBeginningNewlines = false;
                 if (shouldIndentForText()) {
                     indent();
                     m_startNewLine = true;
+                    // newline has always been added here because if this is the
+                    // text before the first element, shouldIndent() won't
+                    // return true.
+                    skipBeginningNewlines = true;
                 }
-                m_charactersBuffer.flush();
+                m_charactersBuffer.flush(skipBeginningNewlines);
             }
         } catch (IOException e) {
             throw new SAXException(e);
@@ -1858,8 +1842,10 @@
         if (isInEntityRef())
             return;
 
-        m_childNodeNum++;
-        flushCharactersBuffer();
+        if (m_doIndent) {
+            m_childNodeNum++;
+            flushCharactersBuffer();
+        }
 
         if (m_needToCallStartDocument)
         {
@@ -1890,8 +1876,6 @@
             if (namespaceURI != null)
                 ensurePrefixIsDeclared(namespaceURI, name);
 
-            m_ispreserve = false;
-
             if (shouldIndent() && m_startNewLine)
             {
                 indent();
@@ -1912,11 +1896,13 @@
         if (atts != null)
             addAttributes(atts);
 
-        m_ispreserveSpace = m_preserveSpaces.peekOrFalse();
-        m_preserveSpaces.push(m_ispreserveSpace);
-
-        m_childNodeNumStack.push(m_childNodeNum);
-        m_childNodeNum = 0;
+        if (m_doIndent) {
+            m_ispreserveSpace = m_preserveSpaces.peekOrFalse();
+            m_preserveSpaces.push(m_ispreserveSpace);
+
+            m_childNodeNumStack.add(m_childNodeNum);
+            m_childNodeNum = 0;
+        }
 
         m_elemContext = m_elemContext.push(namespaceURI,localName,name);
         m_isprevtext = false;
@@ -2128,7 +2114,9 @@
         if (isInEntityRef())
             return;
 
-        flushCharactersBuffer();
+        if (m_doIndent) {
+            flushCharactersBuffer();
+        }
         // namespaces declared at the current depth are no longer valid
         // so get rid of them
         m_prefixMap.popNamespaces(m_elemContext.m_currentElemDepth, null);
@@ -2175,16 +2163,13 @@
             throw new SAXException(e);
         }
 
-        if (!m_elemContext.m_startTagOpen && m_doIndent)
-        {
-            m_ispreserve = m_preserves.isEmpty() ? false : m_preserves.pop();
+        if (m_doIndent) {
+            m_ispreserveSpace = m_preserveSpaces.popAndTop();
+            m_childNodeNum = m_childNodeNumStack.remove(m_childNodeNumStack.size() - 1);
+
+            m_isprevtext = false;
         }
 
-        m_ispreserveSpace = m_preserveSpaces.popAndTop();
-        m_childNodeNum = m_childNodeNumStack.pop();
-
-        m_isprevtext = false;
-
         // fire off the end element event
         if (m_tracer != null)
             super.fireEndElem(name);
@@ -2320,8 +2305,10 @@
         int start_old = start;
         if (isInEntityRef())
             return;
-        m_childNodeNum++;
-        flushCharactersBuffer();
+        if (m_doIndent) {
+            m_childNodeNum++;
+            flushCharactersBuffer();
+        }
         if (m_elemContext.m_startTagOpen)
         {
             closeStartTag();
@@ -2501,8 +2488,10 @@
      */
     public void startCDATA() throws org.xml.sax.SAXException
     {
-        m_childNodeNum++;
-        flushCharactersBuffer();
+        if (m_doIndent) {
+            m_childNodeNum++;
+            flushCharactersBuffer();
+        }
 
         m_cdataStartCalled = true;
     }
@@ -2588,12 +2577,6 @@
              */
             if (m_StringOfCDATASections != null)
                 m_elemContext.m_isCdataSection = isCdataSection();
-
-            if (m_doIndent)
-            {
-                m_isprevtext = false;
-                m_preserves.push(m_ispreserve);
-            }
         }
 
     }
@@ -2943,7 +2926,9 @@
         String value,
         boolean xslAttribute)
     {
-        if (m_charactersBuffer.isAnyCharactersBuffered()) {
+        if (!m_charactersBuffer.isAnyCharactersBuffered()) {
+            return doAddAttributeAlways(uri, localName, rawName, type, value, xslAttribute);
+        } else {
             /*
              * If stylesheet includes xsl:copy-of an attribute node, XSLTC will
              * fire an addAttribute event. When a text node is handling in
@@ -2954,8 +2939,6 @@
              *
              */
             return m_attributes.getIndex(rawName) < 0;
-        } else {
-            return doAddAttributeAlways(uri, localName, rawName, type, value, xslAttribute);
         }
     }
 
@@ -3086,7 +3069,7 @@
             }
         }
 
-        if (rawName.equals("xml:space")) {
+        if (m_doIndent && rawName.equals("xml:space")) {
             if (value.equals("preserve")) {
                 m_ispreserveSpace = true;
                 if (m_preserveSpaces.size() > 0)
@@ -3227,8 +3210,6 @@
          // Leave m_format alone for now - Brian M.
          // this.m_format = null;
          this.m_inDoctype = false;
-         this.m_ispreserve = false;
-         this.m_preserves.clear();
          this.m_ispreserveSpace = false;
          this.m_preserveSpaces.clear();
          this.m_childNodeNum = 0;
@@ -3411,6 +3392,7 @@
         }
     }
 
+
     /**
      * This inner class is used to buffer the text nodes and the entity
      * reference nodes if indentation is on. There is only one CharacterBuffer
@@ -3425,20 +3407,21 @@
          */
         private abstract class GenericCharacters {
             /**
-             * @return True if having any character other than whitespace or
-             *         line feed.
+             * @return True if all characters in this Text are newlines.
              */
-            abstract boolean hasContent();
-
-            abstract void flush() throws SAXException;
+            abstract boolean flush(boolean skipBeginningNewlines) throws SAXException;
 
             /**
-             * Converts this GenericCharacters to a new character array.
+             * Converts this GenericCharacters to a new character array. This
+             * method is used to handle cdata-section-elements attribute in
+             * xsl:output. Therefore it doesn't need to consider
+             * skipBeginningNewlines because the text will be involved with CDATA
+             * tag.
              */
             abstract char[] toChars();
         }
 
-        private Queue<GenericCharacters> bufferedCharacters = new ArrayDeque<>();
+        private List<GenericCharacters> bufferedCharacters = new ArrayList<>();
 
         /**
          * Append a text node to the buffer.
@@ -3451,27 +3434,21 @@
                     text = Arrays.copyOfRange(chars, start, start + length);
                 }
 
-                boolean hasContent() {
-                    for (int i = 0; i < text.length; i++) {
-                        if (!isWhiteSpace(text[i])) {
+                boolean flush(boolean skipBeginningNewlines) throws SAXException {
+                    int start = 0;
+                    while (skipBeginningNewlines && text[start] == '\n') {
+                        start++;
+                        if (start == text.length) {
                             return true;
                         }
                     }
+                    outputCharacters(text, start, text.length - start);
                     return false;
                 }
 
-                void flush() throws SAXException {
-                    outputCharacters(text, 0, text.length);
-                }
-
                 char[] toChars() {
                     return text;
                 }
-
-                boolean isWhiteSpace(char ch) {
-                    return ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r';
-                }
-
             });
         }
 
@@ -3480,12 +3457,22 @@
          */
         public void addEntityReference(String entityName) {
             bufferedCharacters.add(new GenericCharacters() {
-                boolean hasContent() {
-                    return true;
-                }
-
-                void flush() throws SAXException {
-                    outputEntityReference(entityName);
+                boolean flush(boolean skipBeginningNewlines) throws SAXException {
+                    if (m_elemContext.m_startTagOpen)
+                    {
+                        closeStartTag();
+                        m_elemContext.m_startTagOpen = false;
+                    }
+                    if (m_cdataTagOpen)
+                        closeCDATA();
+                    char[] cs = toChars();
+                    try {
+                        m_writer.write(cs, 0, cs.length);
+                        m_isprevtext = true;
+                    } catch (IOException e) {
+                        throw new SAXException(e);
+                    }
+                    return false;
                 }
 
                 char[] toChars() {
@@ -3495,35 +3482,69 @@
         }
 
         /**
-         * @return True if any GenericCharacters is already buffered.
+         * Append a raw text to the buffer. Used to handle raw characters event.
          */
-        public boolean isAnyCharactersBuffered() {
-            return !bufferedCharacters.isEmpty();
+        public void addRawText(final char chars[], final int start, final int length) {
+            bufferedCharacters.add(new GenericCharacters() {
+                char[] text;
+
+                {
+                    text = Arrays.copyOfRange(chars, start, start + length);
+                }
+
+                boolean flush(boolean skipBeginningNewlines) throws SAXException {
+                    try {
+                        int start = 0;
+                        while (skipBeginningNewlines && text[start] == '\n') {
+                            start++;
+                            if (start == text.length) {
+                                return true;
+                            }
+                        }
+                        m_writer.write(text, start, text.length - start);
+                        m_isprevtext = true;
+                    } catch (IOException e) {
+                        throw new SAXException(e);
+                    }
+                    return false;
+                }
+
+                char[] toChars() {
+                    return text;
+                }
+            });
         }
 
         /**
-         * @return True if any buffered GenericCharacters has content.
+         * @return True if any GenericCharacters are buffered.
          */
-        public boolean hasContent() {
-            return bufferedCharacters.stream().anyMatch(GenericCharacters::hasContent);
+        public boolean isAnyCharactersBuffered() {
+            return bufferedCharacters.size() > 0;
         }
 
         /**
          * Flush all buffered GenericCharacters.
          */
-        public void flush() throws SAXException {
-            GenericCharacters element;
-            while ((element = bufferedCharacters.poll()) != null)
-                element.flush();
+        public void flush(boolean skipBeginningNewlines) throws SAXException {
+            Iterator<GenericCharacters> itr = bufferedCharacters.iterator();
+
+            boolean continueSkipBeginningNewlines = skipBeginningNewlines;
+            while (itr.hasNext()) {
+                GenericCharacters element = itr.next();
+                continueSkipBeginningNewlines = element.flush(continueSkipBeginningNewlines);
+                itr.remove();
+            }
         }
 
         /**
          * Converts all buffered GenericCharacters to a new character array.
          */
         public char[] toChars() {
-            return bufferedCharacters.stream().map(GenericCharacters::toChars)
-                    .collect(StringBuilder::new, StringBuilder::append, StringBuilder::append).toString()
-                    .toCharArray();
+            StringBuilder sb = new StringBuilder();
+            for (GenericCharacters element : bufferedCharacters) {
+                sb.append(element.toChars());
+            }
+            return sb.toString().toCharArray();
         }
 
         /**
@@ -3534,6 +3555,7 @@
         }
     }
 
+
     // Implement DTDHandler
     /**
      * If this method is called, the serializer is used as a
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToXMLStream.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/ToXMLStream.java	Thu Mar 16 20:47:03 2017 +0000
@@ -88,8 +88,6 @@
 
         setOmitXMLDeclaration(xmlListener.getOmitXMLDeclaration());
 
-        m_ispreserve = xmlListener.m_ispreserve;
-        m_preserves = xmlListener.m_preserves;
         m_ispreserveSpace = xmlListener.m_ispreserveSpace;
         m_preserveSpaces = xmlListener.m_preserveSpaces;
         m_childNodeNum = xmlListener.m_childNodeNum;
@@ -201,7 +199,9 @@
      */
     public void endDocument() throws org.xml.sax.SAXException
     {
-        flushCharactersBuffer();
+        if (m_doIndent) {
+            flushCharactersBuffer();
+        }
         flushPending();
         if (m_doIndent && !m_isprevtext)
         {
@@ -235,11 +235,6 @@
      */
     public void startPreserving() throws org.xml.sax.SAXException
     {
-
-        // Not sure this is really what we want.  -sb
-        m_preserves.push(true);
-
-        m_ispreserve = true;
     }
 
     /**
@@ -251,9 +246,6 @@
      */
     public void endPreserving() throws org.xml.sax.SAXException
     {
-
-        // Not sure this is really what we want.  -sb
-        m_ispreserve = m_preserves.isEmpty() ? false : m_preserves.pop();
     }
 
     /**
@@ -273,8 +265,10 @@
         if (isInEntityRef())
             return;
 
-        m_childNodeNum++;
-        flushCharactersBuffer();
+        if (m_doIndent) {
+            m_childNodeNum++;
+            flushCharactersBuffer();
+        }
         flushPending();
 
         if (target.equals(Result.PI_DISABLE_OUTPUT_ESCAPING))
--- a/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/dom3/DOM3TreeWalker.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/src/java.xml/share/classes/com/sun/org/apache/xml/internal/serializer/dom3/DOM3TreeWalker.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1024,7 +1024,8 @@
                 return;
             }
 
-            if (bDispatch) {
+            if (bDispatch
+                    && (!fSerializer.getIndent() || !node.getData().replace('\n', ' ').trim().isEmpty())) {
                 dispatachChars(node);
             }
         }
--- a/jaxp/src/java.xml/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/src/java.xml/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -26,6 +26,8 @@
 /**
  * Defines the Java API for XML Processing (JAXP), the Streaming API for XML (StAX),
  * the Simple API for XML (SAX), and the W3C Document Object Model (DOM) API.
+ *
+ * @since 9
  */
 module java.xml {
     exports javax.xml;
@@ -53,12 +55,6 @@
     exports org.xml.sax;
     exports org.xml.sax.ext;
     exports org.xml.sax.helpers;
-    exports com.sun.org.apache.xerces.internal.dom to
-        java.xml.ws;
-    exports com.sun.org.apache.xerces.internal.jaxp to
-        java.xml.ws;
-    exports com.sun.org.apache.xerces.internal.util to
-        java.xml.ws;
     exports com.sun.org.apache.xml.internal.dtm to
         java.xml.crypto;
     exports com.sun.org.apache.xml.internal.utils to
--- a/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NodeTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/functional/org/w3c/dom/ptests/NodeTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -22,6 +22,7 @@
  */
 package org.w3c.dom.ptests;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
 import static jaxp.library.JAXPTestUtilities.compareWithGold;
 import static jaxp.library.JAXPTestUtilities.tryRunWithTmpPermission;
 import static org.testng.Assert.assertEquals;
@@ -157,7 +158,7 @@
         Element element = (Element) document.getElementsByTagName("sender").item(0);
         parentElement.insertBefore(createTestDocumentFragment(document), element);
 
-        String outputfile = "InsertBefore.out";
+        String outputfile = USER_DIR + "InsertBefore.out";
         String goldfile = GOLDEN_DIR + "InsertBeforeGF.out";
         tryRunWithTmpPermission(() -> outputXml(document, outputfile), new PropertyPermission("user.dir", "read"));
         assertTrue(compareWithGold(goldfile, outputfile));
@@ -175,7 +176,7 @@
         Element element = (Element) document.getElementsByTagName("sender").item(0);
         parentElement.replaceChild(createTestDocumentFragment(document), element);
 
-        String outputfile = "ReplaceChild3.out";
+        String outputfile = USER_DIR + "ReplaceChild3.out";
         String goldfile = GOLDEN_DIR + "ReplaceChild3GF.out";
         tryRunWithTmpPermission(() -> outputXml(document, outputfile), new PropertyPermission("user.dir", "read"));
         assertTrue(compareWithGold(goldfile, outputfile));
--- a/jaxp/test/javax/xml/jaxp/functional/test/astro/DocumentLSTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/functional/test/astro/DocumentLSTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -22,6 +22,7 @@
  */
 package test.astro;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
 import static jaxp.library.JAXPTestUtilities.filenameToURL;
 import static org.testng.Assert.assertEquals;
 import static org.testng.Assert.assertNotNull;
@@ -130,7 +131,7 @@
         impl = (DOMImplementationLS) db.getDOMImplementation();
         LSSerializer domSerializer = impl.createLSSerializer();
         MyDOMOutput mydomoutput = new MyDOMOutput();
-        try (OutputStream os = new FileOutputStream("test.out")) {
+        try (OutputStream os = new FileOutputStream(USER_DIR + "test.out")) {
             mydomoutput.setByteStream(os);
             mydomoutput.setEncoding("UTF-8");
             assertTrue(domSerializer.write(doc, mydomoutput));
--- a/jaxp/test/javax/xml/jaxp/module/ServiceProviderTest/LayerModularXMLParserTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/module/ServiceProviderTest/LayerModularXMLParserTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -96,7 +96,7 @@
     public void testOneLayer() throws Exception {
         ModuleFinder finder1 = ModuleFinder.of(MOD_DIR1);
         Configuration cf1 = Layer.boot().configuration()
-                .resolveRequiresAndUses(finder1, ModuleFinder.of(), Set.of("test"));
+                .resolveAndBind(finder1, ModuleFinder.of(), Set.of("test"));
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer1 = Layer.boot().defineModulesWithManyLoaders(cf1, scl);
         ClassLoader cl1 = layer1.findLoader("test");
@@ -126,12 +126,12 @@
     public void testTwoLayer() throws Exception {
         ModuleFinder finder1 = ModuleFinder.of(MOD_DIR1);
         Configuration cf1 = Layer.boot().configuration()
-                .resolveRequiresAndUses(finder1, ModuleFinder.of(), Set.of("test"));
+                .resolveAndBind(finder1, ModuleFinder.of(), Set.of("test"));
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer1 = Layer.boot().defineModulesWithManyLoaders(cf1, scl);
 
         ModuleFinder finder2 = ModuleFinder.of(MOD_DIR2);
-        Configuration cf2 = cf1.resolveRequiresAndUses(finder2, ModuleFinder.of(), Set.of("test"));
+        Configuration cf2 = cf1.resolveAndBind(finder2, ModuleFinder.of(), Set.of("test"));
         Layer layer2 = layer1.defineModulesWithOneLoader(cf2, layer1.findLoader("test"));
         ClassLoader cl2 = layer2.findLoader("test");
 
@@ -160,12 +160,12 @@
     public void testTwoLayerWithDuplicate() throws Exception {
         ModuleFinder finder1 = ModuleFinder.of(MOD_DIR1, MOD_DIR2);
         Configuration cf1 = Layer.boot().configuration()
-                .resolveRequiresAndUses(finder1, ModuleFinder.of(), Set.of("test"));
+                .resolveAndBind(finder1, ModuleFinder.of(), Set.of("test"));
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer1 = Layer.boot().defineModulesWithManyLoaders(cf1, scl);
 
         ModuleFinder finder2 = ModuleFinder.of(MOD_DIR2);
-        Configuration cf2 = cf1.resolveRequiresAndUses(finder2, ModuleFinder.of(), Set.of("test"));
+        Configuration cf2 = cf1.resolveAndBind(finder2, ModuleFinder.of(), Set.of("test"));
         Layer layer2 = layer1.defineModulesWithOneLoader(cf2, layer1.findLoader("test"));
         ClassLoader cl2 = layer2.findLoader("test");
 
--- a/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/PrettyPrintTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/PrettyPrintTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -60,7 +60,7 @@
 
 /*
  * @test
- * @bug 6439439 8087303
+ * @bug 6439439 8087303 8174025
  * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
  * @run testng/othervm -DrunSecMngr=true common.prettyprint.PrettyPrintTest
  * @run testng/othervm common.prettyprint.PrettyPrintTest
@@ -69,29 +69,30 @@
 @Listeners({jaxp.library.FilePolicy.class})
 public class PrettyPrintTest {
     /*
-     * test CDATA, elements only, text and element, whitespace and element,
-     * xml:space property and nested xml:space property, mixed node types.
+     * test CDATA, elements only, text and element, xml:space property, mixed
+     * node types.
      */
     @DataProvider(name = "xml-data")
     public Object[][] xmlData() throws Exception {
         return new Object[][] {
-                { read("xmltest1.xml"), read("xmltest1.out") },
-                { read("xmltest2.xml"), read("xmltest2.out") },
-                { read("xmltest3.xml"), read("xmltest3.out") },
-                { read("xmltest4.xml"), read("xmltest4.out") },
-                { read("xmltest5.xml"), read("xmltest5.out") },
-                { read("xmltest6.xml"), read("xmltest6.out") },
-                { read("xmltest7.xml"), read("xmltest7.out") },
-                { read("xmltest8.xml"), read("xmltest8.out") } };
+                { "xmltest1.xml", "xmltest1.out" },
+                { "xmltest2.xml", "xmltest2.out" },
+                { "xmltest3.xml", "xmltest3.out" },
+                { "xmltest4.xml", "xmltest4.out" },
+                { "xmltest6.xml", "xmltest6.out" },
+                { "xmltest8.xml", "xmltest8.out" } };
     }
 
     /*
      * @bug 8087303
-     * Test the whitespace text nodes are serialized with pretty-print by LSSerializer and transformer correctly
+     * Test the xml document are serialized with pretty-print by
+     * LSSerializer and transformer correctly
      *
      */
     @Test(dataProvider = "xml-data")
-    public void testXMLPrettyPrint(String source, String expected) throws Exception {
+    public void testXMLPrettyPrint(String sourceFile, String expectedFile) throws Exception {
+        String source = read(sourceFile);
+        String expected = read(expectedFile);
         // test it's no change if no pretty-print
         String result = serializerWrite(toXmlDocument(source), false);
         assertTrue(toXmlDocument(source).isEqualNode(toXmlDocument(result)), "The actual is: " + result);
@@ -104,26 +105,100 @@
         assertEquals(transform(toXmlDocument(source), true).replaceAll("\r\n", "\n"), expected);
     }
 
+
     /*
-     * test pure text content, and sequent Text nodes.
+     * @bug 8087303
+     * Test a single text node is serialized with pretty-print by
+     * LSSerializer and transformer correctly
+     *
      */
-    @DataProvider(name = "xml-node-data")
-    public Object[][] xmlNodeData() throws Exception {
-        return new Object[][] {
-                { newTextNode(read("nodetest1.txt")), read("nodetest1.out") },
-                { createDocWithSequentTextNodes(), read("nodetest2.out") } };
+    @Test
+    public void testSingleTextNode() throws Exception {
+        Node xml = newTextNode(read("nodetest1.txt"));
+        String expected = read("nodetest1.out");
+        assertEquals(serializerWrite(xml, true), expected);
+        assertEquals(transform(xml, true).replaceAll("\r\n", "\n"), expected);
+    }
+
+    /*
+     * @bug 8087303
+     * Test the transformer shall keep all whitespace text node in
+     * sequent text nodes
+     *
+     */
+    @Test
+    public void testSequentTextNodesWithTransformer() throws Exception {
+        Node xml = createDocWithSequentTextNodes();
+        String expected = read("nodetest2.out");
+        assertEquals(transform(xml, true).replaceAll("\r\n", "\n"), expected);
     }
 
     /*
      * @bug 8087303
-     * Test the whitespace text nodes are serialized with pretty-print by LSSerializer and transformer correctly,
-     * doesn't compare with the source because the test data is Node object
+     * Test LSSerializer shall eliminate the whitespace text node
+     * in sequent text nodes
+     *
+     */
+    @Test
+    public void testSequentTextNodesWithLSSerializer() throws Exception {
+        Node xml = createDocWithSequentTextNodes();
+        String expected = read("nodetest2ls.out");
+        assertEquals(serializerWrite(xml, true), expected);
+    }
+
+
+    /*
+     * test whitespace and element, nested xml:space property.
+     */
+    @DataProvider(name = "xml-data-whitespace-ls")
+    public Object[][] whitespaceLS() throws Exception {
+        return new Object[][] {
+                { "xmltest5.xml", "xmltest5ls.out" },
+                { "xmltest7.xml", "xmltest7ls.out" } };
+    }
+
+    /*
+     * @bug 8087303
+     * Test LSSerializer shall eliminate the whitespace text node
+     * unless xml:space="preserve"
      *
      */
-    @Test(dataProvider = "xml-node-data")
-    public void testXMLNodePrettyPrint(Node xml, String expected) throws Exception {
-        assertEquals(serializerWrite(xml, true), expected);
-        assertEquals(transform(xml, true).replaceAll("\r\n", "\n"), expected);
+    @Test(dataProvider = "xml-data-whitespace-ls")
+    public void testWhitespaceWithLSSerializer(String sourceFile, String expectedFile) throws Exception {
+        String source = read(sourceFile);
+        String expected = read(expectedFile);
+        // test it's no change if no pretty-print
+        String result = serializerWrite(toXmlDocument(source), false);
+        assertTrue(toXmlDocument(source).isEqualNode(toXmlDocument(result)), "The actual is: " + result);
+        // test pretty-print
+        assertEquals(serializerWrite(toXmlDocument(source), true), expected);
+    }
+
+    /*
+     * test whitespace and element, nested xml:space property.
+     */
+    @DataProvider(name = "xml-data-whitespace-xslt")
+    public Object[][] whitespaceXSLT() throws Exception {
+        return new Object[][] {
+                { "xmltest5.xml", "xmltest5xslt.out" },
+                { "xmltest7.xml", "xmltest7xslt.out" } };
+    }
+
+    /*
+     * @bug 8087303
+     * Test the transformer shall format the output but keep all
+     * whitespace text node even if xml:space="preserve"
+     *
+     */
+    @Test(dataProvider = "xml-data-whitespace-xslt")
+    public void testWhitespaceWithTransformer(String sourceFile, String expectedFile) throws Exception {
+        String source = read(sourceFile);
+        String expected = read(expectedFile);
+        // test it's no change if no pretty-print
+        String result = transform(toXmlDocument(source), false);
+        assertTrue(toXmlDocument(source).isEqualNode(toXmlDocument(result)), "The actual is: " + result);
+        // test pretty-print
+        assertEquals(transform(toXmlDocument(source), true).replaceAll("\r\n", "\n"), expected);
     }
 
     /*
@@ -132,12 +207,14 @@
     @DataProvider(name = "html-data")
     public Object[][] htmlData() throws Exception {
         return new Object[][] {
-            { read("htmltest1.xml"), read("htmltest1.out") },
-            { read("htmltest2.xml"), read("htmltest2.out") },
-            { read("htmltest3.xml"), read("htmltest3.out") },
-            { read("htmltest4.xml"), read("htmltest4.out") },
-            { read("htmltest5.xml"), read("htmltest5.out") },
-            { read("htmltest6.xml"), read("htmltest6.out") } };
+            { "htmltest1.xml", "htmltest1.out" },
+            { "htmltest2.xml", "htmltest2.out" },
+            { "htmltest3.xml", "htmltest3.out" },
+            { "htmltest4.xml", "htmltest4.out" },
+            { "htmltest5.xml", "htmltest5.out" },
+            { "htmltest6.xml", "htmltest6.out" },
+            /* @bug 8174025, test whitespace between inline elements */
+            { "htmltest7.xml", "htmltest7.out" } };
     }
 
     /*
@@ -146,7 +223,9 @@
      *
      */
     @Test(dataProvider = "html-data")
-    public void testTransformToHTML(String source, String expected) throws Exception {
+    public void testTransformToHTML(String sourceFile, String expectedFile) throws Exception {
+        String source = read(sourceFile);
+        String expected = read(expectedFile);
         // test it's no change if no pretty-print
         StringWriter writer = new StringWriter();
         getTransformer(true, false).transform(new StreamSource(new StringReader(source)), new StreamResult(writer));
@@ -158,6 +237,27 @@
         assertEquals(writer.toString().replaceAll("\r\n", "\n"), expected);
     }
 
+    /*
+     * @bug 8174025
+     * Test the serializer can handle <xsl:text disable-output-escaping="yes"> correctly.
+     *
+     */
+    @Test
+    public void testDisableOutputEscaping() throws Exception {
+        final String xsl ="generate-catalog.xsl";
+        final String xml ="simple-entity-resolver-config.xml";
+        final String expectedOutput ="simple-entity-resolver-config-transformed.xml";
+        TransformerFactory factory = TransformerFactory.newInstance();
+        Transformer transformer = factory.newTemplates(new StreamSource(new StringReader(read(xsl)))).newTransformer();
+
+        String key = "schemaBase";
+        String value = "schemas";
+        transformer.setParameter(key, value);
+        StringWriter writer = new StringWriter();
+        transformer.transform(new StreamSource(new StringReader(read(xml))), new StreamResult(writer));
+        assertEquals(writer.toString().replaceAll("\r\n", "\n"), read(expectedOutput));
+    }
+
     @Test
     public void testLSSerializerFormatPrettyPrint() {
 
@@ -298,6 +398,9 @@
         Document doc = db.newDocument();
         Node root = doc.createElement("root");
         doc.appendChild(root);
+        root.appendChild(doc.createTextNode("\n"));
+        root.appendChild(doc.createTextNode("\n"));
+        root.appendChild(doc.createTextNode("\n"));
         root.appendChild(doc.createTextNode(" "));
         root.appendChild(doc.createTextNode("t"));
         root.appendChild(doc.createTextNode("\n"));
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/generate-catalog.xsl	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="utf-8" ?> 
+ <!-- Stylesheet for generating the entity-resolver document in XCatalog format --> 
+ <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> 
+
+       <xsl:output method="xml" indent="yes"/> 
+       <xsl:param name="schemaBase"/> 
+       <xsl:template match="entity-resolver-config"> 
+          <catalog xmlns="xmlns:xml:catalog" 
+                   prefer="system" 
+                   xml:base="{$schemaBase}" > 
+                    
+                   <xsl:for-each select="entity"> 
+                    
+                          <!-- Generate System Id --> 
+                          <xsl:text disable-output-escaping="yes">&lt;system systemId="</xsl:text> 
+                          <xsl:value-of select="system-id/text()"/> 
+                          <xsl:text>" uri="</xsl:text> 
+                          <xsl:value-of select="location/text()"/> 
+                          <xsl:text disable-output-escaping="yes">" /&gt;&#10;</xsl:text> 
+                   </xsl:for-each> 
+             </catalog> 
+    </xsl:template> 
+ </xsl:stylesheet>
\ No newline at end of file
--- a/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/htmltest1.xml	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/htmltest1.xml	Thu Mar 16 20:47:03 2017 +0000
@@ -1,1 +1,1 @@
-<rss version="2.0"><channel xml:space="preserve"><title>Java Tutorials and Examples 1</title> <language>en-us</language></channel></rss>
\ No newline at end of file
+<rss version="2.0"><channel xml:space="preserve"><title>Java Tutorials and Examples 1</title><language>en-us</language></channel></rss>
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/htmltest7.out	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,7 @@
+<html>
+    <body>
+        <p>
+             <span>this</span> <span>is</span> <span>a</span>  <span>whitespace</span>  <span>inline element</span>  <span>test</span>  
+        </p>
+    </body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/htmltest7.xml	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,1 @@
+<html><body><p> <span>this</span> <span>is</span> <span>a</span>  <span>whitespace</span>  <span>inline element</span>  <span>test</span>  </p></body></html>
\ No newline at end of file
--- a/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/nodetest2.out	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/nodetest2.out	Thu Mar 16 20:47:03 2017 +0000
@@ -1,19 +1,30 @@
 <root>
      t
 t   
-    <child1/>
+    <child1> 
+</child1>
     t
-    <child2/>
-    <child3/>
-    <child4/>
+    <child2> </child2>
+     
+    <child3> </child3>
+     
+    <child4> </child4>
+     
     <child5>
         t
         <child51>
+             
             <child511>t</child511>
+             
         </child51>
         t
     </child5>
+     
     <!-- test comment -->
+     
+
     <!-- -->
+    
     <?target1 test?>
+      
 </root>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/nodetest2ls.out	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,18 @@
+<root>
+    tt
+    <child1/>
+    t
+    <child2/>
+    <child3/>
+    <child4/>
+    <child5>
+        t
+        <child51>
+            <child511>t</child511>
+        </child51>
+        t
+    </child5>
+    <!-- test comment -->
+    <!-- -->
+    <?target1 test?>
+</root>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/simple-entity-resolver-config-transformed.xml	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,3 @@
+<?xml version="1.0" encoding="UTF-8"?><catalog prefer="system" xml:base="schemas" xmlns="xmlns:xml:catalog"><system systemId="http://www.example.test/oracle/schema/example1.xsd" uri="META-INF/example1.xsd" />
+<system systemId="http://www.example.test/oracle/schema/example2.xsd" uri="META-INF/example2.xsd" />
+</catalog>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/simple-entity-resolver-config.xml	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,20 @@
+<?xml version="1.0"?> 
+ <entity-resolver-config 
+     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
+     xsi:noNamespaceSchemaLocation="http://www.example.test/schema.xsd" 
+     schema-major-version="1" 
+     schema-minor-version="1"> 
+
+     <entity> 
+         <description>Example 1 Schema Type library 10.0 </description> 
+         <public-id>>-//Oracle//Example 1 Schema Type library 10.0//EN</public-id> 
+         <system-id>http://www.example.test/oracle/schema/example1.xsd</system-id> 
+         <location>META-INF/example1.xsd</location> 
+     </entity> 
+     <entity> 
+         <description>Example 2 Schema Type library 10.0 </description> 
+         <public-id>>-//Oracle//Example 2 Schema Type library 10.0//EN</public-id> 
+         <system-id>http://www.example.test/oracle/schema/example2.xsd</system-id> 
+         <location>META-INF/example2.xsd</location> 
+     </entity> 
+ </entity-resolver-config>
\ No newline at end of file
--- a/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/xmltest5.out	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-<rss version="2.0">
-    <channel>
-        <title>Java Tutorials and Examples 1</title>
-        <language>en-us</language>
-    </channel>
-    <a>
-        <b/>
-    </a>
-    <c/>
-</rss>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/xmltest5ls.out	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,10 @@
+<rss version="2.0">
+    <channel>
+        <title>Java Tutorials and Examples 1</title>
+        <language>en-us</language>
+    </channel>
+    <a>
+        <b/>
+    </a>
+    <c/>
+</rss>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/xmltest5xslt.out	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,15 @@
+<rss version="2.0">
+    <channel>
+         
+        <title>Java Tutorials and Examples 1</title>
+         
+        <language>en-us</language>
+    </channel>
+    <a>
+        <b> </b>
+    </a>
+     
+    <c>
+ 
+</c>
+</rss>
--- a/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/xmltest7.out	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-<rss>
-    <layer1 xml:space="preserve"> <title>Java </title> <layer2 xml:space="asfsa"> <layer3> <layer4 xml:space="default">
-                    <l5>5</l5>
-                </layer4> </layer3> </layer2> <layer2 xml:space="default">
-            <layer3>
-                <l4/>
-            </layer3>
-            <layer3 xml:space="preserve"> <l4> </l4> </layer3>
-        </layer2> </layer1>
-</rss>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/xmltest7ls.out	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,10 @@
+<rss>
+    <layer1 xml:space="preserve"> <title>Java </title> <layer2 xml:space="asfsa"> <layer3> <layer4 xml:space="default">
+                    <l5>5</l5>
+                </layer4> </layer3> </layer2> <layer2 xml:space="default">
+            <layer3>
+                <l4/>
+            </layer3>
+            <layer3 xml:space="preserve"> <l4> </l4> </layer3>
+        </layer2> </layer1>
+</rss>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/xmltest7xslt.out	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,17 @@
+<rss>
+    <layer1 xml:space="preserve"> <title>Java </title> <layer2 xml:space="asfsa"> <layer3> <layer4 xml:space="default">
+                     
+                    <l5>5</l5>
+                     
+ 
+                </layer4> </layer3> </layer2> <layer2 xml:space="default">
+             
+            <layer3>
+                 
+                <l4> </l4>
+                 
+            </layer3>
+             
+            <layer3 xml:space="preserve"> <l4> </l4> </layer3>
+        </layer2> </layer1>
+</rss>
--- a/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/xmltest8.out	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/xmltest8.out	Thu Mar 16 20:47:03 2017 +0000
@@ -1,25 +1,20 @@
 <root>
-    
-     t
+         t
     <![CDATA[ ]]>
-    
-t   
+    t   
     
     <child1/>
-    
-    t
+        t
     <!-- test comment -->
     <child2/>
     <child5>
-        
-        t
+                t
         <?target1 test?>
         <child51>
             <child511>t</child511>
         </child51>
         <?target1 test?>
-        
-        t
+                t
     
     </child5>
 </root>
--- a/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/xmltest8.xml	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/common/prettyprint/xmltest8.xml	Thu Mar 16 20:47:03 2017 +0000
@@ -2,14 +2,7 @@
      t<![CDATA[ ]]>
 t   
     <child1/>
-    t<!-- test comment -->
-    <child2/>
-    <child5>
-        t<?target1 test?>
-        <child51>
-            <child511>t</child511>
-        </child51><?target1 test?>
+    t<!-- test comment --><child2/><child5>
+        t<?target1 test?><child51><child511>t</child511></child51><?target1 test?>
         t
-    </child5>
-    
-</root> 
+    </child5></root> 
--- a/jaxp/test/javax/xml/jaxp/unittest/dom/ls/LSSerializerTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/dom/ls/LSSerializerTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -279,11 +279,11 @@
                 "<author>\n" +
                 "    <a>&name1;Jo Smith</a>\n" +
                 "    <b>b &name2;Jo Smith &name1;Jo Smith b</b>\n" +
-                "    <c> &name;Jo Smith </c>\n" +
+                "    <c>&name;Jo Smith </c>\n" +
                 "    <d>&ele1;d</d>\n" +
-                "    <e> &ele2;eee </e>\n" +
+                "    <e>&ele2;eee </e>\n" +
                 "    <f>&lt;att&gt;</f>\n" +
-                "    <g> &ele; g</g>\n" +
+                "    <g>&ele; g</g>\n" +
                 "    <h>&ele2;</h>\n" +
                 "</author>\n");
 
@@ -301,7 +301,7 @@
                 "<author>\n" +
                 "    <a>&name;Jo Smith</a>\n" +
                 "    <b>b &name;Jo Smith &name;Jo Smith b</b>\n" +
-                "    <c> &name;Jo Smith </c>\n" +
+                "    <c>&name;Jo Smith </c>\n" +
                 "    <d>\n" +
                 "        <aa>\n" +
                 "            <bb>text</bb>\n" +
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/parsers/BaseParsingTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,158 @@
+/*
+ * Copyright (c) 2017, 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 parsers;
+
+import java.io.StringReader;
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.stream.XMLInputFactory;
+import javax.xml.stream.XMLStreamReader;
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Listeners;
+import org.testng.annotations.Test;
+import org.xml.sax.InputSource;
+
+/**
+ * @test
+ * @bug 8169450
+ * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
+ * @run testng/othervm -DrunSecMngr=true parsers.BaseParsingTest
+ * @run testng/othervm parsers.BaseParsingTest
+ * @summary Tests that verify base parsing
+ */
+@Listeners({jaxp.library.BasePolicy.class})
+public class BaseParsingTest {
+
+    @DataProvider(name = "xmlDeclarations")
+    public static Object[][] xmlDeclarations() {
+        return new Object[][]{
+            {"<?xml version=\"1.0\"?><root><test>t</test></root>"},
+            {"<?xml version=\"1.0\" encoding=\"UTF-8\"?><root><test>t</test></root>"},
+            {"<?xml version=\"1.0\" encoding=\"UTF-8\" standalone='yes'?><root><test>t</test></root>"},
+            {"<?xml\n"
+                + " version=\"1.0\"?>\n"
+                + "<root>\n"
+                + " <test>t</test>\n"
+                + "</root>"},
+            {"<?xml\n"
+                + " version=\"1.0\"\n"
+                + " encoding=\"UTF-8\"?>\n"
+                + "<root>\n"
+                + " <test>t</test>\n"
+                + "</root>"},
+            {"<?xml\n"
+                + " version=\"1.0\"\n"
+                + " encoding=\"UTF-8\"\n"
+                + " standalone=\"yes\"?>\n"
+                + "<root>\n"
+                + " <test>t</test>\n"
+                + "</root>"},
+            {"<?xml\n"
+                + " version\n"
+                + "=\n"
+                + "\"1.0\"\n"
+                + " encoding\n"
+                + "=\n"
+                + "\"UTF-8\"\n"
+                + " standalone\n"
+                + "=\n"
+                + "\"yes\"?>\n"
+                + "<root>\n"
+                + " <test>t</test>\n"
+                + "</root>"},
+            {"<?xml version=\"1.1\"?><root><test>t</test></root>"},
+            {"<?xml version=\"1.1\" encoding=\"UTF-8\"?><root><test>t</test></root>"},
+            {"<?xml version=\"1.1\" encoding=\"UTF-8\" standalone='yes'?><root><test>t</test></root>"},
+            {"<?xml\n"
+                + " version=\"1.1\"?>\n"
+                + "<root>\n"
+                + " <test>t</test>\n"
+                + "</root>"},
+            {"<?xml\n"
+                + " version=\"1.1\"\n"
+                + " encoding=\"UTF-8\"?>\n"
+                + "<root>\n"
+                + " <test>t</test>\n"
+                + "</root>"},
+            {"<?xml\n"
+                + " version=\"1.1\"\n"
+                + " encoding=\"UTF-8\"\n"
+                + " standalone=\"yes\"?>\n"
+                + "<root>\n"
+                + " <test>t</test>\n"
+                + "</root>"},
+            {"<?xml\n"
+                + " version\n"
+                + "=\n"
+                + "\"1.1\"\n"
+                + " encoding\n"
+                + "=\n"
+                + "\"UTF-8\"\n"
+                + " standalone\n"
+                + "=\n"
+                + "\"yes\"?>\n"
+                + "<root>\n"
+                + " <test>t</test>\n"
+                + "</root>"}
+        };
+    }
+
+    /**
+     * @bug 8169450
+     * Verifies that the parser successfully parses the declarations provided in
+     * xmlDeclarations. Exception would otherwise be thrown as reported in 8169450.
+     *
+     * XML Declaration according to https://www.w3.org/TR/REC-xml/#NT-XMLDecl
+     * [23] XMLDecl     ::= '<?xml' VersionInfo EncodingDecl? SDDecl? S? '?>'
+     * [24] VersionInfo ::= S 'version' Eq ("'" VersionNum "'" | '"' VersionNum '"')
+     * [25] Eq          ::= S? '=' S? [26] VersionNum ::= '1.' [0-9]+
+     *
+     * @param xml the test xml
+     * @throws Exception if the parser fails to parse the xml
+     */
+    @Test(dataProvider = "xmlDeclarations")
+    public void test(String xml) throws Exception {
+        XMLInputFactory xif = XMLInputFactory.newDefaultFactory();
+        XMLStreamReader xsr = xif.createXMLStreamReader(new StringReader(xml));
+        while (xsr.hasNext()) {
+            xsr.next();
+        }
+    }
+
+    /**
+     * @bug 8169450
+     * This particular issue does not appear in DOM parsing since the spaces are
+     * normalized during version detection. This test case then serves as a guard
+     * against such an issue from occuring in the version detection.
+     *
+     * @param xml the test xml
+     * @throws Exception if the parser fails to parse the xml
+     */
+    @Test(dataProvider = "xmlDeclarations")
+    public void testWithDOM(String xml) throws Exception {
+        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+        dbf.setValidating(true);
+        DocumentBuilder db = dbf.newDocumentBuilder();
+        db.parse(new InputSource(new StringReader(xml)));
+    }
+}
--- a/jaxp/test/javax/xml/jaxp/unittest/parsers/Bug6341770.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/parsers/Bug6341770.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,7 @@
 
 package parsers;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
 import static jaxp.library.JAXPTestUtilities.tryRunWithTmpPermission;
 
 import java.io.File;
@@ -61,7 +62,7 @@
             return;
         }
         try {
-            File dir = new File(ALPHA);
+            File dir = new File(USER_DIR + ALPHA);
             dir.delete();
             dir.mkdir();
             File main = new File(dir, "main.xml");
--- a/jaxp/test/javax/xml/jaxp/unittest/sax/Bug7057778Test.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/sax/Bug7057778Test.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,7 @@
 
 package sax;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
 import static jaxp.library.JAXPTestUtilities.getSystemProperty;
 import static jaxp.library.JAXPTestUtilities.tryRunWithTmpPermission;
 
@@ -69,7 +70,7 @@
     @Test
     public void testParse() {
         File src = new File(getClass().getResource(xml).getFile());
-        File dst = new File(xml1);
+        File dst = new File(USER_DIR + xml1);
         try {
             copyFile(src, dst);
             SAXParserFactory spf = SAXParserFactory.newInstance();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/sax/SymbolTableResetTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2017, 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 sax;
+
+import java.io.StringReader;
+
+import javax.xml.parsers.SAXParser;
+import javax.xml.parsers.SAXParserFactory;
+
+import org.testng.Assert;
+import org.testng.annotations.Listeners;
+import org.testng.annotations.Test;
+import org.xml.sax.InputSource;
+import org.xml.sax.helpers.DefaultHandler;
+
+/*
+ * @test
+ * @bug 8173390
+ * @library /javax/xml/jaxp/libs /javax/xml/jaxp/unittest
+ * @run testng/othervm -DrunSecMngr=true sax.SymbolTableResetTest
+ * @run testng/othervm sax.SymbolTableResetTest
+ * @summary Test that SAXParser reallocates symbol table during
+ *          subsequent parse operations
+ */
+@Listeners({jaxp.library.BasePolicy.class})
+public class SymbolTableResetTest {
+
+    /*
+     * Test mimics the SAXParser usage in SAAJ-RI that reuses the
+     * parsers from the internal pool. To avoid memory leaks, symbol
+     * table associated with the parser should be reallocated during each
+     * parse() operation.
+     */
+    @Test
+    public void testReset() throws Exception {
+        // Dummy xml input for parser
+        String input = "<dummy>Test</dummy>";
+        // Create SAXParser
+        SAXParserFactory  spf = SAXParserFactory.newInstance();
+        SAXParser p = spf.newSAXParser();
+        // First parse iteration
+        p.parse(new InputSource(new StringReader(input)), new DefaultHandler());
+        // Get first symbol table reference
+        Object symTable1 = p.getProperty(SYMBOL_TABLE_PROPERTY);
+        p.reset();
+        // Second parse iteration
+        p.parse(new InputSource(new StringReader(input)), new DefaultHandler());
+        // Get second symbol table reference
+        Object symTable2 = p.getProperty(SYMBOL_TABLE_PROPERTY);
+        // Symbol table references should be different
+        Assert.assertNotSame(symTable1, symTable2, "Symbol table references");
+    }
+
+    // Symbol table property
+    private static final String SYMBOL_TABLE_PROPERTY = "http://apache.org/xml/properties/internal/symbol-table";
+
+}
--- a/jaxp/test/javax/xml/jaxp/unittest/stream/Bug6688002Test.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/stream/Bug6688002Test.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,8 @@
 
 package stream;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
+
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.InputStream;
@@ -67,15 +69,15 @@
     }
 
     public class MyRunnable implements Runnable {
-        final int no;
+        final String no;
 
         MyRunnable(int no) {
-            this.no = no;
+            this.no = String.valueOf(no);
         }
 
         public void run() {
             try {
-                FileOutputStream fos = new FileOutputStream("" + no);
+                FileOutputStream fos = new FileOutputStream(USER_DIR + no);
                 XMLStreamWriter w = getWriter(fos);
                 // System.out.println("Writer="+w+" Thread="+Thread.currentThread());
                 w.writeStartDocument();
@@ -89,7 +91,7 @@
                 w.close();
                 fos.close();
 
-                FileInputStream fis = new FileInputStream("" + no);
+                FileInputStream fis = new FileInputStream(USER_DIR + no);
                 XMLStreamReader r = getReader(fis);
                 while (r.hasNext()) {
                     r.next();
--- a/jaxp/test/javax/xml/jaxp/unittest/stream/XMLEventWriterTest/ReaderToWriterTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/stream/XMLEventWriterTest/ReaderToWriterTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,8 @@
 
 package stream.XMLEventWriterTest;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
+
 import java.io.ByteArrayOutputStream;
 import java.io.File;
 import java.io.FileInputStream;
@@ -58,7 +60,7 @@
     private static final XMLOutputFactory XML_OUTPUT_FACTORY = XMLOutputFactory.newInstance();
 
     private static final String INPUT_FILE = "W2JDLR4002TestService.wsdl.data";
-    private static final String OUTPUT_FILE = "Encoded.wsdl";
+    private static final String OUTPUT_FILE = USER_DIR + "Encoded.wsdl";
 
     /**
      * Unit test for writing namespaces when namespaceURI == null.
@@ -126,7 +128,7 @@
 
         try {
             InputStream in = getClass().getResourceAsStream("ReaderToWriterTest.wsdl");
-            OutputStream out = new FileOutputStream("ReaderToWriterTest-out.xml");
+            OutputStream out = new FileOutputStream(USER_DIR + "ReaderToWriterTest-out.xml");
 
             XMLEventReader reader = XML_INPUT_FACTORY.createXMLEventReader(in);
             XMLEventWriter writer = XML_OUTPUT_FACTORY.createXMLEventWriter(out, "UTF-8");
--- a/jaxp/test/javax/xml/jaxp/unittest/stream/XMLStreamWriterTest/WriterTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/stream/XMLStreamWriterTest/WriterTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,8 @@
 
 package stream.XMLStreamWriterTest;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
+
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
@@ -84,7 +86,7 @@
         System.out.println("Test StreamWriter with out any namespace functionality");
 
         try {
-            String outputFile = files[0] + ".out";
+            String outputFile = USER_DIR + files[0] + ".out";
             System.out.println("Writing output to " + outputFile);
 
             xtw = outputFactory.createXMLStreamWriter(new FileOutputStream(outputFile), ENCODING);
@@ -98,7 +100,7 @@
             xtw.flush();
             xtw.close();
 
-            Assert.assertTrue(checkResults(files[0] + ".out", files[0] + ".org"));
+            Assert.assertTrue(checkResults(outputFile, files[0] + ".org"));
 
         } catch (Exception ex) {
             Assert.fail("testOne Failed " + ex);
@@ -113,7 +115,7 @@
         System.out.println("Test StreamWriter's Namespace Context");
 
         try {
-            String outputFile = files[1] + ".out";
+            String outputFile = USER_DIR + files[1] + ".out";
             System.out.println("Writing output to " + outputFile);
 
             xtw = outputFactory.createXMLStreamWriter(System.out);
@@ -157,7 +159,7 @@
         System.out.println("Test StreamWriter for proper element sequence.");
 
         try {
-            String outputFile = files[2] + ".out";
+            String outputFile = USER_DIR + files[2] + ".out";
             System.out.println("Writing output to " + outputFile);
 
             xtw = outputFactory.createXMLStreamWriter(new FileOutputStream(outputFile), ENCODING);
@@ -172,7 +174,7 @@
             xtw.flush();
             xtw.close();
 
-            Assert.assertTrue(checkResults(files[2] + ".out", files[2] + ".org"));
+            Assert.assertTrue(checkResults(outputFile, files[2] + ".org"));
 
         } catch (Exception ex) {
             Assert.fail("testThree Failed " + ex);
@@ -188,7 +190,7 @@
 
         try {
 
-            String outputFile = files[3] + ".out";
+            String outputFile = USER_DIR + files[3] + ".out";
             System.out.println("Writing output to " + outputFile);
 
             xtw = outputFactory.createXMLStreamWriter(new FileOutputStream(outputFile), ENCODING);
@@ -205,7 +207,7 @@
             xtw.flush();
             xtw.close();
 
-            Assert.assertTrue(checkResults(files[3] + ".out", files[3] + ".org"));
+            Assert.assertTrue(checkResults(outputFile, files[3] + ".org"));
 
         } catch (Exception ex) {
             Assert.fail("testFour Failed " + ex);
@@ -221,7 +223,7 @@
 
         try {
 
-            String outputFile = files[4] + ".out";
+            String outputFile = USER_DIR + files[4] + ".out";
             System.out.println("Writing output to " + outputFile);
 
             xtw = outputFactory.createXMLStreamWriter(System.out);
@@ -265,7 +267,7 @@
             xtw.writeEndDocument();
             xtw.flush();
             xtw.close();
-            Assert.assertTrue(checkResults(files[4] + ".out", files[4] + ".org"));
+            Assert.assertTrue(checkResults(outputFile, files[4] + ".org"));
             System.out.println("Done");
         } catch (Exception ex) {
             Assert.fail("testFive Failed " + ex);
@@ -281,7 +283,7 @@
 
         try {
 
-            String outputFile = files[5] + ".out";
+            String outputFile = USER_DIR + files[5] + ".out";
             System.out.println("Writing output to " + outputFile);
 
             xtw = outputFactory.createXMLStreamWriter(System.out);
@@ -325,7 +327,7 @@
             xtw.writeEndDocument();
             xtw.flush();
             xtw.close();
-            Assert.assertTrue(checkResults(files[5] + ".out", files[5] + ".org"));
+            Assert.assertTrue(checkResults(outputFile, files[5] + ".org"));
             System.out.println("Done");
         } catch (Exception ex) {
             Assert.fail("testSix Failed " + ex);
@@ -341,7 +343,7 @@
 
         try {
 
-            String outputFile = files[6] + ".out";
+            String outputFile = USER_DIR + files[6] + ".out";
             System.out.println("Writing output to " + outputFile);
 
             xtw = outputFactory.createXMLStreamWriter(new FileOutputStream(outputFile), ENCODING);
@@ -374,7 +376,7 @@
             xtw.writeEndDocument();
             xtw.flush();
             xtw.close();
-            Assert.assertTrue(checkResults(files[6] + ".out", files[6] + ".org"));
+            Assert.assertTrue(checkResults(outputFile, files[6] + ".org"));
             System.out.println("Done");
         } catch (Exception ex) {
             Assert.fail("testSeven Failed " + ex);
@@ -390,7 +392,7 @@
 
         try {
 
-            String outputFile = files[7] + ".out";
+            String outputFile = USER_DIR + files[7] + ".out";
             System.out.println("Writing output to " + outputFile);
             outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, new Boolean(true));
             xtw = outputFactory.createXMLStreamWriter(new FileOutputStream(outputFile), ENCODING);
@@ -424,7 +426,7 @@
             xtw.flush();
             xtw.close();
             // check against testSeven.xml.org
-            Assert.assertTrue(checkResults(files[7] + ".out", files[7] + ".org"));
+            Assert.assertTrue(checkResults(outputFile, files[7] + ".org"));
             System.out.println("Done");
         } catch (Exception ex) {
             ex.printStackTrace();
@@ -442,7 +444,7 @@
 
         try {
 
-            String outputFile = files[8] + ".out";
+            String outputFile = USER_DIR + files[8] + ".out";
             System.out.println("Writing output to " + outputFile);
             outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, new Boolean(true));
             xtw = outputFactory.createXMLStreamWriter(new FileOutputStream(outputFile), ENCODING);
@@ -476,7 +478,7 @@
             xtw.flush();
             xtw.close();
             // check against testSeven.xml.org
-            Assert.assertTrue(checkResults(files[8] + ".out", files[7] + ".org"));
+            Assert.assertTrue(checkResults(outputFile, files[7] + ".org"));
             System.out.println("Done");
         } catch (Exception ex) {
             Assert.fail("testNine Failed " + ex);
@@ -491,7 +493,7 @@
         System.out.println("Test StreamWriter supplied with no namespace information and" + "isRepairingNamespace is set to true.");
         try {
 
-            String outputFile = files[9] + ".out";
+            String outputFile = USER_DIR + files[9] + ".out";
             System.out.println("Writing output to " + outputFile);
             outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, new Boolean(true));
             xtw = outputFactory.createXMLStreamWriter(new FileOutputStream(outputFile), ENCODING);
@@ -542,7 +544,7 @@
         System.out.println("Test StreamWriter supplied with  namespace information passed through startElement and" + "isRepairingNamespace is set to true.");
         try {
 
-            String outputFile = files[10] + ".out";
+            String outputFile = USER_DIR + files[10] + ".out";
             System.out.println("Writing output to " + outputFile);
             outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, new Boolean(true));
             xtw = outputFactory.createXMLStreamWriter(new FileOutputStream(outputFile), ENCODING);
@@ -576,7 +578,7 @@
             xtw.flush();
             xtw.close();
             // check against testSeven.xml.org
-            Assert.assertTrue(checkResults(files[10] + ".out", files[7] + ".org"));
+            Assert.assertTrue(checkResults(outputFile, files[7] + ".org"));
             System.out.println("Done");
         } catch (Exception ex) {
             Assert.fail("testEleven Failed " + ex);
@@ -592,7 +594,7 @@
 
         try {
 
-            String outputFile = files[11] + ".out";
+            String outputFile = USER_DIR + files[11] + ".out";
             System.out.println("Writing output to " + outputFile);
             outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, new Boolean(true));
             xtw = outputFactory.createXMLStreamWriter(new FileOutputStream(outputFile), ENCODING);
@@ -643,7 +645,7 @@
 
         try {
 
-            String outputFile = files[12] + ".out";
+            String outputFile = USER_DIR + files[12] + ".out";
             System.out.println("Writing output to " + outputFile);
             outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, new Boolean(true));
             xtw = outputFactory.createXMLStreamWriter(new FileOutputStream(outputFile), ENCODING);
@@ -695,7 +697,7 @@
 
         try {
 
-            String outputFile = files[14] + ".out";
+            String outputFile = USER_DIR + files[14] + ".out";
             System.out.println("Writing output to " + outputFile);
             outputFactory.setProperty(XMLOutputFactory.IS_REPAIRING_NAMESPACES, new Boolean(true));
             xtw = outputFactory.createXMLStreamWriter(new FileOutputStream(outputFile), ENCODING);
--- a/jaxp/test/javax/xml/jaxp/unittest/transform/Bug4693341Test.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/transform/Bug4693341Test.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,8 @@
 
 package transform;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
+
 import java.io.File;
 import java.io.FileInputStream;
 import java.io.FileOutputStream;
@@ -55,7 +57,7 @@
     // save dtd file to current working directory to avoid writing into source repository
     public void copyDTDtoWorkDir() throws IOException {
         try (FileInputStream dtdres = new FileInputStream(getClass().getResource("Bug4693341.dtd").getPath());
-             FileOutputStream dtdwork = new FileOutputStream("Bug4693341.dtd");) {
+             FileOutputStream dtdwork = new FileOutputStream(USER_DIR + "Bug4693341.dtd");) {
             int n;
             byte[] buffer = new byte[1024];
             while((n = dtdres.read(buffer)) > -1) {
@@ -71,7 +73,7 @@
 
             copyDTDtoWorkDir();
 
-            File outf = new File("Bug4693341.out");
+            File outf = new File(USER_DIR + "Bug4693341.out");
             StreamResult result = new StreamResult(new FileOutputStream(outf));
 
             String in = getClass().getResource("Bug4693341.xml").getPath();
--- a/jaxp/test/javax/xml/jaxp/unittest/transform/Bug4892774.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/transform/Bug4892774.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,8 @@
 
 package transform;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
+
 import java.io.File;
 
 import javax.xml.transform.Source;
@@ -58,7 +60,7 @@
 
     private final String XML_FILE = "catalog.xml";
     private final String XML10_FILE = "catalog_10.xml"; // 1.0 version document
-    private final String TEMP_FILE = "tmp.xml";
+    private final String TEMP_FILE = USER_DIR + "tmp.xml";
     private final String EXPECTED_VERSION = "1.1";
     static private Transformer idTransform = null;
 
--- a/jaxp/test/javax/xml/jaxp/unittest/transform/Bug6216226Test.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/transform/Bug6216226Test.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,7 @@
 
 package transform;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
 import static jaxp.library.JAXPTestUtilities.runWithTmpPermission;
 
 import java.io.File;
@@ -52,7 +53,7 @@
     @Test
     public final void test() {
         try {
-            File test = new File("bug6216226.txt");
+            File test = new File(USER_DIR + "bug6216226.txt");
             TransformerFactory tf = TransformerFactory.newInstance();
             Transformer xformer = tf.newTransformer();
             StringReader st = new StringReader("<?xml version=\"1.0\" encoding=\"UTF-8\"?><doc></doc>");
--- a/jaxp/test/javax/xml/jaxp/unittest/transform/CR6935697Test.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/transform/CR6935697Test.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,8 @@
 
 package transform;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
+
 import java.io.FileOutputStream;
 
 import javax.xml.transform.Result;
@@ -65,7 +67,7 @@
             Transformer xformer = template.newTransformer();
             // Prepare the input and output files
             Source source = new StreamSource(getClass().getResourceAsStream(inFilename));
-            Result result = new StreamResult(new FileOutputStream(outFilename));
+            Result result = new StreamResult(new FileOutputStream(USER_DIR + outFilename));
             // Apply the xsl file to the source file and write the result to the
             // output file
             xformer.transform(source, result);
--- a/jaxp/test/javax/xml/jaxp/unittest/transform/XSLTFunctionsTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/transform/XSLTFunctionsTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,7 @@
 
 package transform;
 
+import java.io.FilePermission;
 import java.io.IOException;
 import java.io.StringReader;
 import java.io.StringWriter;
@@ -46,6 +47,7 @@
 import static jaxp.library.JAXPTestUtilities.runWithAllPerm;
 import static jaxp.library.JAXPTestUtilities.clearSystemProperty;
 import static jaxp.library.JAXPTestUtilities.setSystemProperty;
+import static jaxp.library.JAXPTestUtilities.tryRunWithTmpPermission;
 import static jaxp.library.JAXPTestUtilities.getSystemProperty;
 
 /*
@@ -77,7 +79,9 @@
         Transformer t = tf.newTransformer(new StreamSource(new StringReader(xsl)));
 
         //Transform the xml
-        t.transform(new StreamSource(new StringReader(xml)), new StreamResult(new StringWriter()));
+        tryRunWithTmpPermission(
+                () -> t.transform(new StreamSource(new StringReader(xml)), new StreamResult(new StringWriter())),
+                new FilePermission(output, "write"), new FilePermission(redirect, "write"));
 
         // Verifies that the output is redirected successfully
         String userDir = getSystemProperty("user.dir");
--- a/jaxp/test/javax/xml/jaxp/unittest/transform/util/TransformerUtil.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/transform/util/TransformerUtil.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,8 @@
 
 package transform.util;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
+
 import java.io.InputStream;
 
 import javax.xml.parsers.DocumentBuilder;
@@ -34,7 +36,7 @@
 
     protected String type;
 
-    protected final String TEMP_FILE = "tmp.xml";
+    protected final String TEMP_FILE = USER_DIR + "tmp.xml";
 
     public abstract Source prepareSource(InputStream is) throws Exception;
 
--- a/jaxp/test/javax/xml/jaxp/unittest/validation/CR6708840Test.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/validation/CR6708840Test.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,8 @@
 
 package validation;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
+
 import java.io.File;
 import java.io.FileWriter;
 
@@ -122,7 +124,7 @@
             Validator schemaValidator = schemaGrammar.newValidator();
 
             Source staxSrc = new StAXSource(staxReader);
-            File resultFile = new File("gMonths.result.xml");
+            File resultFile = new File(USER_DIR + "gMonths.result.xml");
             if (resultFile.exists()) {
                 resultFile.delete();
             }
--- a/jaxp/test/javax/xml/jaxp/unittest/validation/ValidatorTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxp/test/javax/xml/jaxp/unittest/validation/ValidatorTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,6 +23,7 @@
 
 package validation;
 
+import static jaxp.library.JAXPTestUtilities.USER_DIR;
 import static jaxp.library.JAXPTestUtilities.runWithTmpPermission;
 
 import java.io.File;
@@ -61,7 +62,7 @@
 
         File resultFile = null;
         try {
-            resultFile = new File("stax.result");
+            resultFile = new File(USER_DIR + "stax.result");
             if (resultFile.exists()) {
                 resultFile.delete();
             }
@@ -88,7 +89,7 @@
 
         File resultFile = null;
         try {
-            resultFile = new File("stax.result");
+            resultFile = new File(USER_DIR + "stax.result");
             if (resultFile.exists()) {
                 resultFile.delete();
             }
@@ -117,7 +118,7 @@
         // test valid gMonths
         File resultFile = null;
         try {
-            resultFile = new File("gMonths.result.xml");
+            resultFile = new File(USER_DIR + "gMonths.result.xml");
             if (resultFile.exists()) {
                 resultFile.delete();
             }
@@ -144,7 +145,7 @@
         // test invalid gMonths
         File invalidResultFile = null;
         try {
-            invalidResultFile = new File("gMonths-invalid.result.xml");
+            invalidResultFile = new File(USER_DIR + "gMonths-invalid.result.xml");
             if (invalidResultFile.exists()) {
                 invalidResultFile.delete();
             }
--- a/jaxws/.hgtags	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxws/.hgtags	Thu Mar 16 20:47:03 2017 +0000
@@ -399,6 +399,7 @@
 c48b4d4768b1c2b8fe5d1a844ca13732e5dfbe2a jdk-9+151
 6f8fb1cf7e5f61c40dcc3654f9a623c505f6de1f jdk-9+152
 7a532a9a227137155b905341d4b99939db51220e jdk-9+153
+34af95c7dbff74f3448fcdb7d745524e8a1cc88a jdk-10+0
 34af95c7dbff74f3448fcdb7d745524e8a1cc88a jdk-9+154
 9b9918656c97724fd89c04a8547043bbd37f5935 jdk-9+155
 7c829eba781409b4fe15392639289af1553dcf63 jdk-9+156
--- a/jaxws/.jcheck/conf	Thu Mar 16 16:34:35 2017 +0000
+++ b/jaxws/.jcheck/conf	Thu Mar 16 20:47:03 2017 +0000
@@ -1,1 +1,1 @@
-project=jdk9
+project=jdk10
--- a/jdk/.hgtags	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/.hgtags	Thu Mar 16 20:47:03 2017 +0000
@@ -396,5 +396,9 @@
 d27bab22ff62823902d93d1d35ca397cfd50d059 jdk-9+151
 a20f2cf90762673e1bc4980fd6597e70a2578045 jdk-9+152
 1c4411322327aea3f91011ec3977a12a05b09629 jdk-9+153
+f2325d80b37c2817e15039bf64189a08e29c6d39 jdk-10+0
 c97e7a8b8da062b9070df442f9cf308e10845fb7 jdk-9+154
 e170c858888e83d5c0994504599b6ed7a1fb0cfc jdk-9+155
+7d64e541a6c04c714bcad4c8b553db912f827cd5 jdk-9+156
+fdfa7b2fe9a7db06792eae20f97748f3e85bb83a jdk-9+157
+c476ca73750698fa5654e101af699ee45db38e2a jdk-9+158
--- a/jdk/.jcheck/conf	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/.jcheck/conf	Thu Mar 16 20:47:03 2017 +0000
@@ -1,1 +1,1 @@
-project=jdk9
+project=jdk10
--- a/jdk/make/CompileModuleTools.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/make/CompileModuleTools.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -37,5 +37,7 @@
                 build/tools/jigsaw, \
     BIN := $(TOOLS_CLASSES_DIR), \
     ADD_JAVAC_FLAGS := \
+        --add-modules jdk.jdeps \
         --add-exports java.base/jdk.internal.module=ALL-UNNAMED \
+        --add-exports jdk.jdeps/com.sun.tools.jdeps=ALL-UNNAMED \
 ))
--- a/jdk/make/GenerateModuleSummary.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/make/GenerateModuleSummary.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -31,11 +31,16 @@
 include ModuleTools.gmk
 
 GENGRAPHS_DIR := $(IMAGES_OUTPUTDIR)/gengraphs
+SPEC_DOTFILES_DIR := $(IMAGES_OUTPUTDIR)/spec-dotfiles
 TOOLS_MODULE_SRCDIR := $(JDK_TOPDIR)/make/src/classes/build/tools/jigsaw
 
 $(GENGRAPHS_DIR)/jdk.dot: $(BUILD_JIGSAW_TOOLS)
 	$(MKDIR) -p $(@D)
-	$(TOOL_GENGRAPHS) $(GENGRAPHS_DIR)
+	$(TOOL_GENGRAPHS) --output $(GENGRAPHS_DIR)
+
+$(SPEC_DOTFILES_DIR)/java.se.dot: $(BUILD_JIGSAW_TOOLS)
+	$(MKDIR) -p $(@D)
+	$(TOOL_GENGRAPHS) --spec --output $(SPEC_DOTFILES_DIR)
 
 $(GENGRAPHS_DIR)/technology-summary.html: $(TOOLS_MODULE_SRCDIR)/technology-summary.html
 	$(install-file)
@@ -44,4 +49,4 @@
 	$(MKDIR) -p $(@D)
 	$(TOOL_MODULESUMMARY) -o $@ --module-path $(IMAGES_OUTPUTDIR)/jmods
 
-all: $(GENGRAPHS_DIR)/jdk.dot $(GENGRAPHS_DIR)/module-summary.html
+all: $(GENGRAPHS_DIR)/jdk.dot $(GENGRAPHS_DIR)/module-summary.html $(SPEC_DOTFILES_DIR)/java.se.dot
--- a/jdk/make/ModuleTools.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/make/ModuleTools.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -36,6 +36,8 @@
     BUILD_JIGSAW_TOOLS, $(TOOLS_CLASSES_DIR))
 
 TOOL_GENGRAPHS := $(BUILD_JAVA) -esa -ea -cp $(TOOLS_CLASSES_DIR) \
+    --add-modules jdk.jdeps \
+    --add-exports jdk.jdeps/com.sun.tools.jdeps=ALL-UNNAMED \
     build.tools.jigsaw.GenGraphs
 
 TOOL_MODULESUMMARY := $(BUILD_JAVA) -esa -ea -cp $(TOOLS_CLASSES_DIR) \
--- a/jdk/make/gensrc/GensrcMisc.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/make/gensrc/GensrcMisc.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -116,11 +116,13 @@
     JCE_DEFAULT_POLICY = limited
 endif
 
-$(eval $(call SetupTextFileProcessing, BUILD_JCESECURITY_JAVA, \
-    SOURCE_FILES := $(JDK_TOPDIR)/src/java.base/share/classes/javax/crypto/JceSecurity.java.template, \
-    OUTPUT_FILE := $(SUPPORT_OUTPUTDIR)/gensrc/java.base/javax/crypto/JceSecurity.java, \
-    REPLACEMENTS := \
+ifneq ($(wildcard $(JDK_TOPDIR)/src/java.base/share/classes/javax/crypto/JceSecurity.java.template), )
+  $(eval $(call SetupTextFileProcessing, BUILD_JCESECURITY_JAVA, \
+      SOURCE_FILES := $(JDK_TOPDIR)/src/java.base/share/classes/javax/crypto/JceSecurity.java.template, \
+      OUTPUT_FILE := $(SUPPORT_OUTPUTDIR)/gensrc/java.base/javax/crypto/JceSecurity.java, \
+      REPLACEMENTS := \
         @@JCE_DEFAULT_POLICY@@ => $(JCE_DEFAULT_POLICY), \
-))
+  ))
 
-GENSRC_JAVA_BASE += $(BUILD_JCESECURITY_JAVA)
+  GENSRC_JAVA_BASE += $(BUILD_JCESECURITY_JAVA)
+endif
--- a/jdk/make/launcher/Launcher-java.base.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/make/launcher/Launcher-java.base.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 2017, 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
@@ -71,102 +71,37 @@
 
 ################################################################################
 
-BUILD_JEXEC :=
-BUILD_JEXEC_SRC :=
-BUILD_JEXEC_INC :=
-BUILD_JEXEC_DST_DIR := $(SUPPORT_OUTPUTDIR)/modules_libs/java.base
-
-#
-# UNHANDLED:
-# - COMPILE_APPROACH = normal
-#
-
-#
-# jdk/make/java/Makefile
-#
-ifeq ($(OPENJDK_TARGET_OS), solaris)
-  ifeq ($(OPENJDK_TARGET_CPU_BITS), 32)
-    BUILD_JEXEC := 1
-  endif
-endif
-
 ifeq ($(OPENJDK_TARGET_OS), linux)
-  BUILD_JEXEC := 1
-endif # OPENJDK_TARGET_OS
-
-#
-# jdk/make/java/jexec/Makefile
-#
-ifeq ($(BUILD_JEXEC), 1)
-
-  ifeq ($(OPENJDK_TARGET_OS), windows)
-  else ifeq ($(OPENJDK_TARGET_OS), macosx)
-    BUILD_JEXEC_SRC := $(JDK_TOPDIR)/src/java.base/macosx/native/launcher
-  else
-    BUILD_JEXEC_SRC := $(JDK_TOPDIR)/src/java.base/unix/native/launcher
-  endif
-
-  ifeq ($(OPENJDK_TARGET_OS), linux)
-    BUILD_JEXEC_DST_DIR := $(SUPPORT_OUTPUTDIR)/modules_libs/java.base
-    BUILD_JEXEC_INC += -I$(JDK_TOPDIR)/src/java.base/share/native/libjli
-  endif
-endif
-
-#
-# Note that the two Makefile's seems to contradict each other,
-# and that src/macosx/bin/jexec.c seems unused
-#
-ifneq ($(BUILD_JEXEC_SRC), )
-  $(eval $(call SetupNativeCompilation,BUILD_JEXEC, \
-      SRC := $(BUILD_JEXEC_SRC), \
+  $(eval $(call SetupNativeCompilation, BUILD_JEXEC, \
+      SRC := $(JDK_TOPDIR)/src/$(MODULE)/unix/native/launcher, \
       INCLUDE_FILES := jexec.c, \
       OPTIMIZATION := LOW, \
       CFLAGS := $(CFLAGS_JDKEXE) \
-          $(BUILD_JEXEC_INC), \
+          -I$(JDK_TOPDIR)/src/$(MODULE)/share/native/libjli, \
       CFLAGS_linux := -fPIC, \
       CFLAGS_solaris := -KPIC, \
       LDFLAGS := $(LDFLAGS_JDKEXE), \
       OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/jexec_obj, \
-      OUTPUT_DIR := $(BUILD_JEXEC_DST_DIR), \
-      PROGRAM := jexec))
+      OUTPUT_DIR := $(SUPPORT_OUTPUTDIR)/modules_libs/$(MODULE), \
+      PROGRAM := jexec, \
+  ))
 
   TARGETS += $(BUILD_JEXEC)
 endif
 
 ################################################################################
 
-BUILD_JSPAWNHELPER :=
-BUILD_JSPAWNHELPER_SRC := $(JDK_TOPDIR)/src/java.base/unix/native/jspawnhelper
-JSPAWNHELPER_CFLAGS := -I$(JDK_TOPDIR)/src/java.base/unix/native/libjava
-BUILD_JSPAWNHELPER_DST_DIR := $(SUPPORT_OUTPUTDIR)/modules_libs/java.base
-LINK_JSPAWNHELPER_OBJECTS := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/libjava/childproc.o
-BUILD_JSPAWNHELPER_LDFLAGS :=
-
 ifneq ($(findstring $(OPENJDK_TARGET_OS), macosx solaris aix), )
-  BUILD_JSPAWNHELPER := 1
-endif
-
-ifeq ($(OPENJDK_TARGET_OS), macosx)
-  BUILD_JSPAWNHELPER_DST_DIR := $(SUPPORT_OUTPUTDIR)/modules_libs/java.base
-endif
-
-ifeq ($(OPENJDK_TARGET_CPU_BITS), 64)
-  BUILD_JSPAWNHELPER_LDFLAGS += $(COMPILER_TARGET_BITS_FLAG)64
-endif
-
-ifeq ($(BUILD_JSPAWNHELPER), 1)
-  $(eval $(call SetupNativeCompilation,BUILD_JSPAWNHELPER, \
-      SRC := $(BUILD_JSPAWNHELPER_SRC), \
-      INCLUDE_FILES := jspawnhelper.c, \
+  $(eval $(call SetupNativeCompilation, BUILD_JSPAWNHELPER, \
+      SRC := $(JDK_TOPDIR)/src/$(MODULE)/unix/native/jspawnhelper, \
       OPTIMIZATION := LOW, \
-      CFLAGS := $(CFLAGS_JDKEXE) $(JSPAWNHELPER_CFLAGS), \
-      LDFLAGS := $(LDFLAGS_JDKEXE) $(BUILD_JSPAWNHELPER_LDFLAGS), \
-      LIBS := $(LINK_JSPAWNHELPER_OBJECTS), \
+      CFLAGS := $(CFLAGS_JDKEXE) -I$(JDK_TOPDIR)/src/$(MODULE)/unix/native/libjava, \
+      EXTRA_OBJECT_FILES := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/libjava/childproc.o, \
+      LDFLAGS := $(LDFLAGS_JDKEXE), \
       OBJECT_DIR := $(SUPPORT_OUTPUTDIR)/native/$(MODULE)/jspawnhelper, \
-      OUTPUT_DIR := $(BUILD_JSPAWNHELPER_DST_DIR), \
-      PROGRAM := jspawnhelper))
-
-  $(BUILD_JSPAWNHELPER): $(LINK_JSPAWNHELPER_OBJECTS)
+      OUTPUT_DIR := $(SUPPORT_OUTPUTDIR)/modules_libs/$(MODULE), \
+      PROGRAM := jspawnhelper, \
+  ))
 
   TARGETS += $(BUILD_JSPAWNHELPER)
 endif
--- a/jdk/make/launcher/Launcher-jdk.pack.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/make/launcher/Launcher-jdk.pack.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -44,7 +44,7 @@
   UNPACKEXE_CFLAGS += -DSYSTEM_ZLIB
   UNPACKEXE_LIBS := -lz
 else
-  UNPACKEXE_CFLAGS += -I$(JDK_TOPDIR)/src/java.base/share/native/libzip/zlib-1.2.8
+  UNPACKEXE_CFLAGS += -I$(JDK_TOPDIR)/src/java.base/share/native/libzip/zlib
   UNPACKEXE_ZIPOBJS := $(SUPPORT_OUTPUTDIR)/native/java.base/libzip/zcrc32$(OBJ_SUFFIX) \
       $(SUPPORT_OUTPUTDIR)/native/java.base/libzip/deflate$(OBJ_SUFFIX) \
       $(SUPPORT_OUTPUTDIR)/native/java.base/libzip/trees$(OBJ_SUFFIX) \
--- a/jdk/make/lib/Awt2dLibraries.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/make/lib/Awt2dLibraries.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -889,7 +889,7 @@
   LIBSPLASHSCREEN_LIBS :=
 
   ifneq ($(USE_EXTERNAL_LIBZ), true)
-    LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/java.base/share/native/libzip/zlib-1.2.8
+    LIBSPLASHSCREEN_DIRS += $(JDK_TOPDIR)/src/java.base/share/native/libzip/zlib
     LIBSPLASHSCREEN_CFLAGS += $(ZLIB_CPPFLAGS)
   endif
 
--- a/jdk/make/lib/CoreLibraries.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/make/lib/CoreLibraries.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -202,7 +202,7 @@
 
 BUILD_LIBZIP_EXCLUDES :=
 ifeq ($(USE_EXTERNAL_LIBZ), true)
-  LIBZIP_EXCLUDES += zlib-1.2.8
+  LIBZIP_EXCLUDES += zlib
 endif
 
 BUILD_LIBZIP_REORDER :=
@@ -343,7 +343,7 @@
 ifneq ($(USE_EXTERNAL_LIBZ), true)
   LIBJLI_CFLAGS += $(ZLIB_CPPFLAGS)
   LIBJLI_EXTRA_FILES += \
-      $(addprefix $(JDK_TOPDIR)/src/java.base/share/native/libzip/zlib-1.2.8/, \
+      $(addprefix $(JDK_TOPDIR)/src/java.base/share/native/libzip/zlib/, \
           inflate.c \
           inftrees.c \
           inffast.c \
--- a/jdk/make/lib/LibCommon.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/make/lib/LibCommon.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -73,7 +73,7 @@
 ifeq ($(USE_EXTERNAL_LIBZ), true)
   LIBZ := -lz
 else
-  ZLIB_CPPFLAGS := -I$(JDK_TOPDIR)/src/java.base/share/native/libzip/zlib-1.2.8
+  ZLIB_CPPFLAGS := -I$(JDK_TOPDIR)/src/java.base/share/native/libzip/zlib
 endif
 
 ###############################################################################
--- a/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/make/src/classes/build/tools/jigsaw/GenGraphs.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,29 +25,21 @@
 
 package build.tools.jigsaw;
 
+import com.sun.tools.jdeps.ModuleDotGraph;
+import com.sun.tools.jdeps.ModuleDotGraph.DotGraphBuilder;
+
 import java.io.IOException;
-import java.io.OutputStream;
-import java.io.PrintStream;
 import java.lang.module.Configuration;
 import java.lang.module.ModuleDescriptor;
 import java.lang.module.ModuleFinder;
 import java.lang.module.ModuleReference;
-import java.lang.module.ResolvedModule;
 import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
-import java.util.List;
 import java.util.Map;
 import java.util.Set;
-import java.util.TreeSet;
-import java.util.function.Function;
-
-import static java.util.stream.Collectors.*;
-import static java.lang.module.ModuleDescriptor.Requires.Modifier.TRANSITIVE;
 
 /**
  * Generate the DOT file for a module graph for each module in the JDK
@@ -56,238 +48,100 @@
 public class GenGraphs {
 
     public static void main(String[] args) throws Exception {
+        Path dir = null;
+        boolean spec = false;
+        for (int i=0; i < args.length; i++) {
+            String arg = args[i];
+            if (arg.equals("--spec")) {
+                spec = true;
+            } else if (arg.equals("--output")) {
+                i++;
+                dir = i < args.length ? Paths.get(args[i]) : null;
+            } else if (arg.startsWith("-")) {
+                throw new IllegalArgumentException("Invalid option: " + arg);
+            }
+        }
 
-        if (args.length != 1) {
-            System.err.println("ERROR: specify the output directory");
+        if (dir == null) {
+            System.err.println("ERROR: must specify --output argument");
             System.exit(1);
         }
-        Path dir = Paths.get(args[0]);
+
+        // setup and configure the dot graph attributes
+        initDotGraphAttributes();
         Files.createDirectories(dir);
 
-        ModuleFinder finder = ModuleFinder.ofSystem();
+        GenGraphs genGraphs = new GenGraphs(dir, spec);
 
-        Set<ModuleDescriptor> javaSEModules
-            = new TreeSet<>(finder.findAll().stream()
-                                  .map(ModuleReference::descriptor)
-                                  .filter(m -> (m.name().startsWith("java.") &&
-                                               !m.name().equals("java.smartcardio")))
-                                  .collect(toSet()));
-        Set<ModuleDescriptor> jdkModules
-            = new TreeSet<>(finder.findAll().stream()
-                                  .map(ModuleReference::descriptor)
-                                  .filter(m -> !javaSEModules.contains(m))
-                                  .collect(toSet()));
-
-        GenGraphs genGraphs = new GenGraphs(dir, javaSEModules, jdkModules);
-        Set<String> mods = new HashSet<>();
-        for (ModuleReference mref: finder.findAll()) {
-            mods.add(mref.descriptor().name());
-            genGraphs.genDotFile(mref);
+        // print dot file for each module
+        Map<String, Configuration> configurations = new HashMap<>();
+        Set<String> modules = new HashSet<>();
+        ModuleFinder finder = ModuleFinder.ofSystem();
+        for (ModuleReference mref : finder.findAll()) {
+            String name = (mref.descriptor().name());
+            modules.add(name);
+            if (genGraphs.accept(name, mref.descriptor())) {
+                configurations.put(name, Configuration.empty()
+                                                      .resolve(finder,
+                                                               ModuleFinder.of(),
+                                                               Set.of(name)));
+            }
         }
 
-        // all modules
-        genGraphs.genDotFile("jdk", mods);
+        if (genGraphs.accept("jdk", null)) {
+            // print a graph of all JDK modules
+            configurations.put("jdk", Configuration.empty()
+                                                   .resolve(finder,
+                                                            ModuleFinder.of(),
+                                                            modules));
+        }
 
+        genGraphs.genDotFiles(configurations);
     }
 
-    private static final String ORANGE = "#e76f00";
-    private static final String BLUE = "#437291";
-    private static final String GRAY = "#dddddd";
-
-    private static final String REEXPORTS = "";
-    private static final String REQUIRES = "style=\"dashed\"";
-    private static final String REQUIRES_BASE = "color=\"" + GRAY + "\"";
-
-    private static final Map<String,Integer> weights = new HashMap<>();
-    private static final List<Set<String>> ranks = new ArrayList<>();
-
-    private static void weight(String s, String t, int w) {
-        weights.put(s + ":" + t, w);
-    }
+    static void initDotGraphAttributes() {
+        int h = 1000;
+        DotGraphBuilder.weight("java.se", "java.sql.rowset", h * 10);
+        DotGraphBuilder.weight("java.sql.rowset", "java.sql", h * 10);
+        DotGraphBuilder.weight("java.sql", "java.xml", h * 10);
+        DotGraphBuilder.weight("java.xml", "java.base", h * 10);
 
-    private static int weightOf(String s, String t) {
-        int w = weights.getOrDefault(s + ":" + t, 1);
-        if (w != 1)
-            return w;
-        if (s.startsWith("java.") && t.startsWith("java."))
-            return 10;
-        return 1;
-    }
-
-    static {
-        int h = 1000;
-        weight("java.se", "java.sql.rowset", h * 10);
-        weight("java.sql.rowset", "java.sql", h * 10);
-        weight("java.sql", "java.xml", h * 10);
-        weight("java.xml", "java.base", h * 10);
-
-        ranks.add(Set.of("java.logging", "java.scripting", "java.xml"));
-        ranks.add(Set.of("java.sql"));
-        ranks.add(Set.of("java.compiler", "java.instrument"));
-        ranks.add(Set.of("java.desktop", "java.management"));
-        ranks.add(Set.of("java.corba", "java.xml.ws"));
-        ranks.add(Set.of("java.xml.bind", "java.xml.ws.annotation"));
-
+        DotGraphBuilder.sameRankNodes(Set.of("java.logging", "java.scripting", "java.xml"));
+        DotGraphBuilder.sameRankNodes(Set.of("java.sql"));
+        DotGraphBuilder.sameRankNodes(Set.of("java.compiler", "java.instrument"));
+        DotGraphBuilder.sameRankNodes(Set.of("java.desktop", "java.management"));
+        DotGraphBuilder.sameRankNodes(Set.of("java.corba", "java.xml.ws"));
+        DotGraphBuilder.sameRankNodes(Set.of("java.xml.bind", "java.xml.ws.annotation"));
+        DotGraphBuilder.setRankSep(0.7);
+        DotGraphBuilder.setFontSize(12);
+        DotGraphBuilder.setArrowSize(1);
+        DotGraphBuilder.setArrowWidth(2);
     }
 
     private final Path dir;
-    private final Set<ModuleDescriptor> javaGroup;
-    private final Set<ModuleDescriptor> jdkGroup;
-
-    GenGraphs(Path dir, Set<ModuleDescriptor> javaGroup, Set<ModuleDescriptor> jdkGroup) {
+    private final boolean spec;
+    GenGraphs(Path dir, boolean spec) {
         this.dir = dir;
-        this.javaGroup = Collections.unmodifiableSet(javaGroup);
-        this.jdkGroup = Collections.unmodifiableSet(jdkGroup);
-    }
-
-    /**
-     * Generates a dot file for the given module reference as the root.
-     */
-    void genDotFile(ModuleReference mref) throws IOException {
-        String name = mref.descriptor().name();
-        genDotFile(name, Set.of(name));
+        this.spec = spec;
     }
 
-    /**
-     * Generates a dot file for the given set of root modules.
-     */
-    void genDotFile(String name, Set<String> roots) throws IOException {
-        Configuration cf =
-            Configuration.empty().resolveRequires(ModuleFinder.ofSystem(),
-                                                  ModuleFinder.of(),
-                                                  roots);
-
-        Set<ModuleDescriptor> mds = cf.modules().stream()
-                .map(ResolvedModule::reference)
-                .map(ModuleReference::descriptor)
-                .collect(toSet());
-
-        // generate a dot file for the resolved graph
-        try (OutputStream os = Files.newOutputStream(dir.resolve(name + ".dot"));
-             PrintStream out = new PrintStream(os)) {
-            printGraph(out, name, gengraph(cf),
-                       mds.stream()
-                          .collect(toMap(ModuleDescriptor::name, Function.identity()))
-            );
-        }
-
-        if (name.equals("java.se") || name.equals("java.se.ee")) {
-            // generate a dot file for Java SE module graph
-            try (OutputStream os = Files.newOutputStream(dir.resolve(name + "-spec.dot"));
-                 PrintStream out = new PrintStream(os)) {
-                // transitive reduction on the graph of `requires transitive` edges
-                // filter out jdk.* modules which are implementation dependences
-                Graph<String> graph = requiresTransitiveGraph(cf, true);
-                printGraph(out, name, graph,
-                           mds.stream()
-                              .filter(md -> !md.name().startsWith("jdk.") &&
-                                                graph.nodes().contains(md.name()))
-                              .collect(toMap(ModuleDescriptor::name, Function.identity()))
-                );
-            }
-        }
+    void genDotFiles(Map<String, Configuration> configurations) throws IOException {
+        ModuleDotGraph dotGraph = new ModuleDotGraph(configurations, spec);
+        dotGraph.genDotFiles(dir);
     }
 
-    private void printGraph(PrintStream out,
-                            String name,
-                            Graph<String> graph,
-                            Map<String, ModuleDescriptor> nameToModule)
-        throws IOException
-    {
-            Set<ModuleDescriptor> descriptors = new TreeSet<>(nameToModule.values());
-
-            out.format("digraph \"%s\" {%n", name);
-            out.format("size=\"25,25\";");
-            out.format("nodesep=.5;%n");
-            out.format("ranksep=1.5;%n");
-            out.format("pencolor=transparent;%n");
-            out.format("node [shape=plaintext, fontname=\"DejaVuSans\", fontsize=36, margin=\".2,.2\"];%n");
-            out.format("edge [penwidth=4, color=\"#999999\", arrowhead=open, arrowsize=2];%n");
-
-            out.format("subgraph %sse {%n", name.equals("jdk") ? "cluster_" : "");
-            descriptors.stream()
-                .filter(javaGroup::contains)
-                .map(ModuleDescriptor::name)
-                .forEach(mn -> out.format("  \"%s\" [fontcolor=\"%s\", group=%s];%n",
-                                          mn, ORANGE, "java"));
-            out.format("}%n");
+    boolean accept(String name, ModuleDescriptor descriptor) {
+        if (!spec) return true;
 
-            // same ranks
-            ranks.stream()
-                .map(group -> descriptors.stream()
-                                         .map(ModuleDescriptor::name)
-                                         .filter(group::contains)
-                                         .map(mn -> "\"" + mn + "\"")
-                                         .collect(joining(",")))
-                .filter(group -> group.length() > 0)
-                .forEach(group -> out.format("{rank=same %s}%n", group));
-
-            descriptors.stream()
-                .filter(jdkGroup::contains)
-                .map(ModuleDescriptor::name)
-                .forEach(mn -> out.format("  \"%s\" [fontcolor=\"%s\", group=%s];%n",
-                                          mn, BLUE, "jdk"));
-
-            descriptors.stream()
-                .forEach(md -> {
-                    String mn = md.name();
-                    Set<String> requiresTransitive = md.requires().stream()
-                            .filter(d -> d.modifiers().contains(TRANSITIVE))
-                            .map(d -> d.name())
-                            .collect(toSet());
+        if (name.equals("jdk"))
+            return false;
 
-                    graph.adjacentNodes(mn)
-                         .stream()
-                         .filter(nameToModule::containsKey)
-                         .forEach(dn -> {
-                             String attr = dn.equals("java.base") ? REQUIRES_BASE
-                                    : (requiresTransitive.contains(dn) ? REEXPORTS : REQUIRES);
-                             int w = weightOf(mn, dn);
-                             if (w > 1)
-                                 attr += "weight=" + w;
-                             out.format("  \"%s\" -> \"%s\" [%s];%n", mn, dn, attr);
-                         });
-                });
-
-            out.println("}");
-    }
+        if (name.equals("java.se") || name.equals("java.se.ee"))
+            return true;
 
-    /**
-     * Returns a Graph of the given Configuration after transitive reduction.
-     *
-     * Transitive reduction of requires transitive edge and requires edge have
-     * to be applied separately to prevent the requires transitive edges
-     * (e.g. U -> V) from being reduced by a path (U -> X -> Y -> V)
-     * in which  V would not be re-exported from U.
-     */
-    private Graph<String> gengraph(Configuration cf) {
-        Graph.Builder<String> builder = new Graph.Builder<>();
-        for (ResolvedModule resolvedModule : cf.modules()) {
-            String mn = resolvedModule.reference().descriptor().name();
-            builder.addNode(mn);
-            resolvedModule.reads().stream()
-                    .map(ResolvedModule::name)
-                    .forEach(target -> builder.addEdge(mn, target));
-        }
-        Graph<String> rpg = requiresTransitiveGraph(cf, false);
-        return builder.build().reduce(rpg);
+        // only the module that has exported API
+        return descriptor.exports().stream()
+                         .filter(e -> !e.isQualified())
+                         .findAny().isPresent();
     }
-
-    /**
-     * Returns a Graph containing only requires transitive edges
-     * with transitive reduction.
-     */
-    private Graph<String> requiresTransitiveGraph(Configuration cf, boolean includeBase) {
-        Graph.Builder<String> builder = new Graph.Builder<>();
-        for (ResolvedModule resolvedModule : cf.modules()) {
-            ModuleDescriptor descriptor = resolvedModule.reference().descriptor();
-            String mn = descriptor.name();
-            descriptor.requires().stream()
-                    .filter(d -> d.modifiers().contains(TRANSITIVE)
-                                    || (includeBase && d.name().equals("java.base")))
-                    .map(d -> d.name())
-                    .forEach(d -> builder.addEdge(mn, d));
-        }
-        return builder.build().reduce();
-    }
-}
+}
\ No newline at end of file
--- a/jdk/make/src/classes/build/tools/jigsaw/Graph.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,171 +0,0 @@
-/*
- * Copyright (c) 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
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package build.tools.jigsaw;
-
-import java.io.PrintStream;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.LinkedList;
-import java.util.Map;
-import java.util.Set;
-
-public class Graph<T> {
-    private static boolean traceOn = Boolean.getBoolean("build.tools.module.trace");
-    private final Set<T> nodes;
-    private final Map<T, Set<T>> edges;
-    private Graph(Set<T> nodes, Map<T, Set<T>> edges) {
-        this.nodes = nodes;
-        this.edges = edges;
-    }
-
-    public Set<T> nodes() {
-        return nodes;
-    }
-
-    public Map<T, Set<T>> edges() {
-        return edges;
-    }
-
-    public Set<T> adjacentNodes(T u) {
-        return edges.get(u);
-    }
-
-    /**
-     * Returns a new Graph after transitive reduction
-     */
-    public Graph<T> reduce() {
-        Graph.Builder<T> builder = new Builder<>();
-        nodes.stream()
-             .forEach(u -> {
-                 builder.addNode(u);
-                 edges.get(u).stream()
-                         .filter(v -> !pathExists(u, v, false))
-                         .forEach(v -> builder.addEdge(u, v));
-             });
-        return builder.build();
-    }
-
-    /**
-     * Returns a new Graph after transitive reduction.  All edges in
-     * the given g takes precedence over this graph.
-     *
-     * @throw IllegalArgumentException g must be a subgraph this graph
-     */
-    public Graph<T> reduce(Graph<T> g) {
-        boolean subgraph = nodes.containsAll(g.nodes) && g.edges.keySet().stream()
-               .allMatch(u -> adjacentNodes(u).containsAll(g.adjacentNodes(u)));
-        if (!subgraph) {
-            throw new IllegalArgumentException("the given argument is not a subgraph of this graph");
-        }
-
-        Graph.Builder<T> builder = new Builder<>();
-        nodes.stream()
-             .forEach(u -> {
-                 builder.addNode(u);
-                 // filter the edge if there exists a path from u to v in the given g
-                 // or there exists another path from u to v in this graph
-                 edges.get(u).stream()
-                      .filter(v -> !g.pathExists(u, v) && !pathExists(u, v, false))
-                      .forEach(v -> builder.addEdge(u, v));
-             });
-
-        // add the overlapped edges from this graph and the given g
-        g.edges().keySet().stream()
-                 .forEach(u -> g.adjacentNodes(u).stream()
-                         .filter(v -> isAdjacent(u, v))
-                         .forEach(v -> builder.addEdge(u, v)));
-        return builder.build();
-    }
-
-    private boolean isAdjacent(T u, T v) {
-        return edges.containsKey(u) && edges.get(u).contains(v);
-    }
-
-    private boolean pathExists(T u, T v) {
-        return pathExists(u, v, true);
-    }
-
-    /**
-     * Returns true if there exists a path from u to v in this graph.
-     * If includeAdjacent is false, it returns true if there exists
-     * another path from u to v of distance > 1
-     */
-    private boolean pathExists(T u, T v, boolean includeAdjacent) {
-        if (!nodes.contains(u) || !nodes.contains(v)) {
-            return false;
-        }
-        if (includeAdjacent && isAdjacent(u, v)) {
-            return true;
-        }
-        Deque<T> stack = new LinkedList<>();
-        Set<T> visited = new HashSet<>();
-        stack.push(u);
-        while (!stack.isEmpty()) {
-            T node = stack.pop();
-            if (node.equals(v)) {
-                if (traceOn) {
-                    System.out.format("Edge %s -> %s removed%n", u, v);
-                }
-                return true;
-            }
-            if (!visited.contains(node)) {
-                visited.add(node);
-                edges.get(node).stream()
-                     .filter(e -> includeAdjacent || !node.equals(u) || !e.equals(v))
-                     .forEach(e -> stack.push(e));
-            }
-        }
-        assert !visited.contains(v);
-        return false;
-    }
-
-    void printGraph(PrintStream out) {
-        nodes.stream()
-             .forEach(u -> adjacentNodes(u).stream()
-                     .forEach(v -> out.format("%s -> %s%n", u, v)));
-    }
-
-    public static class Builder<T> {
-        final Set<T> nodes = new HashSet<>();
-        final Map<T, Set<T>> edges = new HashMap<>();
-        public void addNode(T node) {
-            if (nodes.contains(node)) {
-                return;
-            }
-            nodes.add(node);
-            edges.computeIfAbsent(node, _e -> new HashSet<>());
-        }
-        public void addEdge(T u, T v) {
-            addNode(u);
-            addNode(v);
-            edges.get(u).add(v);
-        }
-        public Graph<T> build() {
-            return new Graph<>(nodes, edges);
-        }
-    }
-}
--- a/jdk/make/src/classes/build/tools/jigsaw/ModuleSummary.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/make/src/classes/build/tools/jigsaw/ModuleSummary.java	Thu Mar 16 20:47:03 2017 +0000
@@ -291,9 +291,9 @@
 
     static Configuration resolve(Set<String> roots) {
         return Configuration.empty()
-            .resolveRequires(ModuleFinder.ofSystem(),
-                             ModuleFinder.of(),
-                             roots);
+            .resolve(ModuleFinder.ofSystem(),
+                     ModuleFinder.of(),
+                     roots);
     }
 
     static class HtmlDocument {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/aix/classes/sun/nio/ch/DefaultAsynchronousChannelProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.nio.ch;
+
+import java.nio.channels.spi.AsynchronousChannelProvider;
+
+/**
+ * Creates this platform's default AsynchronousChannelProvider
+ */
+
+public class DefaultAsynchronousChannelProvider {
+
+    /**
+     * Prevent instantiation.
+     */
+    private DefaultAsynchronousChannelProvider() { }
+
+    /**
+     * Returns the default AsynchronousChannelProvider.
+     */
+    public static AsynchronousChannelProvider create() {
+        return new AixAsynchronousChannelProvider();
+    }
+}
--- a/jdk/src/java.base/aix/classes/sun/nio/ch/DefaultSelectorProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/aix/classes/sun/nio/ch/DefaultSelectorProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -42,7 +42,6 @@
      * Returns the default SelectorProvider.
      */
     public static SelectorProvider create() {
-        return new sun.nio.ch.PollSelectorProvider();
+        return new PollSelectorProvider();
     }
-
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/linux/classes/sun/nio/ch/DefaultAsynchronousChannelProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.nio.ch;
+
+import java.nio.channels.spi.AsynchronousChannelProvider;
+
+/**
+ * Creates this platform's default AsynchronousChannelProvider
+ */
+
+public class DefaultAsynchronousChannelProvider {
+
+    /**
+     * Prevent instantiation.
+     */
+    private DefaultAsynchronousChannelProvider() { }
+
+    /**
+     * Returns the default AsynchronousChannelProvider.
+     */
+    public static AsynchronousChannelProvider create() {
+        return new LinuxAsynchronousChannelProvider();
+    }
+}
--- a/jdk/src/java.base/linux/classes/sun/nio/ch/DefaultSelectorProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/linux/classes/sun/nio/ch/DefaultSelectorProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -42,7 +42,6 @@
      * Returns the default SelectorProvider.
      */
     public static SelectorProvider create() {
-        return new sun.nio.ch.EPollSelectorProvider();
+        return new EPollSelectorProvider();
     }
-
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/macosx/classes/sun/nio/ch/DefaultAsynchronousChannelProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.nio.ch;
+
+import java.nio.channels.spi.AsynchronousChannelProvider;
+
+/**
+ * Creates this platform's default AsynchronousChannelProvider
+ */
+
+public class DefaultAsynchronousChannelProvider {
+
+    /**
+     * Prevent instantiation.
+     */
+    private DefaultAsynchronousChannelProvider() { }
+
+    /**
+     * Returns the default AsynchronousChannelProvider.
+     */
+    public static AsynchronousChannelProvider create() {
+        return new BsdAsynchronousChannelProvider();
+    }
+}
--- a/jdk/src/java.base/macosx/classes/sun/nio/ch/DefaultSelectorProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/macosx/classes/sun/nio/ch/DefaultSelectorProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, 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
@@ -42,7 +42,6 @@
      * Returns the default SelectorProvider.
      */
     public static SelectorProvider create() {
-        return new sun.nio.ch.KQueueSelectorProvider();
+        return new KQueueSelectorProvider();
     }
-
 }
--- a/jdk/src/java.base/macosx/native/launcher/jexec.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,239 +0,0 @@
-/*
- * Copyright (c) 1999, 2012, 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.
- */
-
-/*
- * jexec for J2SE
- *
- * jexec is used by the system to allow execution of JAR files.
- *    Essentially jexec needs to run java and
- *    needs to be a native ISA executable (not a shell script), although
- *    this native ISA executable requirement was a mistake that will be fixed.
- *    (<ISA> is sparc or i386 or amd64).
- *
- *    When you execute a jar file, jexec is executed by the system as follows:
- *      /usr/java/jre/lib/<ISA>/jexec -jar JARFILENAME
- *    so this just needs to be turned into:
- *      /usr/java/jre/bin/java -jar JARFILENAME
- *
- * Solaris systems (new 7's and all 8's) will be looking for jexec at:
- *      /usr/java/jre/lib/<ISA>/jexec
- * Older systems may need to add this to their /etc/system file:
- *      set javaexec:jexec="/usr/java/jre/lib/<ISA>/jexec"
- *     and reboot the machine for this to work.
- *
- * This source should be compiled as:
- *      cc -o jexec jexec.c
- *
- * And jexec should be placed at the following location of the installation:
- *      <INSTALLATIONDIR>/jre/lib/<ISA>/jexec  (for Solaris)
- *      <INSTALLATIONDIR>/lib/jexec            (for Linux)
- *
- * NOTE: Unless <INSTALLATIONDIR> is the "default" JDK on the system
- *       (i.e. /usr/java -> <INSTALLATIONDIR>), this jexec will not be
- *       found.  The 1.2 java is only the default on Solaris 8 and
- *       on systems where the 1.2 packages were installed and no 1.1
- *       java was found.
- *
- * NOTE: You must use 1.2 jar to build your jar files. The system
- *       doesn't seem to pick up 1.1 jar files.
- *
- * NOTE: We don't need to set LD_LIBRARY_PATH here, even though we
- *       are running the actual java binary because the java binary will
- *       look for it's libraries through it's own runpath, which uses
- *       $ORIGIN.
- *
- * NOTE: This jexec should NOT have any special .so library needs because
- *       it appears that this executable will NOT get the $ORIGIN of jexec
- *       but the $ORIGIN of the jar file being executed. Be careful to keep
- *       this program simple and with no .so dependencies.
- */
-
-#include <stdlib.h>
-#include <stdio.h>
-#include <unistd.h>
-#include <string.h>
-#include <limits.h>
-#include <errno.h>
-
-static const int CRAZY_EXEC = ENOEXEC;
-static const int BAD_MAGIC  = ENOEXEC;
-
-static const char * BAD_EXEC_MSG     = "jexec failed";
-static const char * CRAZY_EXEC_MSG   = "missing args";
-static const char * MISSING_JAVA_MSG = "can't locate java";
-static const char * UNKNOWN_ERROR    = "unknown error";
-
-/* Define a constant that represents the number of directories to pop off the
- * current location to find the java binary */
-static const int RELATIVE_DEPTH = 3;
-
-/* path to java after popping */
-static const char * BIN_PATH = "/bin/java";
-
-/* flag used when running JAR files */
-static const char * JAR_FLAG = "-jar";
-
-int main(int argc, const char * argv[]);
-void errorExit(int error, const char * message);
-int getJavaPath(const char * path, char * buf, int depth);
-
-/*
- * This is the main entry point.  This program (jexec) will attempt to execute
- * a JAR file by finding the Java program (java), relative to its own location.
- * The exact location of the Java program depends on the platform, i.e.
- *
- *      <INSTALLATIONDIR>/jre/lib/<ISA>/jexec  (for Solaris)
- *      <INSTALLATIONDIR>/lib/jexec            (for Linux JDK)
- *
- * Once the Java program is found, this program copies any remaining arguments
- * into another array, which is then used to exec the Java program.
- *
- * On Linux this program does some additional steps.  When copying the array of
- * args, it is necessary to insert the "-jar" flag between arg[0], the program
- * name, and the original arg[1], which is presumed to be a path to a JAR file.
- * It is also necessary to verify that the original arg[1] really is a JAR file.
- * (These steps are unnecessary on Solaris because they are taken care of by
- * the kernel.)
- */
-int main(int argc, const char * argv[]) {
-    /* We need to exec the original arguments using java, instead of jexec.
-     * Also, for Linux, it is necessary to add the "-jar" argument between
-     * the new arg[0], and the old arg[1].  To do this we will create a new
-     * args array. */
-    char          java[PATH_MAX + 1];    /* path to java binary  */
-    const char ** nargv = NULL;          /* new args array       */
-    int           nargc = 0;             /* new args array count */
-    int           argi  = 0;             /* index into old array */
-
-    /* Make sure we have something to work with */
-    if ((argc < 1) || (argv == NULL)) {
-        /* Shouldn't happen... */
-        errorExit(CRAZY_EXEC, CRAZY_EXEC_MSG);
-    }
-
-    /* Get the path to the java binary, which is in a known position relative
-     * to our current position, which is in argv[0]. */
-    if (getJavaPath(argv[argi++], java, RELATIVE_DEPTH) != 0) {
-        errorExit(errno, MISSING_JAVA_MSG);
-    }
-
-    nargv = (const char **) malloc((argc + 2) * (sizeof (const char *)));
-    nargv[nargc++] = java;
-
-    if (argc >= 2) {
-        const char * jarfile = argv[argi++];
-        const char * message = NULL;
-
-        /* the next argument is the path to the JAR file */
-        nargv[nargc++] = jarfile;
-    }
-
-    /* finally copy any remaining arguments */
-    while (argi < argc) {
-        nargv[nargc++] = argv[argi++];
-    }
-
-    /* finally add one last terminating null */
-    nargv[nargc++] = NULL;
-
-    /* It's time to exec the java binary with the new arguments.  It
-     * is possible that we've reached this point without actually
-     * having a JAR file argument (i.e. if argc < 2), but we still
-     * want to exec the java binary, since that will take care of
-     * displaying the correct usage. */
-    execv(java, (char * const *) nargv);
-
-    /* If the exec worked, this process would have been replaced
-     * by the new process.  So any code reached beyond this point
-     * implies an error in the exec. */
-    free(nargv);
-    errorExit(errno, BAD_EXEC_MSG);
-    return 0; // keep the compiler happy
-}
-
-
-/*
- * Exit the application by setting errno, and writing a message.
- *
- * Parameters:
- *     error   - errno is set to this value, and it is used to exit.
- *     message - the message to write.
- */
-void errorExit(int error, const char * message) {
-    if (error != 0) {
-        errno = error;
-        perror((message != NULL) ? message : UNKNOWN_ERROR);
-    }
-
-    exit((error == 0) ? 0 : 1);
-}
-
-
-/*
- * Get the path to the java binary that should be relative to the current path.
- *
- * Parameters:
- *     path  - the input path that the java binary that should be relative to.
- *     buf   - a buffer of size PATH_MAX or greater that the java path is
- *             copied to.
- *     depth - the number of names to trim off the current path, including the
- *             name of this program.
- *
- * Returns:
- *     This function returns 0 on success; otherwise it returns the value of
- *     errno.
- */
-int getJavaPath(const char * path, char * buf, int depth) {
-    int result = 0;
-
-    /* Get the full path to this program.  Depending on whether this is Solaris
-     * or Linux, this will be something like,
-     *
-     *     <FOO>/jre/lib/<ISA>/jexec  (for Solaris)
-     *     <FOO>/lib/jexec            (for Linux)
-     */
-    if (realpath(path, buf) != NULL) {
-        int count = 0;
-
-        /* Pop off the filename, and then subdirectories for each level of
-         * depth */
-        for (count = 0; count < depth; count++) {
-            *(strrchr(buf, '/')) = '\0';
-        }
-
-        /* Append the relative location of java, creating something like,
-         *
-         *     <FOO>/jre/bin/java  (for Solaris)
-         *     <FOO>/bin/java      (for Linux)
-         */
-        strcat(buf, BIN_PATH);
-    }
-    else {
-        /* Failed to get the path */
-        result = errno;
-    }
-
-    return (result);
-}
--- a/jdk/src/java.base/macosx/native/libjava/java_props_macosx.c	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/macosx/native/libjava/java_props_macosx.c	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2017, 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
@@ -80,23 +80,31 @@
             // "en-GB"      (language with alpha-2 region designator)
             // "es-419"     (language with 3-digit UN M.49 area code)
             // "zh-Hans"    (language with ISO 15924 script designator)
+            // "zh-Hans-US"  (language with ISO 15924 script designator and region)
+            // "zh-Hans-419" (language with ISO 15924 script designator and UN M.49)
             //
-            // In the case of region designators (alpha-2 or UN M.49), we convert
+            // In the case of region designators (alpha-2 and/or UN M.49), we convert
             // to our locale string format by changing '-' to '_'.  That is, if
             // the '-' is followed by fewer than 4 chars.
             char* scriptOrRegion = strchr(languageString, '-');
-            if (scriptOrRegion != NULL && strlen(scriptOrRegion) < 5) {
-                *scriptOrRegion = '_';
+            if (scriptOrRegion != NULL) {
+                int length = strlen(scriptOrRegion);
+                if (length > 5) {
+                    // Region and script both exist. Honor the script for now
+                    scriptOrRegion[5] = '\0';
+                } else if (length < 5) {
+                    *scriptOrRegion = '_';
 
-                assert((strlen(scriptOrRegion) == 3 &&
+                    assert((length == 3 &&
                         // '-' followed by a 2 character region designator
                           isalpha(scriptOrRegion[1]) &&
                           isalpha(scriptOrRegion[2])) ||
-                       (strlen(scriptOrRegion) == 4 &&
+                           (length == 4 &&
                         // '-' followed by a 3-digit UN M.49 area code
                           isdigit(scriptOrRegion[1]) &&
                           isdigit(scriptOrRegion[2]) &&
                           isdigit(scriptOrRegion[3])));
+                }
             }
             const char* retVal = languageString;
 
--- a/jdk/src/java.base/share/classes/java/io/FilterInputStream.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/io/FilterInputStream.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2017, 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
@@ -84,7 +84,7 @@
     }
 
     /**
-     * Reads up to <code>byte.length</code> bytes of data from this
+     * Reads up to <code>b.length</code> bytes of data from this
      * input stream into an array of bytes. This method blocks until some
      * input is available.
      * <p>
--- a/jdk/src/java.base/share/classes/java/io/FilterOutputStream.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/io/FilterOutputStream.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1994, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1994, 2017, 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
@@ -91,8 +91,8 @@
      * <code>b.length</code>.
      * <p>
      * Note that this method does not call the one-argument
-     * <code>write</code> method of its underlying stream with the single
-     * argument <code>b</code>.
+     * <code>write</code> method of its underlying output stream with
+     * the single argument <code>b</code>.
      *
      * @param      b   the data to be written.
      * @exception  IOException  if an I/O error occurs.
@@ -113,7 +113,7 @@
      * <code>byte</code> to output.
      * <p>
      * Note that this method does not call the <code>write</code> method
-     * of its underlying input stream with the same arguments. Subclasses
+     * of its underlying output stream with the same arguments. Subclasses
      * of <code>FilterOutputStream</code> should provide a more efficient
      * implementation of this method.
      *
--- a/jdk/src/java.base/share/classes/java/lang/Class.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/Class.java	Thu Mar 16 20:47:03 2017 +0000
@@ -425,6 +425,7 @@
      *         </ul>
      *
      * @since 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static Class<?> forName(Module module, String name) {
@@ -819,6 +820,7 @@
      * @return the module that this class or interface is a member of
      *
      * @since 9
+     * @spec JPMS
      */
     public Module getModule() {
         return module;
@@ -924,6 +926,8 @@
      * this method returns {@code null}.
      *
      * @return the package of this class.
+     * @revised 9
+     * @spec JPMS
      */
     public Package getPackage() {
         if (isPrimitive() || isArray()) {
@@ -951,20 +955,30 @@
      * declaring class} of the {@link #getEnclosingMethod enclosing method} or
      * {@link #getEnclosingConstructor enclosing constructor}.
      *
-     * <p> This method returns {@code null} if this class represents an array type,
-     * a primitive type or void.
+     * <p> If this class represents an array type then this method returns the
+     * package name of the element type. If this class represents a primitive
+     * type or void then the package name "{@code java.lang}" is returned.
      *
      * @return the fully qualified package name
      *
      * @since 9
+     * @spec JPMS
      * @jls 6.7  Fully Qualified Names
      */
     public String getPackageName() {
         String pn = this.packageName;
-        if (pn == null && !isArray() && !isPrimitive()) {
-            String cn = getName();
-            int dot = cn.lastIndexOf('.');
-            pn = (dot != -1) ? cn.substring(0, dot).intern() : "";
+        if (pn == null) {
+            Class<?> c = this;
+            while (c.isArray()) {
+                c = c.getComponentType();
+            }
+            if (c.isPrimitive()) {
+                pn = "java.lang";
+            } else {
+                String cn = c.getName();
+                int dot = cn.lastIndexOf('.');
+                pn = (dot != -1) ? cn.substring(0, dot).intern() : "";
+            }
             this.packageName = pn;
         }
         return pn;
@@ -2491,10 +2505,16 @@
      * Finds a resource with a given name.
      *
      * <p> If this class is in a named {@link Module Module} then this method
-     * will attempt to find the resource in the module by means of the absolute
-     * resource name, subject to the rules for encapsulation specified in the
-     * {@code Module} {@link Module#getResourceAsStream getResourceAsStream}
-     * method.
+     * will attempt to find the resource in the module. This is done by
+     * delegating to the module's class loader {@link
+     * ClassLoader#findResource(String,String) findResource(String,String)}
+     * method, invoking it with the module name and the absolute name of the
+     * resource. Resources in named modules are subject to the rules for
+     * encapsulation specified in the {@code Module} {@link
+     * Module#getResourceAsStream getResourceAsStream} method and so this
+     * method returns {@code null} when the resource is a
+     * non-"{@code .class}" resource in a package that is not open to the
+     * caller's module.
      *
      * <p> Otherwise, if this class is not in a named module then the rules for
      * searching resources associated with a given class are implemented by the
@@ -2503,9 +2523,8 @@
      * the bootstrap class loader, the method delegates to {@link
      * ClassLoader#getSystemResourceAsStream}.
      *
-     * <p> Before finding a resource in the caller's module or delegation to a
-     * class loader, an absolute resource name is constructed from the given
-     * resource name using this algorithm:
+     * <p> Before delegation, an absolute resource name is constructed from the
+     * given resource name using this algorithm:
      *
      * <ul>
      *
@@ -2532,7 +2551,11 @@
      *          least the caller module, or access to the resource is denied
      *          by the security manager.
      * @throws  NullPointerException If {@code name} is {@code null}
+     *
+     * @see Module#getResourceAsStream(String)
      * @since  1.1
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public InputStream getResourceAsStream(String name) {
@@ -2585,10 +2608,16 @@
      * Finds a resource with a given name.
      *
      * <p> If this class is in a named {@link Module Module} then this method
-     * will attempt to find the resource in the module by means of the absolute
-     * resource name, subject to the rules for encapsulation specified in the
-     * {@code Module} {@link Module#getResourceAsStream getResourceAsStream}
-     * method.
+     * will attempt to find the resource in the module. This is done by
+     * delegating to the module's class loader {@link
+     * ClassLoader#findResource(String,String) findResource(String,String)}
+     * method, invoking it with the module name and the absolute name of the
+     * resource. Resources in named modules are subject to the rules for
+     * encapsulation specified in the {@code Module} {@link
+     * Module#getResourceAsStream getResourceAsStream} method and so this
+     * method returns {@code null} when the resource is a
+     * non-"{@code .class}" resource in a package that is not open to the
+     * caller's module.
      *
      * <p> Otherwise, if this class is not in a named module then the rules for
      * searching resources associated with a given class are implemented by the
@@ -2627,6 +2656,8 @@
      *         manager.
      * @throws NullPointerException If {@code name} is {@code null}
      * @since  1.1
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public URL getResource(String name) {
--- a/jdk/src/java.base/share/classes/java/lang/ClassLoader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/ClassLoader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -207,6 +207,8 @@
  * @jls 13.1 The Form of a Binary
  * @see      #resolveClass(Class)
  * @since 1.0
+ * @revised 9
+ * @spec JPMS
  */
 public abstract class ClassLoader {
 
@@ -380,12 +382,12 @@
      *         method doesn't allow creation of a new class loader.
      *
      * @since  9
+     * @spec JPMS
      */
     protected ClassLoader(String name, ClassLoader parent) {
         this(checkCreateClassLoader(name), name, parent);
     }
 
-
     /**
      * Creates a new class loader using the specified parent class loader for
      * delegation.
@@ -440,6 +442,7 @@
      * this class loader is not named.
      *
      * @since 9
+     * @spec JPMS
      */
     public String getName() {
         return name;
@@ -710,6 +713,7 @@
      *         if the class could not be found.
      *
      * @since 9
+     * @spec JPMS
      */
     protected Class<?> findClass(String moduleName, String name) {
         if (moduleName == null) {
@@ -834,6 +838,8 @@
      * @see  java.security.SecureClassLoader
      *
      * @since  1.1
+     * @revised 9
+     * @spec JPMS
      */
     protected final Class<?> defineClass(String name, byte[] b, int off, int len)
         throws ClassFormatError
@@ -967,6 +973,9 @@
      *          certificates than this class, or if {@code name} begins with
      *          "{@code java.}" and this class loader is not the platform
      *          class loader or its ancestor.
+     *
+     * @revised 9
+     * @spec JPMS
      */
     protected final Class<?> defineClass(String name, byte[] b, int off, int len,
                                          ProtectionDomain protectionDomain)
@@ -1041,6 +1050,8 @@
      * @see      #defineClass(String, byte[], int, int, ProtectionDomain)
      *
      * @since  1.5
+     * @revised 9
+     * @spec JPMS
      */
     protected final Class<?> defineClass(String name, java.nio.ByteBuffer b,
                                          ProtectionDomain protectionDomain)
@@ -1264,11 +1275,11 @@
      * Class loader implementations that support the loading from modules
      * should override this method.
      *
-     * @apiNote This method is the basis for the {@code Class} {@link
-     * Class#getResource getResource} and {@link Class#getResourceAsStream
-     * getResourceAsStream} methods. It is not subject to the rules for
-     * encapsulation specified by {@code Module} {@link
-     * Module#getResourceAsStream getResourceAsStream}.
+     * @apiNote This method is the basis for the {@link
+     * Class#getResource Class.getResource}, {@link Class#getResourceAsStream
+     * Class.getResourceAsStream}, and {@link Module#getResourceAsStream
+     * Module.getResourceAsStream} methods. It is not subject to the rules for
+     * encapsulation specified by {@code Module.getResourceAsStream}.
      *
      * @implSpec The default implementation attempts to find the resource by
      * invoking {@link #findResource(String)} when the {@code moduleName} is
@@ -1292,6 +1303,7 @@
      *
      * @see java.lang.module.ModuleReader#find(String)
      * @since 9
+     * @spec JPMS
      */
     protected URL findResource(String moduleName, String name) throws IOException {
         if (moduleName == null) {
@@ -1342,6 +1354,8 @@
      * @throws  NullPointerException If {@code name} is {@code null}
      *
      * @since  1.1
+     * @revised 9
+     * @spec JPMS
      */
     public URL getResource(String name) {
         Objects.requireNonNull(name);
@@ -1403,6 +1417,8 @@
      * @see  #findResources(String)
      *
      * @since  1.2
+     * @revised 9
+     * @spec JPMS
      */
     public Enumeration<URL> getResources(String name) throws IOException {
         Objects.requireNonNull(name);
@@ -1499,6 +1515,8 @@
      *          denied by the security manager.
      *
      * @since  1.2
+     * @revised 9
+     * @spec JPMS
      */
     protected URL findResource(String name) {
         return null;
@@ -1531,6 +1549,8 @@
      *          If I/O errors occur
      *
      * @since  1.2
+     * @revised 9
+     * @spec JPMS
      */
     protected Enumeration<URL> findResources(String name) throws IOException {
         return Collections.emptyEnumeration();
@@ -1601,6 +1621,8 @@
      *          denied by the security manager.
      *
      * @since  1.1
+     * @revised 9
+     * @spec JPMS
      */
     public static URL getSystemResource(String name) {
         return getSystemClassLoader().getResource(name);
@@ -1636,6 +1658,8 @@
      *          If I/O errors occur
      *
      * @since  1.2
+     * @revised 9
+     * @spec JPMS
      */
     public static Enumeration<URL> getSystemResources(String name)
         throws IOException
@@ -1667,6 +1691,8 @@
      * @throws  NullPointerException If {@code name} is {@code null}
      *
      * @since  1.1
+     * @revised 9
+     * @spec JPMS
      */
     public InputStream getResourceAsStream(String name) {
         Objects.requireNonNull(name);
@@ -1699,6 +1725,8 @@
      *          denied by the security manager.
      *
      * @since  1.1
+     * @revised 9
+     * @spec JPMS
      */
     public static InputStream getSystemResourceAsStream(String name) {
         URL url = getSystemResource(name);
@@ -1749,6 +1777,7 @@
      *
      * @see Module#isNamed()
      * @since 9
+     * @spec JPMS
      */
     public final Module getUnnamedModule() {
         return unnamedModule;
@@ -1772,6 +1801,7 @@
      *          {@link RuntimePermission}{@code ("getClassLoader")}
      *
      * @since 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static ClassLoader getPlatformClassLoader() {
@@ -1847,6 +1877,8 @@
      *          {@link Throwable#getCause()} method.
      *
      * @revised  1.4
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static ClassLoader getSystemClassLoader() {
@@ -2101,6 +2133,8 @@
      *          defined by this class loader
      *
      * @since  1.2
+     * @revised 9
+     * @spec JPMS
      *
      * @see <a href="../../../technotes/guides/jar/jar.html#versioning">
      *      The JAR File Specification: Package Versioning</a>
@@ -2138,6 +2172,7 @@
      *          if {@code name} is {@code null}.
      *
      * @since  9
+     * @spec JPMS
      */
     public final Package getDefinedPackage(String name) {
         Objects.requireNonNull(name, "name cannot be null");
@@ -2160,6 +2195,7 @@
      *         or an zero length array if no package has been defined by this class loader.
      *
      * @since  9
+     * @spec JPMS
      */
     public final Package[] getDefinedPackages() {
         return packages().toArray(Package[]::new);
@@ -2196,6 +2232,8 @@
      * a {@code Package} for the specified class loader.
      *
      * @since  1.2
+     * @revised 9
+     * @spec JPMS
      */
     @Deprecated(since="9")
     protected Package getPackage(String name) {
@@ -2220,6 +2258,8 @@
      *          class loader and its ancestors
      *
      * @since  1.2
+     * @revised 9
+     * @spec JPMS
      */
     protected Package[] getPackages() {
         Stream<Package> pkgs = packages();
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/IllegalCallerException.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,76 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package java.lang;
+
+/**
+ * Thrown to indicate that a method has been called by an inappropriate caller.
+ *
+ * @since 9
+ * @spec JPMS
+ * @see StackWalker#getCallerClass
+ */
+public class IllegalCallerException extends RuntimeException {
+    /**
+     * Constructs an IllegalCallerException with no detail message.
+     */
+    public IllegalCallerException() {
+        super();
+    }
+
+    /**
+     * Constructs an IllegalCallerException with the specified detail
+     * message.
+     *
+     * @param s the String that contains a detailed message (can be null)
+     */
+    public IllegalCallerException(String s) {
+        super(s);
+    }
+
+    /**
+     * Constructs a new exception with the specified detail message and
+     * cause.
+     *
+     * @param  message the detail message (can be null)
+     * @param  cause the cause (can be null)
+     */
+    public IllegalCallerException(String message, Throwable cause) {
+        super(message, cause);
+    }
+
+    /**
+     * Constructs a new exception with the specified cause and a detail
+     * message of {@code (cause==null ? null : cause.toString())} (which
+     * typically contains the class and detail message of {@code cause}).
+     *
+     * @param  cause the cause (can be null)
+     */
+    public IllegalCallerException(Throwable cause) {
+        super(cause);
+    }
+
+    static final long serialVersionUID = -2349421918363102232L;
+}
--- a/jdk/src/java.base/share/classes/java/lang/LiveStackFrame.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/LiveStackFrame.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -55,14 +55,36 @@
      *
      * <p>A single local variable can hold a value of type boolean, byte, char,
      * short, int, float, reference or returnAddress.  A pair of local variables
-     * can hold a value of type long or double.  In other words,
-     * a value of type long or type double occupies two consecutive local
-     * variables.  For a value of primitive type, the element in the
-     * local variable array is an {@link PrimitiveValue} object;
-     * otherwise, the element is an {@code Object}.
+     * can hold a value of type long or double (JVMS section 2.6.1).  Primitive
+     * locals are represented in the returned array as {@code PrimitiveSlot}s,
+     * with longs and doubles occupying a pair of consecutive
+     * {@code PrimitiveSlot}s.
+     *
+     * <p>The current VM implementation does not provide specific type
+     * information for primitive locals.  This method simply returns the raw
+     * contents of the VM's primitive locals on a best-effort basis, without
+     * indicating a specific type.
+     *
+     * <p>The returned array may contain null entries for local variables that
+     * are not live.
      *
-     * <p>The returned array may contain null entries if a local variable is not
-     * live.
+     * @implNote
+     * <p> The specific subclass of {@code PrimitiveSlot} will reflect the
+     * underlying architecture, and will be either {@code PrimitiveSlot32} or
+     * {@code PrimitiveSlot64}.
+     *
+     * <p>How a long or double value is stored in the pair of
+     * {@code PrimitiveSlot}s can vary based on the underlying architecture and
+     * VM implementation.  On 32-bit architectures, long/double values are split
+     * between the two {@code PrimitiveSlot32}s.
+     * On 64-bit architectures, the entire value may be stored in one of the
+     * {@code PrimitiveSlot64}s, with the other {@code PrimitiveSlot64} being
+     * unused.
+     *
+     * <p>The contents of the unused, high-order portion of a
+     * {@code PrimitiveSlot64} (when storing a primitive other than a long or
+     * double) is unspecified.  In particular, the unused bits are not
+     * necessarily zeroed out.
      *
      * @return  the local variable array of this stack frame.
      */
@@ -78,7 +100,7 @@
      * <p>Each entry on the operand stack can hold a value of any Java Virtual
      * Machine Type.
      * For a value of primitive type, the element in the returned array is
-     * an {@link PrimitiveValue} object; otherwise, the element is the {@code Object}
+     * a {@link PrimitiveSlot} object; otherwise, the element is the {@code Object}
      * on the operand stack.
      *
      * @return the operand stack of this stack frame.
@@ -87,107 +109,37 @@
 
     /**
      * <em>UNSUPPORTED</em> This interface is intended to be package-private
-     * or move to an internal package.<p>
+     * or moved to an internal package.<p>
      *
-     * Represents a local variable or an entry on the operand whose value is
+     * Represents a local variable or an entry on the operand stack whose value is
      * of primitive type.
      */
-    public abstract class PrimitiveValue {
+    public abstract class PrimitiveSlot {
         /**
-         * Returns the base type of this primitive value, one of
-         * {@code B, D, C, F, I, J, S, Z}.
-         *
-         * @return Name of a base type
-         * @jvms table 4.3-A
+         * Returns the size, in bytes, of the slot.
          */
-        abstract char type();
+        public abstract int size();
 
         /**
-         * Returns the boolean value if this primitive value is of type boolean.
-         * @return the boolean value if this primitive value is of type boolean.
+         * Returns the int value if this primitive value is of size 4
+         * @return the int value if this primitive value is of size 4
          *
          * @throws UnsupportedOperationException if this primitive value is not
-         * of type boolean.
-         */
-        public boolean booleanValue() {
-            throw new UnsupportedOperationException("this primitive of type " + type());
-        }
-
-        /**
-         * Returns the int value if this primitive value is of type int.
-         * @return the int value if this primitive value is of type int.
-         *
-         * @throws UnsupportedOperationException if this primitive value is not
-         * of type int.
+         * of size 4.
          */
         public int intValue() {
-            throw new UnsupportedOperationException("this primitive of type " + type());
-        }
-
-        /**
-         * Returns the long value if this primitive value is of type long.
-         * @return the long value if this primitive value is of type long.
-         *
-         * @throws UnsupportedOperationException if this primitive value is not
-         * of type long.
-         */
-        public long longValue() {
-            throw new UnsupportedOperationException("this primitive of type " + type());
+            throw new UnsupportedOperationException("this " + size() + "-byte primitive");
         }
 
         /**
-         * Returns the char value if this primitive value is of type char.
-         * @return the char value if this primitive value is of type char.
-         *
-         * @throws UnsupportedOperationException if this primitive value is not
-         * of type char.
-         */
-        public char charValue() {
-            throw new UnsupportedOperationException("this primitive of type " + type());
-        }
-
-        /**
-         * Returns the byte value if this primitive value is of type byte.
-         * @return the byte value if this primitive value is of type byte.
-         *
-         * @throws UnsupportedOperationException if this primitive value is not
-         * of type byte.
-         */
-        public byte byteValue() {
-            throw new UnsupportedOperationException("this primitive of type " + type());
-        }
-
-        /**
-         * Returns the short value if this primitive value is of type short.
-         * @return the short value if this primitive value is of type short.
+         * Returns the long value if this primitive value is of size 8
+         * @return the long value if this primitive value is of size 8
          *
          * @throws UnsupportedOperationException if this primitive value is not
-         * of type short.
-         */
-        public short shortValue() {
-            throw new UnsupportedOperationException("this primitive of type " + type());
-        }
-
-        /**
-         * Returns the float value if this primitive value is of type float.
-         * @return the float value if this primitive value is of type float.
-         *
-         * @throws UnsupportedOperationException if this primitive value is not
-         * of type float.
+         * of size 8.
          */
-        public float floatValue() {
-            throw new UnsupportedOperationException("this primitive of type " + type());
-        }
-
-        /**
-         * Returns the double value if this primitive value is of type double.
-         * @return the double value if this primitive value is of type double.
-         *
-         * @throws UnsupportedOperationException if this primitive value is not
-         * of type double.
-         */
-        public double doubleValue() {
-            throw new UnsupportedOperationException("this primitive of type " + type());
+        public long longValue() {
+            throw new UnsupportedOperationException("this " + size() + "-byte primitive");
         }
     }
 
--- a/jdk/src/java.base/share/classes/java/lang/LiveStackFrameInfo.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/LiveStackFrameInfo.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -24,15 +24,13 @@
  */
 package java.lang;
 
-import java.lang.StackWalker.Option;
-import java.util.EnumSet;
-import java.util.Set;
-
-import static java.lang.StackWalker.ExtendedOption.*;
-
 final class LiveStackFrameInfo extends StackFrameInfo implements LiveStackFrame {
     private static Object[] EMPTY_ARRAY = new Object[0];
 
+    // These flags must match the values maintained in the VM
+    private static final int MODE_INTERPRETED = 0x01;
+    private static final int MODE_COMPILED    = 0x02;
+
     LiveStackFrameInfo(StackWalker walker) {
         super(walker);
     }
@@ -41,6 +39,7 @@
     private Object[] monitors = EMPTY_ARRAY;
     private Object[] locals = EMPTY_ARRAY;
     private Object[] operands = EMPTY_ARRAY;
+    private int mode = 0;
 
     @Override
     public Object[] getMonitors() {
@@ -57,51 +56,44 @@
         return operands;
     }
 
-    /*
-     * Convert primitive value to {@code Primitive} object to represent
-     * a local variable or an element on the operand stack of primitive type.
-     */
-    static PrimitiveValue asPrimitive(boolean value) {
-        return new BooleanPrimitive(value);
-    }
-
-    static PrimitiveValue asPrimitive(int value) {
-        return new IntPrimitive(value);
-    }
-
-    static PrimitiveValue asPrimitive(short value) {
-        return new ShortPrimitive(value);
-    }
-
-    static PrimitiveValue asPrimitive(char value) {
-        return new CharPrimitive(value);
+    @Override
+    public String toString() {
+        StringBuilder retVal = new StringBuilder(super.toString());
+        if (mode != 0) {
+            retVal.append("(");
+            if ((mode & MODE_INTERPRETED) == MODE_INTERPRETED) {
+                retVal.append(" interpreted ");
+            }
+            if ((mode & MODE_COMPILED) == MODE_COMPILED) {
+                retVal.append(" compiled ");
+            }
+            retVal.append(")");
+        }
+        return retVal.toString();
     }
 
-    static PrimitiveValue asPrimitive(byte value) {
-        return new BytePrimitive(value);
-    }
+    /*
+     * Convert primitive value to {@code PrimitiveSlot} object to represent
+     * a local variable or an element on the operand stack of primitive type.
+     */
 
-    static PrimitiveValue asPrimitive(long value) {
-        return new LongPrimitive(value);
+    static PrimitiveSlot asPrimitive(int value) {
+        return new PrimitiveSlot32(value);
     }
 
-    static PrimitiveValue asPrimitive(float value) {
-        return new FloatPrimitive(value);
+    static PrimitiveSlot asPrimitive(long value) {
+        return new PrimitiveSlot64(value);
     }
 
-    static PrimitiveValue asPrimitive(double value) {
-        return new DoublePrimitive(value);
-    }
-
-    private static class IntPrimitive extends PrimitiveValue {
+    private static class PrimitiveSlot32 extends PrimitiveSlot {
         final int value;
-        IntPrimitive(int value) {
+        PrimitiveSlot32(int value) {
             this.value = value;
         }
 
         @Override
-        public char type() {
-            return 'I';
+        public int size() {
+            return 4;
         }
 
         @Override
@@ -115,103 +107,15 @@
         }
     }
 
-    private static class ShortPrimitive extends PrimitiveValue {
-        final short value;
-        ShortPrimitive(short value) {
-            this.value = value;
-        }
-
-        @Override
-        public char type() {
-            return 'S';
-        }
-
-        @Override
-        public short shortValue() {
-            return value;
-        }
-
-        @Override
-        public String toString() {
-            return String.valueOf(value);
-        }
-    }
-
-    private static class BooleanPrimitive extends PrimitiveValue {
-        final boolean value;
-        BooleanPrimitive(boolean value) {
+    private static class PrimitiveSlot64 extends PrimitiveSlot {
+        final long value;
+        PrimitiveSlot64(long value) {
             this.value = value;
         }
 
         @Override
-        public char type() {
-            return 'Z';
-        }
-
-        @Override
-        public boolean booleanValue()  {
-            return value;
-        }
-
-        @Override
-        public String toString() {
-            return String.valueOf(value);
-        }
-    }
-
-    private static class CharPrimitive extends PrimitiveValue {
-        final char value;
-        CharPrimitive(char value) {
-            this.value = value;
-        }
-
-        @Override
-        public char type() {
-            return 'C';
-        }
-
-        @Override
-        public char charValue() {
-            return value;
-        }
-
-        @Override
-        public String toString() {
-            return String.valueOf(value);
-        }
-    }
-
-    private static class BytePrimitive extends PrimitiveValue {
-        final byte value;
-        BytePrimitive(byte value) {
-            this.value = value;
-        }
-
-        @Override
-        public char type() {
-            return 'B';
-        }
-
-        @Override
-        public byte byteValue() {
-            return value;
-        }
-
-        @Override
-        public String toString() {
-            return String.valueOf(value);
-        }
-    }
-
-    private static class LongPrimitive extends PrimitiveValue {
-        final long value;
-        LongPrimitive(long value) {
-            this.value = value;
-        }
-
-        @Override
-        public char type() {
-            return 'J';
+        public int size() {
+            return 8;
         }
 
         @Override
@@ -224,48 +128,4 @@
             return String.valueOf(value);
         }
     }
-
-    private static class FloatPrimitive extends PrimitiveValue {
-        final float value;
-        FloatPrimitive(float value) {
-            this.value = value;
-        }
-
-        @Override
-        public char type() {
-            return 'F';
-        }
-
-        @Override
-        public float floatValue() {
-            return value;
-        }
-
-        @Override
-        public String toString() {
-            return String.valueOf(value);
-        }
-    }
-
-    private static class DoublePrimitive extends PrimitiveValue {
-        final double value;
-        DoublePrimitive(double value) {
-            this.value = value;
-        }
-
-        @Override
-        public char type() {
-            return 'D';
-        }
-
-        @Override
-        public double doubleValue() {
-            return value;
-        }
-
-        @Override
-        public String toString() {
-            return String.valueOf(value);
-        }
-    }
 }
--- a/jdk/src/java.base/share/classes/java/lang/Package.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/Package.java	Thu Mar 16 20:47:03 2017 +0000
@@ -111,6 +111,8 @@
  * @see ClassLoader#definePackage(String, String, String, String, String, String, String, URL)
  *
  * @since 1.2
+ * @revised 9
+ * @spec JPMS
  */
 public class Package extends NamedPackage implements java.lang.reflect.AnnotatedElement {
     /**
@@ -207,6 +209,9 @@
      * is returned if it is not known.
      * @return the vendor that implemented this package, {@code null}
      * is returned if it is not known.
+     *
+     * @revised 9
+     * @spec JPMS
      */
     public String getImplementationVendor() {
         return versionInfo.implVendor;
@@ -334,6 +339,9 @@
      * a {@code Package} for the specified class loader.
      *
      * @see ClassLoader#getDefinedPackage
+     *
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     @Deprecated(since="9")
@@ -356,6 +364,9 @@
      *          class loader and its ancestors
      *
      * @see ClassLoader#getDefinedPackages
+     *
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static Package[] getPackages() {
--- a/jdk/src/java.base/share/classes/java/lang/SecurityManager.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/SecurityManager.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1458,6 +1458,18 @@
     }
 
     /**
+     * Called by java.security.Security
+     */
+    static void invalidatePackageAccessCache() {
+        synchronized (packageAccessLock) {
+            packageAccessValid = false;
+        }
+        synchronized (packageDefinitionLock) {
+            packageDefinitionValid = false;
+        }
+    }
+
+    /**
      * Returns true if the module's loader is the boot or platform loader.
      */
     private static boolean isBootOrPlatformModule(Module m) {
--- a/jdk/src/java.base/share/classes/java/lang/StackStreamFactory.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/StackStreamFactory.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,11 +25,13 @@
 package java.lang;
 
 import jdk.internal.reflect.MethodAccessor;
+import jdk.internal.reflect.ConstructorAccessor;
 import java.lang.StackWalker.Option;
 import java.lang.StackWalker.StackFrame;
 
 import java.lang.annotation.Native;
 import java.lang.reflect.Method;
+import java.lang.reflect.Constructor;
 import java.util.HashSet;
 import java.util.NoSuchElementException;
 import java.util.Objects;
@@ -684,7 +686,7 @@
                 frames[n++] = caller;
             }
             if (frames[1] == null) {
-                throw new IllegalStateException("no caller frame");
+                throw new IllegalCallerException("no caller frame");
             }
             return n;
         }
@@ -922,7 +924,8 @@
          */
         final void setBatch(int depth, int startIndex, int endIndex) {
             if (startIndex <= 0 || endIndex <= 0)
-                throw new IllegalArgumentException("startIndex=" + startIndex + " endIndex=" + endIndex);
+                throw new IllegalArgumentException("startIndex=" + startIndex
+                        + " endIndex=" + endIndex);
 
             this.origin = startIndex;
             this.fence = endIndex;
@@ -980,13 +983,18 @@
 
     private static boolean isReflectionFrame(Class<?> c) {
         if (c.getName().startsWith("jdk.internal.reflect") &&
-                !MethodAccessor.class.isAssignableFrom(c)) {
-            throw new InternalError("Not jdk.internal.reflect.MethodAccessor: " + c.toString());
+                !MethodAccessor.class.isAssignableFrom(c) &&
+                !ConstructorAccessor.class.isAssignableFrom(c)) {
+            throw new InternalError("Not jdk.internal.reflect.MethodAccessor"
+                    + " or jdk.internal.reflect.ConstructorAccessor: "
+                    + c.toString());
         }
         // ## should filter all @Hidden frames?
         return c == Method.class ||
-                MethodAccessor.class.isAssignableFrom(c) ||
-                c.getName().startsWith("java.lang.invoke.LambdaForm");
+               c == Constructor.class ||
+               MethodAccessor.class.isAssignableFrom(c) ||
+               ConstructorAccessor.class.isAssignableFrom(c) ||
+               c.getName().startsWith("java.lang.invoke.LambdaForm");
     }
 
 }
--- a/jdk/src/java.base/share/classes/java/lang/StackTraceElement.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/StackTraceElement.java	Thu Mar 16 20:47:03 2017 +0000
@@ -92,6 +92,8 @@
      * @throws NullPointerException if {@code declaringClass} or
      *         {@code methodName} is null
      * @since 1.5
+     * @revised 9
+     * @spec JPMS
      */
     public StackTraceElement(String declaringClass, String methodName,
                              String fileName, int lineNumber) {
@@ -128,6 +130,7 @@
      *         or {@code methodName} is {@code null}
      *
      * @since 9
+     * @spec JPMS
      */
     public StackTraceElement(String classLoaderName,
                              String moduleName, String moduleVersion,
@@ -187,6 +190,7 @@
      *         point represented by this stack trace element; {@code null}
      *         if the module name is not available.
      * @since 9
+     * @spec JPMS
      * @see java.lang.reflect.Module#getName()
      */
     public String getModuleName() {
@@ -201,6 +205,7 @@
      *         point represented by this stack trace element; {@code null}
      *         if the module version is not available.
      * @since 9
+     * @spec JPMS
      * @see java.lang.module.ModuleDescriptor.Version
      */
     public String getModuleVersion() {
@@ -216,6 +221,7 @@
      *         if the class loader is not named.
      *
      * @since 9
+     * @spec JPMS
      * @see java.lang.ClassLoader#getName()
      */
     public String getClassLoaderName() {
@@ -329,6 +335,8 @@
      * {@link java.lang.StackWalker.StackFrame}, where an implementation may
      * choose to omit some element in the returned string.
      *
+     * @revised 9
+     * @spec JPMS
      * @see    Throwable#printStackTrace()
      */
     public String toString() {
@@ -376,6 +384,9 @@
      * @return true if the specified object is another
      *         {@code StackTraceElement} instance representing the same
      *         execution point as this instance.
+     *
+     * @revised 9
+     * @spec JPMS
      */
     public boolean equals(Object obj) {
         if (obj==this)
--- a/jdk/src/java.base/share/classes/java/lang/StackWalker.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/StackWalker.java	Thu Mar 16 20:47:03 2017 +0000
@@ -29,6 +29,7 @@
 import java.util.*;
 import java.util.function.Consumer;
 import java.util.function.Function;
+import java.util.function.Predicate;
 import java.util.stream.Stream;
 
 /**
@@ -207,13 +208,23 @@
         /**
          * Shows all reflection frames.
          *
-         * <p>By default, reflection frames are hidden.  This includes the
-         * {@link java.lang.reflect.Method#invoke} method
-         * and the reflection implementation classes. A {@code StackWalker} with
-         * this {@code SHOW_REFLECT_FRAMES} option will show all reflection frames.
-         * The {@link #SHOW_HIDDEN_FRAMES} option can also be used to show all
+         * <p>By default, reflection frames are hidden.  A {@code StackWalker}
+         * configured with this {@code SHOW_REFLECT_FRAMES} option
+         * will show all reflection frames that
+         * include {@link java.lang.reflect.Method#invoke} and
+         * {@link java.lang.reflect.Constructor#newInstance(Object...)}
+         * and their reflection implementation classes.
+         *
+         * <p>The {@link #SHOW_HIDDEN_FRAMES} option can also be used to show all
          * reflection frames and it will also show other hidden frames that
          * are implementation-specific.
+         *
+         * @apiNote
+         * This option includes the stack frames representing the invocation of
+         * {@code Method} and {@code Constructor}.  Any utility methods that
+         * are equivalent to calling {@code Method.invoke} or
+         * {@code Constructor.newInstance} such as {@code Class.newInstance}
+         * are not filtered or controlled by any stack walking option.
          */
         SHOW_REFLECT_FRAMES,
         /**
@@ -465,28 +476,31 @@
     }
 
     /**
-     * Gets the {@code Class} object of the caller invoking the method
-     * that calls this {@code getCallerClass} method.
+     * Gets the {@code Class} object of the caller who invoked the method
+     * that invoked {@code getCallerClass}.
      *
-     * <p> Reflection frames, {@link java.lang.invoke.MethodHandle}, and
-     * hidden frames are filtered regardless of the
+     * <p> This method filters {@linkplain Option#SHOW_REFLECT_FRAMES reflection
+     * frames}, {@link java.lang.invoke.MethodHandle}, and
+     * {@linkplain Option#SHOW_HIDDEN_FRAMES hidden frames} regardless of the
      * {@link Option#SHOW_REFLECT_FRAMES SHOW_REFLECT_FRAMES}
      * and {@link Option#SHOW_HIDDEN_FRAMES SHOW_HIDDEN_FRAMES} options
      * this {@code StackWalker} has been configured with.
      *
+     * <p> This method should be called when a caller frame is present.  If
+     * it is called from the bottom most frame on the stack,
+     * {@code IllegalCallerException} will be thrown.
+     *
      * <p> This method throws {@code UnsupportedOperationException}
      * if this {@code StackWalker} is not configured with the
      * {@link Option#RETAIN_CLASS_REFERENCE RETAIN_CLASS_REFERENCE} option.
-     * This method should be called when a caller frame is present.  If
-     * it is called from the last frame on the stack,
-     * {@code IllegalStateException} will be thrown.
      *
      * @apiNote
      * For example, {@code Util::getResourceBundle} loads a resource bundle
-     * on behalf of the caller.  It calls this {@code getCallerClass} method
-     * to find the method calling {@code Util::getResourceBundle} and uses the caller's
-     * class loader to load the resource bundle. The caller class in this example
-     * is the {@code MyTool} class.
+     * on behalf of the caller.  It invokes {@code getCallerClass} to identify
+     * the class whose method called {@code Util::getResourceBundle}.
+     * Then, it obtains the class loader of that class, and uses
+     * the class loader to load the resource bundle. The caller class
+     * in this example is {@code MyTool}.
      *
      * <pre>{@code
      * class Util {
@@ -517,17 +531,17 @@
      * }</pre>
      *
      * When the {@code getCallerClass} method is called from a method that
-     * is the last frame on the stack,
+     * is the bottom most frame on the stack,
      * for example, {@code static public void main} method launched by the
      * {@code java} launcher, or a method invoked from a JNI attached thread,
-     * {@code IllegalStateException} is thrown.
+     * {@code IllegalCallerException} is thrown.
      *
      * @return {@code Class} object of the caller's caller invoking this method.
      *
      * @throws UnsupportedOperationException if this {@code StackWalker}
      *         is not configured with {@link Option#RETAIN_CLASS_REFERENCE
      *         Option.RETAIN_CLASS_REFERENCE}.
-     * @throws IllegalStateException if there is no caller frame, i.e.
+     * @throws IllegalCallerException if there is no caller frame, i.e.
      *         when this {@code getCallerClass} method is called from a method
      *         which is the last frame on the stack.
      */
--- a/jdk/src/java.base/share/classes/java/lang/StringCoding.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/StringCoding.java	Thu Mar 16 20:47:03 2017 +0000
@@ -46,9 +46,6 @@
 import static java.lang.String.LATIN1;
 import static java.lang.String.UTF16;
 import static java.lang.String.COMPACT_STRINGS;
-import static java.nio.charset.StandardCharsets.ISO_8859_1;
-import static java.nio.charset.StandardCharsets.US_ASCII;
-import static java.nio.charset.StandardCharsets.UTF_8;
 
 /**
  * Utility class for string encoding and decoding.
@@ -64,6 +61,10 @@
     private static final ThreadLocal<SoftReference<StringEncoder>> encoder =
         new ThreadLocal<>();
 
+    private static final Charset ISO_8859_1 = Charset.forName("iso-8859-1");
+    private static final Charset US_ASCII = Charset.forName("us-ascii");
+    private static final Charset UTF_8 = Charset.forName("utf-8");
+
     private static boolean warnUnsupportedCharset = true;
 
     private static <T> T deref(ThreadLocal<SoftReference<T>> tl) {
--- a/jdk/src/java.base/share/classes/java/lang/System.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/System.java	Thu Mar 16 20:47:03 2017 +0000
@@ -534,6 +534,8 @@
      * @param x object for which the hashCode is to be calculated
      * @return  the hashCode
      * @since   1.1
+     * @see Object#hashCode
+     * @see java.util.Objects#hashCode(Object)
      */
     @HotSpotIntrinsicCandidate
     public static native int identityHashCode(Object x);
@@ -1942,10 +1944,6 @@
      * the application classpath or modulepath.
      */
     private static void initPhase3() {
-        // Initialize publicLookup early, to avoid bootstrapping circularities
-        // with security manager using java.lang.invoke infrastructure.
-        java.lang.invoke.MethodHandles.publicLookup();
-
         // set security manager
         String cn = System.getProperty("java.security.manager");
         if (cn != null) {
@@ -2053,6 +2051,9 @@
             public String fastUUID(long lsb, long msb) {
                 return Long.fastUUID(lsb, msb);
             }
+            public void invalidatePackageAccessCache() {
+                SecurityManager.invalidatePackageAccessCache();
+            }
         });
     }
 }
--- a/jdk/src/java.base/share/classes/java/lang/invoke/AbstractValidatingLambdaMetafactory.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/AbstractValidatingLambdaMetafactory.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,6 +26,7 @@
 
 import sun.invoke.util.Wrapper;
 
+import static java.lang.invoke.MethodHandleInfo.*;
 import static sun.invoke.util.Wrapper.forPrimitiveType;
 import static sun.invoke.util.Wrapper.forWrapperType;
 import static sun.invoke.util.Wrapper.isWrapperType;
@@ -56,11 +57,11 @@
     final String samMethodName;               // Name of the SAM method "foo"
     final MethodType samMethodType;           // Type of the SAM method "(Object)Object"
     final MethodHandle implMethod;            // Raw method handle for the implementation method
+    final MethodType implMethodType;          // Type of the implMethod MethodHandle "(CC,int)String"
     final MethodHandleInfo implInfo;          // Info about the implementation method handle "MethodHandleInfo[5 CC.impl(int)String]"
     final int implKind;                       // Invocation kind for implementation "5"=invokevirtual
     final boolean implIsInstanceMethod;       // Is the implementation an instance method "true"
-    final Class<?> implDefiningClass;         // Type defining the implementation "class CC"
-    final MethodType implMethodType;          // Type of the implementation method "(int)String"
+    final Class<?> implClass;                 // Class for referencing the implementation method "class CC"
     final MethodType instantiatedMethodType;  // Instantiated erased functional interface method type "(Integer)Object"
     final boolean isSerializable;             // Should the returned instance be serializable
     final Class<?>[] markerInterfaces;        // Additional marker interfaces to be implemented
@@ -128,19 +129,51 @@
         this.samMethodType  = samMethodType;
 
         this.implMethod = implMethod;
+        this.implMethodType = implMethod.type();
         this.implInfo = caller.revealDirect(implMethod);
-        this.implKind = implInfo.getReferenceKind();
-        this.implIsInstanceMethod =
-                implKind == MethodHandleInfo.REF_invokeVirtual ||
-                implKind == MethodHandleInfo.REF_invokeSpecial ||
-                implKind == MethodHandleInfo.REF_invokeInterface;
-        this.implDefiningClass = implInfo.getDeclaringClass();
-        this.implMethodType = implInfo.getMethodType();
+        switch (implInfo.getReferenceKind()) {
+            case REF_invokeVirtual:
+            case REF_invokeInterface:
+                this.implClass = implMethodType.parameterType(0);
+                // reference kind reported by implInfo may not match implMethodType's first param
+                // Example: implMethodType is (Cloneable)String, implInfo is for Object.toString
+                this.implKind = implClass.isInterface() ? REF_invokeInterface : REF_invokeVirtual;
+                this.implIsInstanceMethod = true;
+                break;
+            case REF_invokeSpecial:
+                // JDK-8172817: should use referenced class here, but we don't know what it was
+                this.implClass = implInfo.getDeclaringClass();
+                this.implKind = REF_invokeSpecial;
+                this.implIsInstanceMethod = true;
+                break;
+            case REF_invokeStatic:
+            case REF_newInvokeSpecial:
+                // JDK-8172817: should use referenced class here for invokestatic, but we don't know what it was
+                this.implClass = implInfo.getDeclaringClass();
+                this.implKind = implInfo.getReferenceKind();
+                this.implIsInstanceMethod = false;
+                break;
+            default:
+                throw new LambdaConversionException(String.format("Unsupported MethodHandle kind: %s", implInfo));
+        }
+
         this.instantiatedMethodType = instantiatedMethodType;
         this.isSerializable = isSerializable;
         this.markerInterfaces = markerInterfaces;
         this.additionalBridges = additionalBridges;
 
+        if (samMethodName.isEmpty() ||
+                samMethodName.indexOf('.') >= 0 ||
+                samMethodName.indexOf(';') >= 0 ||
+                samMethodName.indexOf('[') >= 0 ||
+                samMethodName.indexOf('/') >= 0 ||
+                samMethodName.indexOf('<') >= 0 ||
+                samMethodName.indexOf('>') >= 0) {
+            throw new LambdaConversionException(String.format(
+                    "Method name '%s' is not legal",
+                    samMethodName));
+        }
+
         if (!samBase.isInterface()) {
             throw new LambdaConversionException(String.format(
                     "Functional interface %s is not an interface",
@@ -171,24 +204,12 @@
      * @throws LambdaConversionException if there are improper conversions
      */
     void validateMetafactoryArgs() throws LambdaConversionException {
-        switch (implKind) {
-            case MethodHandleInfo.REF_invokeInterface:
-            case MethodHandleInfo.REF_invokeVirtual:
-            case MethodHandleInfo.REF_invokeStatic:
-            case MethodHandleInfo.REF_newInvokeSpecial:
-            case MethodHandleInfo.REF_invokeSpecial:
-                break;
-            default:
-                throw new LambdaConversionException(String.format("Unsupported MethodHandle kind: %s", implInfo));
-        }
-
-        // Check arity: optional-receiver + captured + SAM == impl
+        // Check arity: captured + SAM == impl
         final int implArity = implMethodType.parameterCount();
-        final int receiverArity = implIsInstanceMethod ? 1 : 0;
         final int capturedArity = invokedType.parameterCount();
         final int samArity = samMethodType.parameterCount();
         final int instantiatedArity = instantiatedMethodType.parameterCount();
-        if (implArity + receiverArity != capturedArity + samArity) {
+        if (implArity != capturedArity + samArity) {
             throw new LambdaConversionException(
                     String.format("Incorrect number of parameters for %s method %s; %d captured parameters, %d functional interface method parameters, %d implementation parameters",
                                   implIsInstanceMethod ? "instance" : "static", implInfo,
@@ -209,8 +230,8 @@
         }
 
         // If instance: first captured arg (receiver) must be subtype of class where impl method is defined
-        final int capturedStart;
-        final int samStart;
+        final int capturedStart; // index of first non-receiver capture parameter in implMethodType
+        final int samStart; // index of first non-receiver sam parameter in implMethodType
         if (implIsInstanceMethod) {
             final Class<?> receiverClass;
 
@@ -223,45 +244,36 @@
             } else {
                 // receiver is a captured variable
                 capturedStart = 1;
-                samStart = 0;
+                samStart = capturedArity;
                 receiverClass = invokedType.parameterType(0);
             }
 
             // check receiver type
-            if (!implDefiningClass.isAssignableFrom(receiverClass)) {
+            if (!implClass.isAssignableFrom(receiverClass)) {
                 throw new LambdaConversionException(
                         String.format("Invalid receiver type %s; not a subtype of implementation type %s",
-                                      receiverClass, implDefiningClass));
-            }
-
-           Class<?> implReceiverClass = implMethod.type().parameterType(0);
-           if (implReceiverClass != implDefiningClass && !implReceiverClass.isAssignableFrom(receiverClass)) {
-               throw new LambdaConversionException(
-                       String.format("Invalid receiver type %s; not a subtype of implementation receiver type %s",
-                                     receiverClass, implReceiverClass));
+                                      receiverClass, implClass));
             }
         } else {
             // no receiver
             capturedStart = 0;
-            samStart = 0;
+            samStart = capturedArity;
         }
 
         // Check for exact match on non-receiver captured arguments
-        final int implFromCaptured = capturedArity - capturedStart;
-        for (int i=0; i<implFromCaptured; i++) {
+        for (int i=capturedStart; i<capturedArity; i++) {
             Class<?> implParamType = implMethodType.parameterType(i);
-            Class<?> capturedParamType = invokedType.parameterType(i + capturedStart);
+            Class<?> capturedParamType = invokedType.parameterType(i);
             if (!capturedParamType.equals(implParamType)) {
                 throw new LambdaConversionException(
                         String.format("Type mismatch in captured lambda parameter %d: expecting %s, found %s",
                                       i, capturedParamType, implParamType));
             }
         }
-        // Check for adaptation match on SAM arguments
-        final int samOffset = samStart - implFromCaptured;
-        for (int i=implFromCaptured; i<implArity; i++) {
+        // Check for adaptation match on non-receiver SAM arguments
+        for (int i=samStart; i<implArity; i++) {
             Class<?> implParamType = implMethodType.parameterType(i);
-            Class<?> instantiatedParamType = instantiatedMethodType.parameterType(i + samOffset);
+            Class<?> instantiatedParamType = instantiatedMethodType.parameterType(i - capturedArity);
             if (!isAdaptableTo(instantiatedParamType, implParamType, true)) {
                 throw new LambdaConversionException(
                         String.format("Type mismatch for lambda argument %d: %s is not convertible to %s",
@@ -271,29 +283,40 @@
 
         // Adaptation match: return type
         Class<?> expectedType = instantiatedMethodType.returnType();
-        Class<?> actualReturnType =
-                (implKind == MethodHandleInfo.REF_newInvokeSpecial)
-                  ? implDefiningClass
-                  : implMethodType.returnType();
-        Class<?> samReturnType = samMethodType.returnType();
+        Class<?> actualReturnType = implMethodType.returnType();
         if (!isAdaptableToAsReturn(actualReturnType, expectedType)) {
             throw new LambdaConversionException(
                     String.format("Type mismatch for lambda return: %s is not convertible to %s",
                                   actualReturnType, expectedType));
         }
-        if (!isAdaptableToAsReturnStrict(expectedType, samReturnType)) {
-            throw new LambdaConversionException(
-                    String.format("Type mismatch for lambda expected return: %s is not convertible to %s",
-                                  expectedType, samReturnType));
+
+        // Check descriptors of generated methods
+        checkDescriptor(samMethodType);
+        for (MethodType bridgeMT : additionalBridges) {
+            checkDescriptor(bridgeMT);
         }
-        for (MethodType bridgeMT : additionalBridges) {
-            if (!isAdaptableToAsReturnStrict(expectedType, bridgeMT.returnType())) {
-                throw new LambdaConversionException(
-                        String.format("Type mismatch for lambda expected return: %s is not convertible to %s",
-                                      expectedType, bridgeMT.returnType()));
+    }
+
+    /** Validate that the given descriptor's types are compatible with {@code instantiatedMethodType} **/
+    private void checkDescriptor(MethodType descriptor) throws LambdaConversionException {
+        for (int i = 0; i < instantiatedMethodType.parameterCount(); i++) {
+            Class<?> instantiatedParamType = instantiatedMethodType.parameterType(i);
+            Class<?> descriptorParamType = descriptor.parameterType(i);
+            if (!descriptorParamType.isAssignableFrom(instantiatedParamType)) {
+                String msg = String.format("Type mismatch for instantiated parameter %d: %s is not a subtype of %s",
+                                           i, instantiatedParamType, descriptorParamType);
+                throw new LambdaConversionException(msg);
             }
         }
-     }
+
+        Class<?> instantiatedReturnType = instantiatedMethodType.returnType();
+        Class<?> descriptorReturnType = descriptor.returnType();
+        if (!isAdaptableToAsReturnStrict(instantiatedReturnType, descriptorReturnType)) {
+            String msg = String.format("Type mismatch for lambda expected return: %s is not convertible to %s",
+                                       instantiatedReturnType, descriptorReturnType);
+            throw new LambdaConversionException(msg);
+        }
+    }
 
     /**
      * Check type adaptability for parameter types.
@@ -345,8 +368,8 @@
                || !fromType.equals(void.class) && isAdaptableTo(fromType, toType, false);
     }
     private boolean isAdaptableToAsReturnStrict(Class<?> fromType, Class<?> toType) {
-        if (fromType.equals(void.class)) return toType.equals(void.class);
-        return isAdaptableTo(fromType, toType, true);
+        if (fromType.equals(void.class) || toType.equals(void.class)) return fromType.equals(toType);
+        else return isAdaptableTo(fromType, toType, true);
     }
 
 
--- a/jdk/src/java.base/share/classes/java/lang/invoke/DelegatingMethodHandle.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/DelegatingMethodHandle.java	Thu Mar 16 20:47:03 2017 +0000
@@ -98,21 +98,17 @@
                                         Object constraint,
                                         NamedFunction getTargetFn) {
         // No pre-action needed.
-        return makeReinvokerForm(target, whichCache, constraint, null, true, getTargetFn, null);
+        return makeReinvokerForm(target, whichCache, constraint, true, getTargetFn, null);
     }
     /** Create a LF which simply reinvokes a target of the given basic type. */
     static LambdaForm makeReinvokerForm(MethodHandle target,
                                         int whichCache,
                                         Object constraint,
-                                        String debugString,
                                         boolean forceInline,
                                         NamedFunction getTargetFn,
                                         NamedFunction preActionFn) {
         MethodType mtype = target.type().basicType();
         Kind kind = whichKind(whichCache);
-        if (debugString == null) {
-            debugString = kind.defaultLambdaName;
-        }
         boolean customized = (whichCache < 0 ||
                 mtype.parameterSlotCount() > MethodType.MAX_MH_INVOKER_ARITY);
         boolean hasPreAction = (preActionFn != null);
@@ -144,7 +140,7 @@
             targetArgs[0] = names[NEXT_MH];  // overwrite this MH with next MH
             names[REINVOKE] = new LambdaForm.Name(mtype, targetArgs);
         }
-        form = new LambdaForm(debugString, ARG_LIMIT, names, forceInline, kind);
+        form = new LambdaForm(ARG_LIMIT, names, forceInline, kind);
         if (!customized) {
             form = mtype.form().setCachedLambdaForm(whichCache, form);
         }
--- a/jdk/src/java.base/share/classes/java/lang/invoke/DirectMethodHandle.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/DirectMethodHandle.java	Thu Mar 16 20:47:03 2017 +0000
@@ -242,8 +242,7 @@
             result = NEW_OBJ;
         }
         names[LINKER_CALL] = new Name(linker, outArgs);
-        String lambdaName = kind.defaultLambdaName + "_" + shortenSignature(basicTypeSignature(mtype));
-        LambdaForm lform = new LambdaForm(lambdaName, ARG_LIMIT, names, result, kind);
+        LambdaForm lform = new LambdaForm(ARG_LIMIT, names, result, kind);
 
         // This is a tricky bit of code.  Don't send it through the LF interpreter.
         lform.compileToBytecode();
@@ -696,22 +695,33 @@
         if (needsCast && isGetter)
             names[POST_CAST] = new Name(NF_checkCast, names[DMH_THIS], names[LINKER_CALL]);
         for (Name n : names)  assert(n != null);
-        // add some detail to the lambdaForm debugname,
-        // significant only for debugging
-        StringBuilder nameBuilder = new StringBuilder(kind.methodName);
-        if (isStatic) {
-            nameBuilder.append("Static");
-        } else {
-            nameBuilder.append("Field");
-        }
-        if (needsCast)  nameBuilder.append("Cast");
-        if (needsInit)  nameBuilder.append("Init");
+
+        LambdaForm form;
         if (needsCast || needsInit) {
             // can't use the pre-generated form when casting and/or initializing
-            return new LambdaForm(nameBuilder.toString(), ARG_LIMIT, names, RESULT);
+            form = new LambdaForm(ARG_LIMIT, names, RESULT);
         } else {
-            return new LambdaForm(nameBuilder.toString(), ARG_LIMIT, names, RESULT, kind);
+            form = new LambdaForm(ARG_LIMIT, names, RESULT, kind);
         }
+
+        if (LambdaForm.debugNames()) {
+            // add some detail to the lambdaForm debugname,
+            // significant only for debugging
+            StringBuilder nameBuilder = new StringBuilder(kind.methodName);
+            if (isStatic) {
+                nameBuilder.append("Static");
+            } else {
+                nameBuilder.append("Field");
+            }
+            if (needsCast) {
+                nameBuilder.append("Cast");
+            }
+            if (needsInit) {
+                nameBuilder.append("Init");
+            }
+            LambdaForm.associateWithDebugName(form, nameBuilder.toString());
+        }
+        return form;
     }
 
     /**
--- a/jdk/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/InnerClassLambdaMetafactory.java	Thu Mar 16 20:47:03 2017 +0000
@@ -96,7 +96,6 @@
     private final String implMethodClassName;        // Name of type containing implementation "CC"
     private final String implMethodName;             // Name of implementation method "impl"
     private final String implMethodDesc;             // Type descriptor for implementation methods "(I)Ljava/lang/String;"
-    private final Class<?> implMethodReturnClass;    // class for implementation method return type "Ljava/lang/String;"
     private final MethodType constructorType;        // Generated class constructor type "(CC)void"
     private final ClassWriter cw;                    // ASM class writer
     private final String[] argNames;                 // Generated names for the constructor arguments
@@ -153,12 +152,9 @@
         super(caller, invokedType, samMethodName, samMethodType,
               implMethod, instantiatedMethodType,
               isSerializable, markerInterfaces, additionalBridges);
-        implMethodClassName = implDefiningClass.getName().replace('.', '/');
+        implMethodClassName = implClass.getName().replace('.', '/');
         implMethodName = implInfo.getName();
-        implMethodDesc = implMethodType.toMethodDescriptorString();
-        implMethodReturnClass = (implKind == MethodHandleInfo.REF_newInvokeSpecial)
-                ? implDefiningClass
-                : implMethodType.returnType();
+        implMethodDesc = implInfo.getMethodType().toMethodDescriptorString();
         constructorType = invokedType.changeReturnType(Void.TYPE);
         lambdaClassName = targetClass.getName().replace('.', '/') + "$$Lambda$" + counter.incrementAndGet();
         cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
@@ -467,13 +463,14 @@
             // Invoke the method we want to forward to
             visitMethodInsn(invocationOpcode(), implMethodClassName,
                             implMethodName, implMethodDesc,
-                            implDefiningClass.isInterface());
+                            implClass.isInterface());
 
             // Convert the return value (if any) and return it
             // Note: if adapting from non-void to void, the 'return'
             // instruction will pop the unneeded result
+            Class<?> implReturnClass = implMethodType.returnType();
             Class<?> samReturnClass = methodType.returnType();
-            convertType(implMethodReturnClass, samReturnClass, samReturnClass);
+            convertType(implReturnClass, samReturnClass, samReturnClass);
             visitInsn(getReturnOpcode(samReturnClass));
             // Maxs computed by ClassWriter.COMPUTE_MAXS,these arguments ignored
             visitMaxs(-1, -1);
@@ -482,23 +479,13 @@
 
         private void convertArgumentTypes(MethodType samType) {
             int lvIndex = 0;
-            boolean samIncludesReceiver = implIsInstanceMethod &&
-                                                   invokedType.parameterCount() == 0;
-            int samReceiverLength = samIncludesReceiver ? 1 : 0;
-            if (samIncludesReceiver) {
-                // push receiver
-                Class<?> rcvrType = samType.parameterType(0);
-                visitVarInsn(getLoadOpcode(rcvrType), lvIndex + 1);
-                lvIndex += getParameterSize(rcvrType);
-                convertType(rcvrType, implDefiningClass, instantiatedMethodType.parameterType(0));
-            }
             int samParametersLength = samType.parameterCount();
-            int argOffset = implMethodType.parameterCount() - samParametersLength;
-            for (int i = samReceiverLength; i < samParametersLength; i++) {
+            int captureArity = invokedType.parameterCount();
+            for (int i = 0; i < samParametersLength; i++) {
                 Class<?> argType = samType.parameterType(i);
                 visitVarInsn(getLoadOpcode(argType), lvIndex + 1);
                 lvIndex += getParameterSize(argType);
-                convertType(argType, implMethodType.parameterType(argOffset + i), instantiatedMethodType.parameterType(i));
+                convertType(argType, implMethodType.parameterType(captureArity + i), instantiatedMethodType.parameterType(i));
             }
         }
 
--- a/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/InvokerBytecodeGenerator.java	Thu Mar 16 20:47:03 2017 +0000
@@ -130,7 +130,7 @@
 
     /** For generating customized code for a single LambdaForm. */
     private InvokerBytecodeGenerator(String className, LambdaForm form, MethodType invokerType) {
-        this(className, form.debugName, form, invokerType);
+        this(className, form.lambdaName(), form, invokerType);
     }
 
     /** For generating customized code for a single LambdaForm. */
--- a/jdk/src/java.base/share/classes/java/lang/invoke/Invokers.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/Invokers.java	Thu Mar 16 20:47:03 2017 +0000
@@ -132,7 +132,7 @@
         MethodType mtype = targetType;
         MethodType invokerType = mtype.insertParameterTypes(0, VarHandle.class);
 
-        LambdaForm lform = varHandleMethodInvokerHandleForm(ak.methodName(), mtype, isExact);
+        LambdaForm lform = varHandleMethodInvokerHandleForm(ak, mtype, isExact);
         VarHandle.AccessDescriptor ad = new VarHandle.AccessDescriptor(mtype, ak.at.ordinal(), ak.ordinal());
         MethodHandle invoker = BoundMethodHandle.bindSingle(invokerType, lform, ad);
 
@@ -325,9 +325,9 @@
         }
         names[LINKER_CALL] = new Name(outCallType, outArgs);
         if (customized) {
-            lform = new LambdaForm(kind.defaultLambdaName, INARG_LIMIT, names);
+            lform = new LambdaForm(INARG_LIMIT, names);
         } else {
-            lform = new LambdaForm(kind.defaultLambdaName, INARG_LIMIT, names, kind);
+            lform = new LambdaForm(INARG_LIMIT, names, kind);
         }
         if (isLinker)
             lform.compileToBytecode();  // JVM needs a real methodOop
@@ -337,11 +337,10 @@
     }
 
 
-    static MemberName varHandleInvokeLinkerMethod(String name,
-                                                  MethodType mtype) {
+    static MemberName varHandleInvokeLinkerMethod(VarHandle.AccessMode ak, MethodType mtype) {
         LambdaForm lform;
         if (mtype.parameterSlotCount() <= MethodType.MAX_MH_ARITY - MH_LINKER_ARG_APPENDED) {
-            lform = varHandleMethodGenericLinkerHandleForm(name, mtype);
+            lform = varHandleMethodGenericLinkerHandleForm(ak, mtype);
         } else {
             // TODO
             throw newInternalError("Unsupported parameter slot count " + mtype.parameterSlotCount());
@@ -349,7 +348,8 @@
         return lform.vmentry;
     }
 
-    private static LambdaForm varHandleMethodGenericLinkerHandleForm(String name, MethodType mtype) {
+    private static LambdaForm varHandleMethodGenericLinkerHandleForm(VarHandle.AccessMode ak,
+            MethodType mtype) {
         // TODO Cache form?
 
         final int THIS_VH      = 0;
@@ -383,14 +383,18 @@
         MethodType outCallType = mtype.insertParameterTypes(0, VarHandle.class)
                 .basicType();
         names[LINKER_CALL] = new Name(outCallType, outArgs);
-        LambdaForm lform = new LambdaForm(name + ":VarHandle_invoke_MT_" + shortenSignature(basicTypeSignature(mtype)),
-                                          ARG_LIMIT + 1, names);
-
+        LambdaForm lform = new LambdaForm(ARG_LIMIT + 1, names, VARHANDLE_LINKER);
+        if (LambdaForm.debugNames()) {
+            String name = ak.methodName() + ":VarHandle_invoke_MT_" +
+                    shortenSignature(basicTypeSignature(mtype));
+            LambdaForm.associateWithDebugName(lform, name);
+        }
         lform.compileToBytecode();
         return lform;
     }
 
-    private static LambdaForm varHandleMethodInvokerHandleForm(String name, MethodType mtype, boolean isExact) {
+    private static LambdaForm varHandleMethodInvokerHandleForm(VarHandle.AccessMode ak,
+            MethodType mtype, boolean isExact) {
         // TODO Cache form?
 
         final int THIS_MH      = 0;
@@ -429,10 +433,14 @@
         MethodType outCallType = mtype.insertParameterTypes(0, VarHandle.class)
                 .basicType();
         names[LINKER_CALL] = new Name(outCallType, outArgs);
-        String debugName = isExact ? ":VarHandle_exactInvoker" : ":VarHandle_invoker";
-        LambdaForm lform = new LambdaForm(name + debugName + shortenSignature(basicTypeSignature(mtype)),
-                                          ARG_LIMIT, names);
-
+        Kind kind = isExact ? VARHANDLE_EXACT_INVOKER : VARHANDLE_INVOKER;
+        LambdaForm lform = new LambdaForm(ARG_LIMIT, names, kind);
+        if (LambdaForm.debugNames()) {
+            String name = ak.methodName() +
+                    (isExact ? ":VarHandle_exactInvoker_" : ":VarHandle_invoker_") +
+                    shortenSignature(basicTypeSignature(mtype));
+            LambdaForm.associateWithDebugName(lform, name);
+        }
         lform.prepare();
         return lform;
     }
@@ -543,7 +551,8 @@
         System.arraycopy(outArgs, 0, outArgs, PREPEND_COUNT, outArgs.length - PREPEND_COUNT);
         outArgs[PREPEND_MH] = names[CALL_MH];
         names[LINKER_CALL] = new Name(mtype, outArgs);
-        lform = new LambdaForm((skipCallSite ? "linkToTargetMethod" : "linkToCallSite"), INARG_LIMIT, names);
+        lform = new LambdaForm(INARG_LIMIT, names,
+                (skipCallSite ? LINK_TO_TARGET_METHOD : LINK_TO_CALL_SITE));
         lform.compileToBytecode();  // JVM needs a real methodOop
         lform = mtype.form().setCachedLambdaForm(which, lform);
         return lform;
--- a/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/LambdaForm.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, 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
@@ -126,7 +126,6 @@
     final boolean forceInline;
     final MethodHandle customized;
     @Stable final Name[] names;
-    final String debugName;
     final Kind kind;
     MemberName vmentry;   // low-level behavior, or null if not yet prepared
     private boolean isCompiled;
@@ -268,7 +267,7 @@
     }
 
     enum Kind {
-        GENERIC(""),
+        GENERIC("invoke"),
         ZERO("zero"),
         IDENTITY("identity"),
         BOUND_REINVOKER("BMH.reinvoke"),
@@ -278,6 +277,8 @@
         EXACT_INVOKER("MH.exactInvoker"),
         GENERIC_LINKER("MH.invoke_MT"),
         GENERIC_INVOKER("MH.invoker"),
+        LINK_TO_TARGET_METHOD("linkToTargetMethod"),
+        LINK_TO_CALL_SITE("linkToCallSite"),
         DIRECT_INVOKE_VIRTUAL("DMH.invokeVirtual"),
         DIRECT_INVOKE_SPECIAL("DMH.invokeSpecial"),
         DIRECT_INVOKE_STATIC("DMH.invokeStatic"),
@@ -319,7 +320,18 @@
         GET_DOUBLE("getDouble"),
         PUT_DOUBLE("putDouble"),
         GET_DOUBLE_VOLATILE("getDoubleVolatile"),
-        PUT_DOUBLE_VOLATILE("putDoubleVolatile");
+        PUT_DOUBLE_VOLATILE("putDoubleVolatile"),
+        TRY_FINALLY("tryFinally"),
+        COLLECT("collect"),
+        CONVERT("convert"),
+        SPREAD("spread"),
+        LOOP("loop"),
+        FIELD("field"),
+        GUARD("guard"),
+        GUARD_WITH_CATCH("guardWithCatch"),
+        VARHANDLE_EXACT_INVOKER("VH.exactInvoker"),
+        VARHANDLE_INVOKER("VH.invoker"),
+        VARHANDLE_LINKER("VH.invoke_MT");
 
         final String defaultLambdaName;
         final String methodName;
@@ -335,25 +347,20 @@
         }
     }
 
-    LambdaForm(String debugName,
-               int arity, Name[] names, int result) {
-        this(debugName, arity, names, result, /*forceInline=*/true, /*customized=*/null, Kind.GENERIC);
+    LambdaForm(int arity, Name[] names, int result) {
+        this(arity, names, result, /*forceInline=*/true, /*customized=*/null, Kind.GENERIC);
     }
-    LambdaForm(String debugName,
-               int arity, Name[] names, int result, Kind kind) {
-        this(debugName, arity, names, result, /*forceInline=*/true, /*customized=*/null, kind);
+    LambdaForm(int arity, Name[] names, int result, Kind kind) {
+        this(arity, names, result, /*forceInline=*/true, /*customized=*/null, kind);
     }
-    LambdaForm(String debugName,
-               int arity, Name[] names, int result, boolean forceInline, MethodHandle customized) {
-        this(debugName, arity, names, result, forceInline, customized, Kind.GENERIC);
+    LambdaForm(int arity, Name[] names, int result, boolean forceInline, MethodHandle customized) {
+        this(arity, names, result, forceInline, customized, Kind.GENERIC);
     }
-    LambdaForm(String debugName,
-               int arity, Name[] names, int result, boolean forceInline, MethodHandle customized, Kind kind) {
+    LambdaForm(int arity, Name[] names, int result, boolean forceInline, MethodHandle customized, Kind kind) {
         assert(namesOK(arity, names));
         this.arity = arity;
         this.result = fixResult(result, names);
         this.names = names.clone();
-        this.debugName = fixDebugName(debugName);
         this.forceInline = forceInline;
         this.customized = customized;
         this.kind = kind;
@@ -364,31 +371,23 @@
             compileToBytecode();
         }
     }
-    LambdaForm(String debugName,
-               int arity, Name[] names) {
-        this(debugName, arity, names, LAST_RESULT, /*forceInline=*/true, /*customized=*/null, Kind.GENERIC);
+    LambdaForm(int arity, Name[] names) {
+        this(arity, names, LAST_RESULT, /*forceInline=*/true, /*customized=*/null, Kind.GENERIC);
     }
-    LambdaForm(String debugName,
-               int arity, Name[] names, Kind kind) {
-        this(debugName, arity, names, LAST_RESULT, /*forceInline=*/true, /*customized=*/null, kind);
+    LambdaForm(int arity, Name[] names, Kind kind) {
+        this(arity, names, LAST_RESULT, /*forceInline=*/true, /*customized=*/null, kind);
     }
-    LambdaForm(String debugName,
-               int arity, Name[] names, boolean forceInline) {
-        this(debugName, arity, names, LAST_RESULT, forceInline, /*customized=*/null, Kind.GENERIC);
+    LambdaForm(int arity, Name[] names, boolean forceInline) {
+        this(arity, names, LAST_RESULT, forceInline, /*customized=*/null, Kind.GENERIC);
     }
-    LambdaForm(String debugName,
-               int arity, Name[] names, boolean forceInline, Kind kind) {
-        this(debugName, arity, names, LAST_RESULT, forceInline, /*customized=*/null, kind);
+    LambdaForm(int arity, Name[] names, boolean forceInline, Kind kind) {
+        this(arity, names, LAST_RESULT, forceInline, /*customized=*/null, kind);
     }
-    LambdaForm(String debugName,
-               Name[] formals, Name[] temps, Name result) {
-        this(debugName,
-             formals.length, buildNames(formals, temps, result), LAST_RESULT, /*forceInline=*/true, /*customized=*/null);
+    LambdaForm(Name[] formals, Name[] temps, Name result) {
+        this(formals.length, buildNames(formals, temps, result), LAST_RESULT, /*forceInline=*/true, /*customized=*/null);
     }
-    LambdaForm(String debugName,
-               Name[] formals, Name[] temps, Name result, boolean forceInline) {
-        this(debugName,
-             formals.length, buildNames(formals, temps, result), LAST_RESULT, forceInline, /*customized=*/null);
+    LambdaForm(Name[] formals, Name[] temps, Name result, boolean forceInline) {
+        this(formals.length, buildNames(formals, temps, result), LAST_RESULT, forceInline, /*customized=*/null);
     }
 
     private static Name[] buildNames(Name[] formals, Name[] temps, Name result) {
@@ -408,10 +407,9 @@
         this.arity = mt.parameterCount();
         this.result = (mt.returnType() == void.class || mt.returnType() == Void.class) ? -1 : arity;
         this.names = buildEmptyNames(arity, mt, result == -1);
-        this.debugName = "LF.zero";
         this.forceInline = true;
         this.customized = null;
-        this.kind = Kind.GENERIC;
+        this.kind = Kind.ZERO;
         assert(nameRefsAreLegal());
         assert(isEmpty());
         String sig = null;
@@ -436,36 +434,46 @@
         return result;
     }
 
-    private static String fixDebugName(String debugName) {
-        if (DEBUG_NAME_COUNTERS != null) {
-            int under = debugName.indexOf('_');
-            int length = debugName.length();
-            if (under < 0)  under = length;
-            String debugNameStem = debugName.substring(0, under);
-            Integer ctr;
-            synchronized (DEBUG_NAME_COUNTERS) {
-                ctr = DEBUG_NAME_COUNTERS.get(debugNameStem);
-                if (ctr == null)  ctr = 0;
-                DEBUG_NAME_COUNTERS.put(debugNameStem, ctr+1);
+    static boolean debugNames() {
+        return DEBUG_NAME_COUNTERS != null;
+    }
+
+    static void associateWithDebugName(LambdaForm form, String name) {
+        assert (debugNames());
+        synchronized (DEBUG_NAMES) {
+            DEBUG_NAMES.put(form, name);
+        }
+    }
+
+    String lambdaName() {
+        if (DEBUG_NAMES != null) {
+            synchronized (DEBUG_NAMES) {
+                String name = DEBUG_NAMES.get(this);
+                if (name == null) {
+                    name = generateDebugName();
+                }
+                return name;
             }
-            StringBuilder buf = new StringBuilder(debugNameStem);
-            buf.append('_');
-            int leadingZero = buf.length();
-            buf.append((int) ctr);
-            for (int i = buf.length() - leadingZero; i < 3; i++)
-                buf.insert(leadingZero, '0');
-            if (under < length) {
-                ++under;    // skip "_"
-                while (under < length && Character.isDigit(debugName.charAt(under))) {
-                    ++under;
-                }
-                if (under < length && debugName.charAt(under) == '_')  ++under;
-                if (under < length)
-                    buf.append('_').append(debugName, under, length);
-            }
-            return buf.toString();
         }
-        return debugName;
+        return kind.defaultLambdaName;
+    }
+
+    private String generateDebugName() {
+        assert (debugNames());
+        String debugNameStem = kind.defaultLambdaName;
+        Integer ctr = DEBUG_NAME_COUNTERS.getOrDefault(debugNameStem, 0);
+        DEBUG_NAME_COUNTERS.put(debugNameStem, ctr + 1);
+        StringBuilder buf = new StringBuilder(debugNameStem);
+        int leadingZero = buf.length();
+        buf.append((int) ctr);
+        for (int i = buf.length() - leadingZero; i < 3; i++) {
+            buf.insert(leadingZero, '0');
+        }
+        buf.append('_');
+        buf.append(basicTypeSignature());
+        String name = buf.toString();
+        associateWithDebugName(this, name);
+        return name;
     }
 
     private static boolean namesOK(int arity, Name[] names) {
@@ -482,7 +490,7 @@
 
     /** Customize LambdaForm for a particular MethodHandle */
     LambdaForm customize(MethodHandle mh) {
-        LambdaForm customForm = new LambdaForm(debugName, arity, names, result, forceInline, mh, kind);
+        LambdaForm customForm = new LambdaForm(arity, names, result, forceInline, mh, kind);
         if (COMPILE_THRESHOLD >= 0 && isCompiled) {
             // If shared LambdaForm has been compiled, compile customized version as well.
             customForm.compileToBytecode();
@@ -1030,7 +1038,8 @@
     }
 
     public String toString() {
-        StringBuilder buf = new StringBuilder(debugName+"=Lambda(");
+        String lambdaName = lambdaName();
+        StringBuilder buf = new StringBuilder(lambdaName + "=Lambda(");
         for (int i = 0; i < names.length; i++) {
             if (i == arity)  buf.append(")=>{");
             Name n = names[i];
@@ -1742,7 +1751,7 @@
         // bootstrap dependency on this method in case we're interpreting LFs
         if (isVoid) {
             Name[] idNames = new Name[] { argument(0, L_TYPE) };
-            idForm = new LambdaForm(idMem.getName(), 1, idNames, VOID_RESULT, Kind.IDENTITY);
+            idForm = new LambdaForm(1, idNames, VOID_RESULT, Kind.IDENTITY);
             idForm.compileToBytecode();
             idFun = new NamedFunction(idMem, SimpleMethodHandle.make(idMem.getInvocationType(), idForm));
 
@@ -1750,14 +1759,14 @@
             zeFun = idFun;
         } else {
             Name[] idNames = new Name[] { argument(0, L_TYPE), argument(1, type) };
-            idForm = new LambdaForm(idMem.getName(), 2, idNames, 1, Kind.IDENTITY);
+            idForm = new LambdaForm(2, idNames, 1, Kind.IDENTITY);
             idForm.compileToBytecode();
             idFun = new NamedFunction(idMem, MethodHandleImpl.makeIntrinsic(
                     idMem.getInvocationType(), idForm, MethodHandleImpl.Intrinsic.IDENTITY));
 
             Object zeValue = Wrapper.forBasicType(btChar).zero();
             Name[] zeNames = new Name[] { argument(0, L_TYPE), new Name(idFun, zeValue) };
-            zeForm = new LambdaForm(zeMem.getName(), 1, zeNames, 1, Kind.ZERO);
+            zeForm = new LambdaForm(1, zeNames, 1, Kind.ZERO);
             zeForm.compileToBytecode();
             zeFun = new NamedFunction(zeMem, MethodHandleImpl.makeIntrinsic(
                     zeMem.getInvocationType(), zeForm, MethodHandleImpl.Intrinsic.ZERO));
@@ -1805,11 +1814,15 @@
     }
 
     private static final HashMap<String,Integer> DEBUG_NAME_COUNTERS;
+    private static final HashMap<LambdaForm,String> DEBUG_NAMES;
     static {
-        if (debugEnabled())
+        if (debugEnabled()) {
             DEBUG_NAME_COUNTERS = new HashMap<>();
-        else
+            DEBUG_NAMES = new HashMap<>();
+        } else {
             DEBUG_NAME_COUNTERS = null;
+            DEBUG_NAMES = null;
+        }
     }
 
     static {
--- a/jdk/src/java.base/share/classes/java/lang/invoke/LambdaFormBuffer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/LambdaFormBuffer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -40,7 +40,6 @@
     private byte flags;
     private int firstChange;
     private Name resultName;
-    private String debugName;
     private ArrayList<Name> dups;
 
     private static final int F_TRANS = 0x10, F_OWNED = 0x03;
@@ -50,15 +49,15 @@
         setNames(lf.names);
         int result = lf.result;
         if (result == LAST_RESULT)  result = length - 1;
-        if (result >= 0 && lf.names[result].type != V_TYPE)
+        if (result >= 0 && lf.names[result].type != V_TYPE) {
             resultName = lf.names[result];
-        debugName = lf.debugName;
+        }
         assert(lf.nameRefsAreLegal());
     }
 
     private LambdaForm lambdaForm() {
         assert(!inTrans());  // need endEdit call to tidy things up
-        return new LambdaForm(debugName, arity, nameArray(), resultIndex());
+        return new LambdaForm(arity, nameArray(), resultIndex());
     }
 
     Name name(int i) {
--- a/jdk/src/java.base/share/classes/java/lang/invoke/LambdaFormEditor.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/LambdaFormEditor.java	Thu Mar 16 20:47:03 2017 +0000
@@ -915,7 +915,7 @@
             }
         }
 
-        form = new LambdaForm(lambdaForm.debugName, arity2, names2, result2);
+        form = new LambdaForm(arity2, names2, result2);
         return putInCache(key, form);
     }
 
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -399,7 +399,7 @@
             assert(RETURN_CONV == names.length-1);
         }
 
-        LambdaForm form = new LambdaForm("convert", lambdaType.parameterCount(), names, RESULT);
+        LambdaForm form = new LambdaForm(lambdaType.parameterCount(), names, RESULT, Kind.CONVERT);
         return SimpleMethodHandle.make(srcType, form);
     }
 
@@ -608,7 +608,7 @@
         }
         names[names.length - 1] = new Name(target, (Object[]) targetArgs);
 
-        LambdaForm form = new LambdaForm("spread", lambdaType.parameterCount(), names);
+        LambdaForm form = new LambdaForm(lambdaType.parameterCount(), names, Kind.SPREAD);
         return SimpleMethodHandle.make(srcType, form);
     }
 
@@ -676,7 +676,7 @@
         assert(inputArgPos + chunk == collectNamePos);  // use of rest of input args also
         names[targetNamePos] = new Name(target, (Object[]) targetArgs);
 
-        LambdaForm form = new LambdaForm("collect", lambdaType.parameterCount(), names);
+        LambdaForm form = new LambdaForm(lambdaType.parameterCount(), names, Kind.COLLECT);
         return SimpleMethodHandle.make(srcType, form);
     }
 
@@ -774,7 +774,7 @@
             @Override
             public LambdaForm apply(MethodHandle target) {
                 return DelegatingMethodHandle.makeReinvokerForm(target,
-                                   MethodTypeForm.LF_DELEGATE_BLOCK_INLINING, CountingWrapper.class, "reinvoker.dontInline", false,
+                                   MethodTypeForm.LF_DELEGATE_BLOCK_INLINING, CountingWrapper.class, false,
                                    DelegatingMethodHandle.NF_getTarget, CountingWrapper.NF_maybeStopCounting);
             }
         };
@@ -943,7 +943,7 @@
         invokeArgs[0] = names[SELECT_ALT];
         names[CALL_TARGET] = new Name(basicType, invokeArgs);
 
-        lform = new LambdaForm("guard", lambdaType.parameterCount(), names, /*forceInline=*/true);
+        lform = new LambdaForm(lambdaType.parameterCount(), names, /*forceInline=*/true, Kind.GUARD);
 
         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWT, lform);
     }
@@ -1019,7 +1019,7 @@
         Object[] unboxArgs  = new Object[] {names[GET_UNBOX_RESULT], names[TRY_CATCH]};
         names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs);
 
-        lform = new LambdaForm("guardWithCatch", lambdaType.parameterCount(), names);
+        lform = new LambdaForm(lambdaType.parameterCount(), names, Kind.GUARD_WITH_CATCH);
 
         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_GWC, lform);
     }
@@ -1886,7 +1886,7 @@
             names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs);
 
             lform = basicType.form().setCachedLambdaForm(MethodTypeForm.LF_LOOP,
-                    new LambdaForm("loop", lambdaType.parameterCount(), names));
+                    new LambdaForm(lambdaType.parameterCount(), names, Kind.LOOP));
         }
 
         // BOXED_ARGS is the index into the names array where the loop idiom starts
@@ -2120,7 +2120,7 @@
         Object[] unboxArgs  = new Object[] {names[GET_UNBOX_RESULT], names[TRY_FINALLY]};
         names[UNBOX_RESULT] = new Name(invokeBasicUnbox, unboxArgs);
 
-        lform = new LambdaForm("tryFinally", lambdaType.parameterCount(), names);
+        lform = new LambdaForm(lambdaType.parameterCount(), names, Kind.TRY_FINALLY);
 
         return basicType.form().setCachedLambdaForm(MethodTypeForm.LF_TF, lform);
     }
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandleNatives.java	Thu Mar 16 20:47:03 2017 +0000
@@ -420,7 +420,7 @@
                                                              MethodType mtype,
                                                              Object[] appendixResult) {
         // Get the signature method type
-        MethodType sigType = mtype.basicType();
+        final MethodType sigType = mtype.basicType();
 
         // Get the access kind from the method name
         VarHandle.AccessMode ak;
@@ -430,32 +430,37 @@
             throw MethodHandleStatics.newInternalError(e);
         }
 
-        // If not polymorphic in the return type, such as the compareAndSet
-        // methods that return boolean
-        if (ak.at.isMonomorphicInReturnType) {
-            if (ak.at.returnType != mtype.returnType()) {
-                // The caller contains a different return type than that
-                // defined by the method
-                throw newNoSuchMethodErrorOnVarHandle(name, mtype);
-            }
-            // Adjust the return type of the signature method type
-            sigType = sigType.changeReturnType(ak.at.returnType);
-        }
-
-        // Get the guard method type for linking
-        MethodType guardType = sigType
-                // VarHandle at start
-                .insertParameterTypes(0, VarHandle.class)
-                // Access descriptor at end
-                .appendParameterTypes(VarHandle.AccessDescriptor.class);
-
         // Create the appendix descriptor constant
         VarHandle.AccessDescriptor ad = new VarHandle.AccessDescriptor(mtype, ak.at.ordinal(), ak.ordinal());
         appendixResult[0] = ad;
 
         if (MethodHandleStatics.VAR_HANDLE_GUARDS) {
+            // If not polymorphic in the return type, such as the compareAndSet
+            // methods that return boolean
+            Class<?> guardReturnType = sigType.returnType();
+            if (ak.at.isMonomorphicInReturnType) {
+                if (ak.at.returnType != mtype.returnType()) {
+                    // The caller contains a different return type than that
+                    // defined by the method
+                    throw newNoSuchMethodErrorOnVarHandle(name, mtype);
+                }
+                // Adjust the return type of the signature method type
+                guardReturnType = ak.at.returnType;
+            }
+
+            // Get the guard method type for linking
+            final Class<?>[] guardParams = new Class<?>[sigType.parameterCount() + 2];
+            // VarHandle at start
+            guardParams[0] = VarHandle.class;
+            for (int i = 0; i < sigType.parameterCount(); i++) {
+                guardParams[i + 1] = sigType.parameterType(i);
+            }
+            // Access descriptor at end
+            guardParams[guardParams.length - 1] = VarHandle.AccessDescriptor.class;
+            MethodType guardType = MethodType.makeImpl(guardReturnType, guardParams, true);
+
             MemberName linker = new MemberName(
-                    VarHandleGuards.class, "guard_" + getVarHandleMethodSignature(sigType),
+                    VarHandleGuards.class, getVarHandleGuardMethodName(guardType),
                     guardType, REF_invokeStatic);
 
             linker = MemberName.getFactory().resolveOrNull(REF_invokeStatic, linker,
@@ -466,16 +471,18 @@
             // Fall back to lambda form linkage if guard method is not available
             // TODO Optionally log fallback ?
         }
-        return Invokers.varHandleInvokeLinkerMethod(name, mtype);
+        return Invokers.varHandleInvokeLinkerMethod(ak, mtype);
     }
-    static String getVarHandleMethodSignature(MethodType mt) {
-        StringBuilder sb = new StringBuilder(mt.parameterCount() + 2);
+    static String getVarHandleGuardMethodName(MethodType guardType) {
+        String prefix = "guard_";
+        StringBuilder sb = new StringBuilder(prefix.length() + guardType.parameterCount());
 
-        for (int i = 0; i < mt.parameterCount(); i++) {
-            Class<?> pt = mt.parameterType(i);
+        sb.append(prefix);
+        for (int i = 1; i < guardType.parameterCount() - 1; i++) {
+            Class<?> pt = guardType.parameterType(i);
             sb.append(getCharType(pt));
         }
-        sb.append('_').append(getCharType(mt.returnType()));
+        sb.append('_').append(getCharType(guardType.returnType()));
         return sb.toString();
     }
     static char getCharType(Class<?> pt) {
--- a/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/invoke/MethodHandles.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,8 +25,6 @@
 
 package java.lang.invoke;
 
-import jdk.internal.org.objectweb.asm.ClassWriter;
-import jdk.internal.org.objectweb.asm.Opcodes;
 import jdk.internal.reflect.CallerSensitive;
 import jdk.internal.reflect.Reflection;
 import jdk.internal.vm.annotation.ForceInline;
@@ -111,13 +109,17 @@
 
     /**
      * Returns a {@link Lookup lookup object} which is trusted minimally.
-     * It can only be used to create method handles to public members in
+     * The lookup has the {@code PUBLIC} and {@code UNCONDITIONAL} modes.
+     * It can only be used to create method handles to public members of
      * public classes in packages that are exported unconditionally.
      * <p>
-     * For now, the {@linkplain Lookup#lookupClass lookup class} of this lookup
-     * object is in an unnamed module.
-     * Consequently, the lookup context of this lookup object will be the bootstrap
-     * class loader, which means it cannot find user classes.
+     * As a matter of pure convention, the {@linkplain Lookup#lookupClass lookup class}
+     * of this lookup object will be {@link java.lang.Object}.
+     *
+     * @apiNote The use of Object is conventional, and because the lookup modes are
+     * limited, there is no special access provided to the internals of Object, its package
+     * or its module. Consequently, the lookup context of this lookup object will be the
+     * bootstrap class loader, which means it cannot find user classes.
      *
      * <p style="font-size:smaller;">
      * <em>Discussion:</em>
@@ -129,17 +131,12 @@
      * Also, it cannot access
      * <a href="MethodHandles.Lookup.html#callsens">caller sensitive methods</a>.
      * @return a lookup object which is trusted minimally
+     *
+     * @revised 9
+     * @spec JPMS
      */
     public static Lookup publicLookup() {
-        // During VM startup then only classes in the java.base module can be
-        // loaded and linked. This is because java.base exports aren't setup until
-        // the module system is initialized, hence types in the unnamed module
-        // (or any named module) can't link to java/lang/Object.
-        if (!jdk.internal.misc.VM.isModuleSystemInited()) {
-            return new Lookup(Object.class, Lookup.PUBLIC);
-        } else {
-            return LookupHelper.PUBLIC_LOOKUP;
-        }
+        return Lookup.PUBLIC_LOOKUP;
     }
 
     /**
@@ -172,6 +169,7 @@
      * @throws IllegalAccessException if the access check specified above fails
      * @throws SecurityException if denied by the security manager
      * @since 9
+     * @spec JPMS
      * @see Lookup#dropLookupMode
      */
     public static Lookup privateLookupIn(Class<?> targetClass, Lookup lookup) throws IllegalAccessException {
@@ -183,11 +181,11 @@
             throw new IllegalArgumentException(targetClass + " is an array class");
         Module targetModule = targetClass.getModule();
         Module callerModule = lookup.lookupClass().getModule();
-        if (callerModule != targetModule && targetModule.isNamed()) {
-            if (!callerModule.canRead(targetModule))
-                throw new IllegalAccessException(callerModule + " does not read " + targetModule);
+        if (!callerModule.canRead(targetModule))
+            throw new IllegalAccessException(callerModule + " does not read " + targetModule);
+        if (targetModule.isNamed()) {
             String pn = targetClass.getPackageName();
-            assert pn != null && pn.length() > 0 : "unnamed package cannot be in named module";
+            assert pn.length() > 0 : "unnamed package cannot be in named module";
             if (!targetModule.isOpen(pn, callerModule))
                 throw new IllegalAccessException(targetModule + " does not open " + pn + " to " + callerModule);
         }
@@ -601,6 +599,8 @@
      * so that there can be a secure foundation for lookups.
      * Nearly all other methods in the JSR 292 API rely on lookup
      * objects to check access requests.
+     *
+     * @revised 9
      */
     public static final
     class Lookup {
@@ -647,15 +647,33 @@
          *  lookup class and public types in packages exported by other modules
          *  to the module of the lookup class.
          *  @since 9
+         *  @spec JPMS
          */
         public static final int MODULE = PACKAGE << 1;
 
-        private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE);
+        /** A single-bit mask representing {@code unconditional} access
+         *  which may contribute to the result of {@link #lookupModes lookupModes}.
+         *  The value is {@code 0x20}, which does not correspond meaningfully to
+         *  any particular {@linkplain java.lang.reflect.Modifier modifier bit}.
+         *  A {@code Lookup} with this lookup mode assumes {@linkplain
+         *  java.lang.reflect.Module#canRead(java.lang.reflect.Module) readability}.
+         *  In conjunction with the {@code PUBLIC} modifier bit, a {@code Lookup}
+         *  with this lookup mode can access all public members of public types
+         *  of all modules where the type is in a package that is {@link
+         *  java.lang.reflect.Module#isExported(String) exported unconditionally}.
+         *  @since 9
+         *  @spec JPMS
+         *  @see #publicLookup()
+         */
+        public static final int UNCONDITIONAL = PACKAGE << 2;
+
+        private static final int ALL_MODES = (PUBLIC | PRIVATE | PROTECTED | PACKAGE | MODULE | UNCONDITIONAL);
+        private static final int FULL_POWER_MODES = (ALL_MODES & ~UNCONDITIONAL);
         private static final int TRUSTED   = -1;
 
         private static int fixmods(int mods) {
-            mods &= (ALL_MODES - PACKAGE - MODULE);
-            return (mods != 0) ? mods : (PACKAGE | MODULE);
+            mods &= (ALL_MODES - PACKAGE - MODULE - UNCONDITIONAL);
+            return (mods != 0) ? mods : (PACKAGE | MODULE | UNCONDITIONAL);
         }
 
         /** Tells which class is performing the lookup.  It is this class against
@@ -682,13 +700,14 @@
          *  {@linkplain #PRIVATE PRIVATE (0x02)},
          *  {@linkplain #PROTECTED PROTECTED (0x04)},
          *  {@linkplain #PACKAGE PACKAGE (0x08)},
-         *  and {@linkplain #MODULE MODULE (0x10)}.
+         *  {@linkplain #MODULE MODULE (0x10)},
+         *  and {@linkplain #UNCONDITIONAL UNCONDITIONAL (0x20)}.
          *  <p>
          *  A freshly-created lookup object
-         *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class}
-         *  has all possible bits set, since the caller class can access all its own members,
-         *  all public types in the caller's module, and all public types in packages exported
-         *  by other modules to the caller's module.
+         *  on the {@linkplain java.lang.invoke.MethodHandles#lookup() caller's class} has
+         *  all possible bits set, except {@code UNCONDITIONAL}. The lookup can be used to
+         *  access all members of the caller's class, all public types in the caller's module,
+         *  and all public types in packages exported by other modules to the caller's module.
          *  A lookup object on a new lookup class
          *  {@linkplain java.lang.invoke.MethodHandles.Lookup#in created from a previous lookup object}
          *  may have some mode bits set to zero.
@@ -701,6 +720,9 @@
          *  @return the lookup modes, which limit the kinds of access performed by this lookup object
          *  @see #in
          *  @see #dropLookupMode
+         *
+         *  @revised 9
+         *  @spec JPMS
          */
         public int lookupModes() {
             return allowedModes & ALL_MODES;
@@ -712,9 +734,9 @@
          * which in turn is called by a method not in this package.
          */
         Lookup(Class<?> lookupClass) {
-            this(lookupClass, ALL_MODES);
+            this(lookupClass, FULL_POWER_MODES);
             // make sure we haven't accidentally picked up a privileged class:
-            checkUnprivilegedlookupClass(lookupClass, ALL_MODES);
+            checkUnprivilegedlookupClass(lookupClass, FULL_POWER_MODES);
         }
 
         private Lookup(Class<?> lookupClass, int allowedModes) {
@@ -730,19 +752,20 @@
          * However, the resulting {@code Lookup} object is guaranteed
          * to have no more access capabilities than the original.
          * In particular, access capabilities can be lost as follows:<ul>
-         * <li>If the lookup class for this {@code Lookup} is not in a named module,
-         * and the new lookup class is in a named module {@code M}, then no members in
-         * {@code M}'s non-exported packages will be accessible.
-         * <li>If the lookup for this {@code Lookup} is in a named module, and the
-         * new lookup class is in a different module {@code M}, then no members, not even
-         * public members in {@code M}'s exported packages, will be accessible.
-         * <li>If the new lookup class differs from the old one,
-         * protected members will not be accessible by virtue of inheritance.
-         * (Protected members may continue to be accessible because of package sharing.)
+         * <li>If the old lookup class is in a {@link Module#isNamed() named} module, and
+         * the new lookup class is in a different module {@code M}, then no members, not
+         * even public members in {@code M}'s exported packages, will be accessible.
+         * The exception to this is when this lookup is {@link #publicLookup()
+         * publicLookup}, in which case {@code PUBLIC} access is not lost.
+         * <li>If the old lookup class is in an unnamed module, and the new lookup class
+         * is a different module then {@link #MODULE MODULE} access is lost.
+         * <li>If the new lookup class differs from the old one then {@code UNCONDITIONAL} is lost.
          * <li>If the new lookup class is in a different package
          * than the old one, protected and default (package) members will not be accessible.
          * <li>If the new lookup class is not within the same package member
-         * as the old one, private members will not be accessible.
+         * as the old one, private members will not be accessible, and protected members
+         * will not be accessible by virtue of inheritance.
+         * (Protected members may continue to be accessible because of package sharing.)
          * <li>If the new lookup class is not accessible to the old lookup class,
          * then no members, not even public members, will be accessible.
          * (In all other cases, public members will continue to be accessible.)
@@ -757,32 +780,34 @@
          * @return a lookup object which reports the desired lookup class, or the same object
          * if there is no change
          * @throws NullPointerException if the argument is null
+         *
+         * @revised 9
+         * @spec JPMS
          */
         public Lookup in(Class<?> requestedLookupClass) {
             Objects.requireNonNull(requestedLookupClass);
             if (allowedModes == TRUSTED)  // IMPL_LOOKUP can make any lookup at all
-                return new Lookup(requestedLookupClass, ALL_MODES);
+                return new Lookup(requestedLookupClass, FULL_POWER_MODES);
             if (requestedLookupClass == this.lookupClass)
                 return this;  // keep same capabilities
-
-            int newModes = (allowedModes & (ALL_MODES & ~PROTECTED));
+            int newModes = (allowedModes & FULL_POWER_MODES);
             if (!VerifyAccess.isSameModule(this.lookupClass, requestedLookupClass)) {
-                // Allowed to teleport from an unnamed to a named module but resulting
-                // Lookup has no access to module private members
-                if (this.lookupClass.getModule().isNamed()) {
+                // Need to drop all access when teleporting from a named module to another
+                // module. The exception is publicLookup where PUBLIC is not lost.
+                if (this.lookupClass.getModule().isNamed()
+                    && (this.allowedModes & UNCONDITIONAL) == 0)
                     newModes = 0;
-                } else {
-                    newModes &= ~MODULE;
-                }
+                else
+                    newModes &= ~(MODULE|PACKAGE|PRIVATE|PROTECTED);
             }
             if ((newModes & PACKAGE) != 0
                 && !VerifyAccess.isSamePackage(this.lookupClass, requestedLookupClass)) {
-                newModes &= ~(PACKAGE|PRIVATE);
+                newModes &= ~(PACKAGE|PRIVATE|PROTECTED);
             }
             // Allow nestmate lookups to be created without special privilege:
             if ((newModes & PRIVATE) != 0
                 && !VerifyAccess.isSamePackageMember(this.lookupClass, requestedLookupClass)) {
-                newModes &= ~PRIVATE;
+                newModes &= ~(PRIVATE|PROTECTED);
             }
             if ((newModes & PUBLIC) != 0
                 && !VerifyAccess.isClassAccessible(requestedLookupClass, this.lookupClass, allowedModes)) {
@@ -801,28 +826,29 @@
          * finds members, but with a lookup mode that has lost the given lookup mode.
          * The lookup mode to drop is one of {@link #PUBLIC PUBLIC}, {@link #MODULE
          * MODULE}, {@link #PACKAGE PACKAGE}, {@link #PROTECTED PROTECTED} or {@link #PRIVATE PRIVATE}.
-         * {@link #PROTECTED PROTECTED} is always dropped and so the resulting lookup
-         * mode will never have this access capability. When dropping {@code PACKAGE}
-         * then the resulting lookup will not have {@code PACKAGE} or {@code PRIVATE}
-         * access. When dropping {@code MODULE} then the resulting lookup will not
-         * have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. If {@code
-         * PUBLIC} is dropped then the resulting lookup has no access.
+         * {@link #PROTECTED PROTECTED} and {@link #UNCONDITIONAL UNCONDITIONAL} are always
+         * dropped and so the resulting lookup mode will never have these access capabilities.
+         * When dropping {@code PACKAGE} then the resulting lookup will not have {@code PACKAGE}
+         * or {@code PRIVATE} access. When dropping {@code MODULE} then the resulting lookup will
+         * not have {@code MODULE}, {@code PACKAGE}, or {@code PRIVATE} access. If {@code PUBLIC}
+         * is dropped then the resulting lookup has no access.
          * @param modeToDrop the lookup mode to drop
          * @return a lookup object which lacks the indicated mode, or the same object if there is no change
          * @throws IllegalArgumentException if {@code modeToDrop} is not one of {@code PUBLIC},
-         * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED} or {@code PRIVATE}
+         * {@code MODULE}, {@code PACKAGE}, {@code PROTECTED}, {@code PRIVATE} or {@code UNCONDITIONAL}
+         * @see MethodHandles#privateLookupIn
          * @since 9
-         * @see MethodHandles#privateLookupIn
          */
         public Lookup dropLookupMode(int modeToDrop) {
             int oldModes = lookupModes();
-            int newModes = oldModes & ~(modeToDrop | PROTECTED);
+            int newModes = oldModes & ~(modeToDrop | PROTECTED | UNCONDITIONAL);
             switch (modeToDrop) {
                 case PUBLIC: newModes &= ~(ALL_MODES); break;
                 case MODULE: newModes &= ~(PACKAGE | PRIVATE); break;
                 case PACKAGE: newModes &= ~(PRIVATE); break;
                 case PROTECTED:
-                case PRIVATE: break;
+                case PRIVATE:
+                case UNCONDITIONAL: break;
                 default: throw new IllegalArgumentException(modeToDrop + " is not a valid mode to drop");
             }
             if (newModes == oldModes) return this;  // return self if no change
@@ -835,6 +861,12 @@
         /** Package-private version of lookup which is trusted. */
         static final Lookup IMPL_LOOKUP = new Lookup(Object.class, TRUSTED);
 
+        /** Version of lookup which is trusted minimally.
+         *  It can only be used to create method handles to publicly accessible
+         *  members in packages that are exported unconditionally.
+         */
+        static final Lookup PUBLIC_LOOKUP = new Lookup(Object.class, (PUBLIC|UNCONDITIONAL));
+
         private static void checkUnprivilegedlookupClass(Class<?> lookupClass, int allowedModes) {
             String name = lookupClass.getName();
             if (name.startsWith("java.lang.invoke."))
@@ -845,7 +877,7 @@
             // TODO replace with a more formal and less fragile mechanism
             // that does not bluntly restrict classes under packages within
             // java.base from looking up MethodHandles or VarHandles.
-            if (allowedModes == ALL_MODES && lookupClass.getClassLoader() == null) {
+            if (allowedModes == FULL_POWER_MODES && lookupClass.getClassLoader() == null) {
                 if ((name.startsWith("java.") &&
                      !name.equals("java.lang.Thread") &&
                      !name.startsWith("java.util.concurrent.")) ||
@@ -866,6 +898,7 @@
          * <ul>
          * <li>If no access is allowed, the suffix is "/noaccess".
          * <li>If only public access to types in exported packages is allowed, the suffix is "/public".
+         * <li>If only public access and unconditional access are allowed, the suffix is "/publicLookup".
          * <li>If only public and module access are allowed, the suffix is "/module".
          * <li>If only public, module and package access are allowed, the suffix is "/package".
          * <li>If only public, module, package, and private access are allowed, the suffix is "/private".
@@ -884,6 +917,9 @@
          * because it requires a direct subclass relationship between
          * caller and callee.)
          * @see #in
+         *
+         * @revised 9
+         * @spec JPMS
          */
         @Override
         public String toString() {
@@ -893,13 +929,15 @@
                 return cname + "/noaccess";
             case PUBLIC:
                 return cname + "/public";
+            case PUBLIC|UNCONDITIONAL:
+                return cname  + "/publicLookup";
             case PUBLIC|MODULE:
                 return cname + "/module";
             case PUBLIC|MODULE|PACKAGE:
                 return cname + "/package";
-            case ALL_MODES & ~PROTECTED:
+            case FULL_POWER_MODES & ~PROTECTED:
                 return cname + "/private";
-            case ALL_MODES:
+            case FULL_POWER_MODES:
                 return cname;
             case TRUSTED:
                 return "/trusted";  // internal only; not exported
@@ -1580,6 +1618,7 @@
             if (refKind == REF_invokeSpecial)
                 refKind = REF_invokeVirtual;
             assert(method.isMethod());
+            @SuppressWarnings("deprecation")
             Lookup lookup = m.isAccessible() ? IMPL_LOOKUP : this;
             return lookup.getDirectMethodNoSecurityManager(refKind, method.getDeclaringClass(), method, findBoundCallerClass(method));
         }
@@ -1662,6 +1701,7 @@
         public MethodHandle unreflectConstructor(Constructor<?> c) throws IllegalAccessException {
             MemberName ctor = new MemberName(c);
             assert(ctor.isConstructor());
+            @SuppressWarnings("deprecation")
             Lookup lookup = c.isAccessible() ? IMPL_LOOKUP : this;
             return lookup.getDirectConstructorNoSecurityManager(ctor.getDeclaringClass(), ctor);
         }
@@ -1692,6 +1732,7 @@
             assert(isSetter
                     ? MethodHandleNatives.refKindIsSetter(field.getReferenceKind())
                     : MethodHandleNatives.refKindIsGetter(field.getReferenceKind()));
+            @SuppressWarnings("deprecation")
             Lookup lookup = f.isAccessible() ? IMPL_LOOKUP : this;
             return lookup.getDirectFieldNoSecurityManager(field.getReferenceKind(), f.getDeclaringClass(), field);
         }
@@ -2033,9 +2074,9 @@
                                (defc == refc ||
                                 Modifier.isPublic(refc.getModifiers())));
             if (!classOK && (allowedModes & PACKAGE) != 0) {
-                classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), ALL_MODES) &&
+                classOK = (VerifyAccess.isClassAccessible(defc, lookupClass(), FULL_POWER_MODES) &&
                            (defc == refc ||
-                            VerifyAccess.isClassAccessible(refc, lookupClass(), ALL_MODES)));
+                            VerifyAccess.isClassAccessible(refc, lookupClass(), FULL_POWER_MODES)));
             }
             if (!classOK)
                 return "class is not public";
@@ -2348,53 +2389,6 @@
     }
 
     /**
-     * Helper class used to lazily create PUBLIC_LOOKUP with a lookup class
-     * in an <em>unnamed module</em>.
-     *
-     * @see Lookup#publicLookup
-     */
-    private static class LookupHelper {
-        private static final String UNNAMED = "Unnamed";
-        private static final String OBJECT  = "java/lang/Object";
-
-        private static Class<?> createClass() {
-            try {
-                ClassWriter cw = new ClassWriter(0);
-                cw.visit(Opcodes.V1_8,
-                         Opcodes.ACC_FINAL + Opcodes.ACC_SUPER,
-                         UNNAMED,
-                         null,
-                         OBJECT,
-                         null);
-                cw.visitSource(UNNAMED, null);
-                cw.visitEnd();
-                byte[] bytes = cw.toByteArray();
-                ClassLoader loader = new ClassLoader(null) {
-                    @Override
-                    protected Class<?> findClass(String cn) throws ClassNotFoundException {
-                        if (cn.equals(UNNAMED))
-                            return super.defineClass(UNNAMED, bytes, 0, bytes.length);
-                        throw new ClassNotFoundException(cn);
-                    }
-                };
-                return loader.loadClass(UNNAMED);
-            } catch (Exception e) {
-                throw new InternalError(e);
-            }
-        }
-
-        private static final Class<?> PUBLIC_LOOKUP_CLASS = createClass();
-
-        /**
-         * Lookup that is trusted minimally. It can only be used to create
-         * method handles to publicly accessible members in exported packages.
-         *
-         * @see MethodHandles#publicLookup
-         */
-        static final Lookup PUBLIC_LOOKUP = new Lookup(PUBLIC_LOOKUP_CLASS, Lookup.PUBLIC);
-    }
-
-    /**
      * Produces a method handle constructing arrays of a desired type.
      * The return type of the method handle will be the array type.
      * The type of its sole argument will be {@code int}, which specifies the size of the array.
--- a/jdk/src/java.base/share/classes/java/lang/module/Configuration.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/module/Configuration.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -42,126 +42,48 @@
 import java.util.stream.Stream;
 
 /**
- * The configuration that is the result of resolution or resolution with
- * service binding.
- *
- * <h2><a name="resolution">Resolution</a></h2>
- *
- * <p> Resolution is the process of computing the transitive closure of a set
- * of root modules over a set of observable modules by resolving the
- * dependences expressed by {@code requires} clauses.
- *
- * The <em>dependence graph</em> is augmented with edges that take account of
- * implicitly declared dependences ({@code requires transitive}) to create a
- * <em>readability graph</em>. A {@code Configuration} encapsulates the
- * resulting graph of {@link ResolvedModule resolved modules}.
- *
- * <p> Suppose we have the following observable modules: </p>
- * <pre> {@code
- *     module m1 { requires m2; }
- *     module m2 { requires transitive m3; }
- *     module m3 { }
- *     module m4 { }
- * } </pre>
+ * A configuration that is the result of <a href="package-summary.html#resolution">
+ * resolution</a> or resolution with <a href="package-summary.html#servicebinding">
+ * service binding</a>.
  *
- * <p> If the module {@code m1} is resolved then the resulting configuration
- * contains three modules ({@code m1}, {@code m2}, {@code m3}). The edges in
- * its readability graph are: </p>
- * <pre> {@code
- *     m1 --> m2  (meaning m1 reads m2)
- *     m1 --> m3
- *     m2 --> m3
- * } </pre>
- *
- * <p> Resolution is an additive process. When computing the transitive closure
- * then the dependence relation may include dependences on modules in parent
- * configurations. The result is a <em>relative configuration</em> that is
- * relative to one or more parent configurations and where the readability graph
- * may have edges from modules in the configuration to modules in parent
- * configurations.
- *
- * </p>
- *
- * <p> Suppose we have the following observable modules: </p>
- * <pre> {@code
- *     module m1 { requires m2; requires java.xml; }
- *     module m2 { }
- * } </pre>
+ * <p> A configuration encapsulates the <em>readability graph</em> that is the
+ * output of resolution. A readability graph is a directed graph where the nodes
+ * are of type {@link ResolvedModule} and the edges represent the readability
+ * amongst the modules. {@code Configuration} defines the {@link #modules()
+ * modules()} method to get the set of resolved modules in the graph. {@code
+ * ResolvedModule} defines the {@link ResolvedModule#reads() reads()} method to
+ * get the set of modules that a resolved module reads. The modules that are
+ * read may be in the same configuration or may be in {@link #parents() parent}
+ * configurations. </p>
  *
- * <p> If module {@code m1} is resolved with the configuration for the {@link
- * java.lang.reflect.Layer#boot() boot} layer as the parent then the resulting
- * configuration contains two modules ({@code m1}, {@code m2}). The edges in
- * its readability graph are:
- * <pre> {@code
- *     m1 --> m2
- *     m1 --> java.xml
- * } </pre>
- * where module {@code java.xml} is in the parent configuration. For
- * simplicity, this example omits the implicitly declared dependence on the
- * {@code java.base} module.
- *
- * <a name="automaticmoduleresolution"></a>
- * <p> {@link ModuleDescriptor#isAutomatic() Automatic} modules receive special
- * treatment during resolution. Each automatic module is resolved so that it
- * reads all other modules in the configuration and all parent configurations.
- * Each automatic module is also resolved as if it {@code requires transitive}
- * all other automatic modules in the configuration (and all automatic modules
- * in parent configurations). </p>
-
- * <h2><a name="servicebinding">Service binding</a></h2>
+ * <p> Configuration defines the {@link #resolve(ModuleFinder,List,ModuleFinder,Collection)
+ * resolve} method to resolve a collection of root modules, and the {@link
+ * #resolveAndBind(ModuleFinder,List,ModuleFinder,Collection) resolveAndBind}
+ * method to do resolution with service binding. There are instance and
+ * static variants of both methods. The instance methods create a configuration
+ * with the receiver as the parent configuration. The static methods are for
+ * more advanced cases where there can be more than one parent configuration. </p>
  *
- * <p> Service binding is the process of augmenting a graph of resolved modules
- * from the set of observable modules induced by the service-use dependence
- * ({@code uses} and {@code provides} clauses). Any module that was not
- * previously in the graph requires resolution to compute its transitive
- * closure. Service binding is an iterative process in that adding a module
- * that satisfies some service-use dependence may introduce new service-use
- * dependences. </p>
- *
- * <p> Suppose we have the following observable modules: </p>
- * <pre> {@code
- *     module m1 { exports p; uses p.S; }
- *     module m2 { requires m1; provides p.S with p2.S2; }
- *     module m3 { requires m1; requires m4; provides p.S with p3.S3; }
- *     module m4 { }
- * } </pre>
- *
- * <p> If the module {@code m1} is resolved then the resulting graph of modules
- * has one module ({@code m1}). If the graph is augmented with modules induced
- * by the service-use dependence relation then the configuration will contain
- * four modules ({@code m1}, {@code m2}, {@code m3}, {@code m4}). The edges in
- * its readability graph are: </p>
- * <pre> {@code
- *     m2 --> m1
- *     m3 --> m1
- *     m3 --> m4
- * } </pre>
- * <p> The edges in the conceptual service-use graph are: </p>
- * <pre> {@code
- *     m1 --> m2  (meaning m1 uses a service that is provided by m2)
- *     m1 --> m3
- * } </pre>
- *
- * <p> If this configuration is instantiated as a {@code Layer}, and if code in
- * module {@code m1} uses {@link java.util.ServiceLoader ServiceLoader} to
- * iterate over implementations of {@code p.S.class}, then it will iterate over
- * an instance of {@code p2.S2} and {@code p3.S3}. </p>
+ * <p> Each {@link java.lang.reflect.Layer layer} of modules in the Java virtual
+ * machine is created from a configuration. The configuration for the {@link
+ * java.lang.reflect.Layer#boot() boot} layer is obtained by invoking {@code
+ * Layer.boot().configuration()}. The configuration for the boot layer will
+ * often be the parent when creating new configurations. </p>
  *
  * <h3> Example </h3>
  *
- * <p> The following example uses the {@code resolveRequires} method to resolve
- * a module named <em>myapp</em> with the configuration for the boot layer as
- * the parent configuration. It prints the name of each resolved module and
- * the names of the modules that each module reads. </p>
+ * <p> The following example uses the {@link
+ * #resolve(ModuleFinder,ModuleFinder,Collection) resolve} method to resolve a
+ * module named <em>myapp</em> with the configuration for the boot layer as the
+ * parent configuration. It prints the name of each resolved module and the
+ * names of the modules that each module reads. </p>
  *
  * <pre>{@code
  *    ModuleFinder finder = ModuleFinder.of(dir1, dir2, dir3);
  *
  *    Configuration parent = Layer.boot().configuration();
  *
- *    Configuration cf = parent.resolveRequires(finder,
- *                                              ModuleFinder.of(),
- *                                              Set.of("myapp"));
+ *    Configuration cf = parent.resolve(finder, ModuleFinder.of(), Set.of("myapp"));
  *    cf.modules().forEach(m -> {
  *        System.out.format("%s -> %s%n",
  *            m.name(),
@@ -172,6 +94,7 @@
  * }</pre>
  *
  * @since 9
+ * @spec JPMS
  * @see java.lang.reflect.Layer
  */
 public final class Configuration {
@@ -186,11 +109,23 @@
     private final Set<ResolvedModule> modules;
     private final Map<String, ResolvedModule> nameToModule;
 
+    // module constraints on target
+    private final String osName;
+    private final String osArch;
+    private final String osVersion;
+
+    String osName() { return osName; }
+    String osArch() { return osArch; }
+    String osVersion() { return osVersion; }
+
     private Configuration() {
         this.parents = Collections.emptyList();
         this.graph = Collections.emptyMap();
         this.modules = Collections.emptySet();
         this.nameToModule = Collections.emptyMap();
+        this.osName = null;
+        this.osArch = null;
+        this.osVersion = null;
     }
 
     private Configuration(List<Configuration> parents,
@@ -214,27 +149,30 @@
         this.graph = g;
         this.modules = Set.of(moduleArray);
         this.nameToModule = Map.ofEntries(nameEntries);
+
+        this.osName = resolver.osName();
+        this.osArch = resolver.osArch();
+        this.osVersion = resolver.osVersion();
     }
 
-
     /**
      * Resolves a collection of root modules, with this configuration as its
      * parent, to create a new configuration. This method works exactly as
      * specified by the static {@link
-     * #resolveRequires(ModuleFinder,List,ModuleFinder,Collection) resolveRequires}
+     * #resolve(ModuleFinder,List,ModuleFinder,Collection) resolve}
      * method when invoked with this configuration as the parent. In other words,
      * if this configuration is {@code cf} then this method is equivalent to
      * invoking:
      * <pre> {@code
-     *     Configuration.resolveRequires(before, List.of(cf), after, roots);
+     *     Configuration.resolve(before, List.of(cf), after, roots);
      * }</pre>
      *
      * @param  before
      *         The <em>before</em> module finder to find modules
      * @param  after
-     *         The <em>after</em> module finder to locate modules when a
-     *         module cannot be located by the {@code before} module finder
-     *         and the module is not in this configuration
+     *         The <em>after</em> module finder to locate modules when not
+     *         located by the {@code before} module finder or in parent
+     *         configurations
      * @param  roots
      *         The possibly-empty collection of module names of the modules
      *         to resolve
@@ -242,16 +180,20 @@
      * @return The configuration that is the result of resolving the given
      *         root modules
      *
+     * @throws FindException
+     *         If resolution fails for any of the observability-related reasons
+     *         specified by the static {@code resolve} method
      * @throws ResolutionException
-     *         If resolution or the post-resolution checks fail
+     *         If any of the post-resolution consistency checks specified by
+     *         the  static {@code resolve} method fail
      * @throws SecurityException
      *         If locating a module is denied by the security manager
      */
-    public Configuration resolveRequires(ModuleFinder before,
-                                         ModuleFinder after,
-                                         Collection<String> roots)
+    public Configuration resolve(ModuleFinder before,
+                                 ModuleFinder after,
+                                 Collection<String> roots)
     {
-        return resolveRequires(before, List.of(this), after, roots);
+        return resolve(before, List.of(this), after, roots);
     }
 
 
@@ -259,12 +201,12 @@
      * Resolves a collection of root modules, with service binding, and with
      * this configuration as its parent, to create a new configuration.
      * This method works exactly as specified by the static {@link
-     * #resolveRequiresAndUses(ModuleFinder,List,ModuleFinder,Collection)
-     * resolveRequiresAndUses} method when invoked with this configuration
+     * #resolveAndBind(ModuleFinder,List,ModuleFinder,Collection)
+     * resolveAndBind} method when invoked with this configuration
      * as the parent. In other words, if this configuration is {@code cf} then
      * this method is equivalent to invoking:
      * <pre> {@code
-     *     Configuration.resolveRequiresAndUses(before, List.of(cf), after, roots);
+     *     Configuration.resolveAndBind(before, List.of(cf), after, roots);
      * }</pre>
      *
      *
@@ -272,25 +214,29 @@
      *         The <em>before</em> module finder to find modules
      * @param  after
      *         The <em>after</em> module finder to locate modules when not
-     *         located by the {@code before} module finder and this
-     *         configuration
+     *         located by the {@code before} module finder or in parent
+     *         configurations
      * @param  roots
      *         The possibly-empty collection of module names of the modules
      *         to resolve
      *
-     * @return The configuration that is the result of resolving the given
-     *         root modules
+     * @return The configuration that is the result of resolving, with service
+     *         binding, the given root modules
      *
+     * @throws FindException
+     *         If resolution fails for any of the observability-related reasons
+     *         specified by the static {@code resolve} method
      * @throws ResolutionException
-     *         If resolution or the post-resolution checks fail
+     *         If any of the post-resolution consistency checks specified by
+     *         the  static {@code resolve} method fail
      * @throws SecurityException
      *         If locating a module is denied by the security manager
      */
-    public Configuration resolveRequiresAndUses(ModuleFinder before,
-                                                ModuleFinder after,
-                                                Collection<String> roots)
+    public Configuration resolveAndBind(ModuleFinder before,
+                                        ModuleFinder after,
+                                        Collection<String> roots)
     {
-        return resolveRequiresAndUses(before, List.of(this), after, roots);
+        return resolveAndBind(before, List.of(this), after, roots);
     }
 
 
@@ -301,14 +247,14 @@
      *
      * This method is used to create the configuration for the boot layer.
      */
-    static Configuration resolveRequiresAndUses(ModuleFinder finder,
-                                                Collection<String> roots,
-                                                boolean check,
-                                                PrintStream traceOutput)
+    static Configuration resolveAndBind(ModuleFinder finder,
+                                        Collection<String> roots,
+                                        boolean check,
+                                        PrintStream traceOutput)
     {
         List<Configuration> parents = List.of(empty());
         Resolver resolver = new Resolver(finder, parents, ModuleFinder.of(), traceOutput);
-        resolver.resolveRequires(roots).resolveUses();
+        resolver.resolve(roots).bind();
 
         return new Configuration(parents, resolver, check);
     }
@@ -328,11 +274,11 @@
      *
      * <p> When all modules have been resolved then the resulting dependency
      * graph is checked to ensure that it does not contain cycles. A
-     * readability graph is constructed and in conjunction with the module
+     * readability graph is constructed, and in conjunction with the module
      * exports and service use, checked for consistency. </p>
      *
-     * <p> Resolution and the (post-resolution) consistency checks may fail for
-     * following reasons: </p>
+     * <p> Resolution may fail with {@code FindException} for the following
+     * <em>observability-related</em> reasons: </p>
      *
      * <ul>
      *     <li><p> A root module, or a direct or transitive dependency, is not
@@ -343,6 +289,20 @@
      *     descriptor ({@code module-info.class}) or two versions of the same
      *     module are found in the same directory. </p></li>
      *
+     *     <li><p> A module with the required name is found but the module
+     *     requires a different {@link ModuleDescriptor#osName() operating
+     *     system}, {@link ModuleDescriptor#osArch() architecture}, or {@link
+     *     ModuleDescriptor#osVersion() version} to other modules that have
+     *     been resolved for the new configuration or modules in the parent
+     *     configurations. </p></li>
+     *
+     * </ul>
+     *
+     * <p> Post-resolution consistency checks may fail with {@code
+     * ResolutionException} for the following reasons: </p>
+     *
+     * <ul>
+     *
      *     <li><p> A cycle is detected, say where module {@code m1} requires
      *     module {@code m2} and {@code m2} requires {@code m1}. </p></li>
      *
@@ -356,20 +316,11 @@
      *     module {@code M} nor exported to {@code M} by any module that
      *     {@code M} reads. </p></li>
      *
-     *     <li><p> A module {@code M} declares that it
-     *     "{@code provides ... with q.T}" but package {@code q} is not in
-     *     module {@code M}. </p></li>
+     * </ul>
      *
-     *     <li><p> Two or more modules in the configuration are specific to
-     *     different {@link ModuleDescriptor#osName() operating systems},
-     *     {@link ModuleDescriptor#osArch() architectures}, or {@link
-     *     ModuleDescriptor#osVersion() versions}. </p></li>
-     *
-     *     <li><p> Other implementation specific checks, for example referential
-     *     integrity checks to ensure that different versions of tighly coupled
-     *     modules cannot be combined in the same configuration. </p></li>
-     *
-     * </ul>
+     * @implNote In the implementation then observability of modules may depend
+     * on referential integrity checks that ensure different builds of tightly
+     * coupled modules are not combined in the same configuration.
      *
      * @param  before
      *         The <em>before</em> module finder to find modules
@@ -386,17 +337,22 @@
      * @return The configuration that is the result of resolving the given
      *         root modules
      *
+     * @throws FindException
+     *         If resolution fails for an observability-related reason
      * @throws ResolutionException
-     *         If resolution or the post-resolution checks fail
+     *         If a post-resolution consistency checks fails
      * @throws IllegalArgumentException
-     *         If the list of parents is empty
+     *         If the list of parents is empty, or the list has two or more
+     *         parents with modules for different target operating systems,
+     *         architectures, or versions
+     *
      * @throws SecurityException
      *         If locating a module is denied by the security manager
      */
-    public static Configuration resolveRequires(ModuleFinder before,
-                                                List<Configuration> parents,
-                                                ModuleFinder after,
-                                                Collection<String> roots)
+    public static Configuration resolve(ModuleFinder before,
+                                        List<Configuration> parents,
+                                        ModuleFinder after,
+                                        Collection<String> roots)
     {
         Objects.requireNonNull(before);
         Objects.requireNonNull(after);
@@ -407,7 +363,7 @@
             throw new IllegalArgumentException("'parents' is empty");
 
         Resolver resolver = new Resolver(before, parentList, after, null);
-        resolver.resolveRequires(roots);
+        resolver.resolve(roots);
 
         return new Configuration(parentList, resolver, true);
     }
@@ -417,24 +373,24 @@
      * configuration.
      *
      * <p> This method works exactly as specified by {@link
-     * #resolveRequires(ModuleFinder,List,ModuleFinder,Collection)
-     * resolveRequires} except that the graph of resolved modules is augmented
+     * #resolve(ModuleFinder,List,ModuleFinder,Collection)
+     * resolve} except that the graph of resolved modules is augmented
      * with modules induced by the service-use dependence relation. </p>
      *
      * <p> More specifically, the root modules are resolved as if by calling
-     * {@code resolveRequires}. The resolved modules, and all modules in the
+     * {@code resolve}. The resolved modules, and all modules in the
      * parent configurations, with {@link ModuleDescriptor#uses() service
      * dependences} are then examined. All modules found by the given module
      * finders that {@link ModuleDescriptor#provides() provide} an
      * implementation of one or more of the service types are added to the
      * module graph and then resolved as if by calling the {@code
-     * resolveRequires} method. Adding modules to the module graph may
-     * introduce new service-use dependences and so the process works
-     * iteratively until no more modules are added. </p>
+     * resolve} method. Adding modules to the module graph may introduce new
+     * service-use dependences and so the process works iteratively until no
+     * more modules are added. </p>
      *
-     * <p> As service binding involves resolution then it may fail with {@link
-     * ResolutionException} for exactly the same reasons specified in
-     * {@code resolveRequires}.  </p>
+     * <p> As service binding involves resolution then it may fail with {@code
+     * FindException} or {@code ResolutionException} for exactly the same
+     * reasons specified in {@code resolve}. </p>
      *
      * @param  before
      *         The <em>before</em> module finder to find modules
@@ -448,20 +404,26 @@
      *         The possibly-empty collection of module names of the modules
      *         to resolve
      *
-     * @return The configuration that is the result of resolving the given
-     *         root modules
+     * @return The configuration that is the result of resolving, with service
+     *         binding, the given root modules
      *
+     * @throws FindException
+     *         If resolution fails for any of the observability-related reasons
+     *         specified by the static {@code resolve} method
      * @throws ResolutionException
-     *         If resolution or the post-resolution checks fail
+     *         If any of the post-resolution consistency checks specified by
+     *         the  static {@code resolve} method fail
      * @throws IllegalArgumentException
-     *         If the list of parents is empty
+     *         If the list of parents is empty, or the list has two or more
+     *         parents with modules for different target operating systems,
+     *         architectures, or versions
      * @throws SecurityException
      *         If locating a module is denied by the security manager
      */
-    public static Configuration resolveRequiresAndUses(ModuleFinder before,
-                                                       List<Configuration> parents,
-                                                       ModuleFinder after,
-                                                       Collection<String> roots)
+    public static Configuration resolveAndBind(ModuleFinder before,
+                                               List<Configuration> parents,
+                                               ModuleFinder after,
+                                               Collection<String> roots)
     {
         Objects.requireNonNull(before);
         Objects.requireNonNull(after);
@@ -472,7 +434,7 @@
             throw new IllegalArgumentException("'parents' is empty");
 
         Resolver resolver = new Resolver(before, parentList, after, null);
-        resolver.resolveRequires(roots).resolveUses();
+        resolver.resolve(roots).bind();
 
         return new Configuration(parentList, resolver, true);
     }
--- a/jdk/src/java.base/share/classes/java/lang/module/FindException.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/module/FindException.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -26,10 +26,14 @@
 package java.lang.module;
 
 /**
- * Thrown by module finders when finding a module fails.
+ * Thrown by a {@link ModuleFinder ModuleFinder} when an error occurs finding
+ * a module. Also thrown by {@link
+ * Configuration#resolve(ModuleFinder,java.util.List,ModuleFinder,java.util.Collection)
+ * Configuration.resolve} when resolution fails for observability-related
+ * reasons.
  *
- * @see ModuleFinder
  * @since 9
+ * @spec JPMS
  */
 
 public class FindException extends RuntimeException {
--- a/jdk/src/java.base/share/classes/java/lang/module/InvalidModuleDescriptorException.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/module/InvalidModuleDescriptorException.java	Thu Mar 16 20:47:03 2017 +0000
@@ -31,6 +31,7 @@
  *
  * @see ModuleDescriptor#read
  * @since 9
+ * @spec JPMS
  */
 public class InvalidModuleDescriptorException extends RuntimeException {
     private static final long serialVersionUID = 4863390386809347380L;
--- a/jdk/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/module/ModuleDescriptor.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2017, 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 java.nio.ByteBuffer;
 import java.nio.file.Path;
 import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.EnumSet;
@@ -56,18 +57,37 @@
 /**
  * A module descriptor.
  *
- * <p> A {@code ModuleDescriptor} is typically created from the binary form
- * of a module declaration. Alternatively, the {@link ModuleDescriptor.Builder}
- * class can be used to create a {@code ModuleDescriptor} from its components.
- * The {@link #module module}, {@link #openModule openModule}, and {@link
- * #automaticModule automaticModule} methods create builders for building
- * different kinds of modules. </p>
+ * <p> A module descriptor describes a named module and defines methods to
+ * obtain each of its components. The module descriptor for a named module
+ * in the Java virtual machine is obtained by invoking the {@link
+ * java.lang.reflect.Module Module}'s {@link java.lang.reflect.Module#getDescriptor
+ * getDescriptor} method. Module descriptors can also be created using the
+ * {@link ModuleDescriptor.Builder} class or by reading the binary form of a
+ * module declaration ({@code module-info.class}) using the {@link
+ * #read(InputStream,Supplier) read} methods defined here. </p>
+ *
+ * <p> A module descriptor describes a <em>normal</em>, open, or automatic
+ * module. <em>Normal</em> modules and open modules describe their {@link
+ * #requires() dependences}, {@link #exports() exported-packages}, the services
+ * that they {@link #uses() use} or {@link #provides() provide}, and other
+ * components. <em>Normal</em> modules may {@link #opens() open} specific
+ * packages. The module descriptor for an open modules does not declare any
+ * open packages (its {@code opens} method returns an empty set) but when
+ * instantiated in the Java virtual machine then it is treated as if all
+ * packages are open. The module descriptor for an automatic module does not
+ * declare any dependences (except for the mandatory dependency on {@code
+ * java.base}), and does not declare any exported or open packages. Automatic
+ * module receive special treatment during resolution so that they read all
+ * other modules in the configuration. When an automatic module is instantiated
+ * in the Java virtual machine then it reads every unnamed module and is
+ * treated as if all packages are exported and open. </p>
  *
  * <p> {@code ModuleDescriptor} objects are immutable and safe for use by
  * multiple concurrent threads.</p>
  *
+ * @see java.lang.reflect.Module
  * @since 9
- * @see java.lang.reflect.Module
+ * @spec JPMS
  */
 
 public class ModuleDescriptor
@@ -75,10 +95,45 @@
 {
 
     /**
+     * A modifier on a module.
+     *
+     * @see ModuleDescriptor#modifiers()
+     * @since 9
+     */
+    public static enum Modifier {
+        /**
+         * An open module. An open module does not declare any open packages
+         * but the resulting module is treated as if all packages are open.
+         */
+        OPEN,
+
+        /**
+         * An automatic module. An automatic module is treated as if it exports
+         * and opens all packages.
+         *
+         * @apiNote This modifier does not correspond to a module flag in the
+         * binary form of a module declaration ({@code module-info.class}).
+         */
+        AUTOMATIC,
+
+        /**
+         * The module was not explicitly or implicitly declared.
+         */
+        SYNTHETIC,
+
+        /**
+         * The module was implicitly declared.
+         */
+        MANDATED;
+    }
+
+
+    /**
      * <p> A dependence upon a module </p>
      *
      * @see ModuleDescriptor#requires()
      * @since 9
+     * @spec JPMS
      */
 
     public final static class Requires
@@ -88,7 +143,9 @@
         /**
          * A modifier on a module dependence.
          *
+         * @see Requires#modifiers()
          * @since 9
+         * @spec JPMS
          */
         public static enum Modifier {
 
@@ -171,14 +228,18 @@
          * Compares this module dependence to another.
          *
          * <p> Two {@code Requires} objects are compared by comparing their
-         * module name lexicographically.  Where the module names are equal then
-         * the sets of modifiers are compared based on a value computed from the
-         * ordinal of each modifier. Where the module names are equal and the
-         * set of modifiers are equal then the version of the modules recorded
-         * at compile-time are compared. When comparing the versions recorded
-         * at compile-time then a dependence that has a recorded version is
-         * considered to succeed a dependence that does not have a recorded
-         * version. </p>
+         * module names lexicographically. Where the module names are equal
+         * then the sets of modifiers are compared in the same way that
+         * module modifiers are compared (see {@link ModuleDescriptor#compareTo
+         * ModuleDescriptor.compareTo}). Where the module names are equal and
+         * the set of modifiers are equal then the version of the modules
+         * recorded at compile-time are compared. When comparing the versions
+         * recorded at compile-time then a dependence that has a recorded
+         * version is considered to succeed a dependence that does not have a
+         * recorded version. </p>
+         *
+         * @param  that
+         *         The module dependence to compare
          *
          * @return A negative integer, zero, or a positive integer if this module
          *         dependence is less than, equal to, or greater than the given
@@ -186,39 +247,22 @@
          */
         @Override
         public int compareTo(Requires that) {
+            if (this == that) return 0;
+
             int c = this.name().compareTo(that.name());
-            if (c != 0)
-                return c;
+            if (c != 0) return c;
 
             // modifiers
-            c = Long.compare(this.modsValue(), that.modsValue());
-            if (c != 0)
-                return c;
+            long v1 = modsValue(this.modifiers());
+            long v2 = modsValue(that.modifiers());
+            c = Long.compare(v1, v2);
+            if (c != 0) return c;
 
             // compiledVersion
-            if (this.compiledVersion != null) {
-                if (that.compiledVersion != null)
-                    c = this.compiledVersion.compareTo(that.compiledVersion);
-                else
-                    c = 1;
-            } else {
-                if (that.compiledVersion != null)
-                    c = -1;
-            }
+            c = compare(this.compiledVersion, that.compiledVersion);
+            if (c != 0) return c;
 
-            return c;
-        }
-
-        /**
-         * Return a value for the modifiers to allow sets of modifiers to be
-         * compared.
-         */
-        private long modsValue() {
-            long value = 0;
-            for (Modifier m : mods) {
-                value += 1 << m.ordinal();
-            }
-            return value;
+            return 0;
         }
 
         /**
@@ -266,9 +310,9 @@
         }
 
         /**
-         * Returns a string describing module dependence.
+         * Returns a string describing this module dependence.
          *
-         * @return A string describing module dependence
+         * @return A string describing this module dependence
          */
         @Override
         public String toString() {
@@ -285,18 +329,23 @@
 
 
     /**
-     * <p> A module export, may be qualified or unqualified. </p>
+     * <p> A package exported by a module, may be qualified or unqualified. </p>
      *
      * @see ModuleDescriptor#exports()
      * @since 9
+     * @spec JPMS
      */
 
-    public final static class Exports {
+    public final static class Exports
+        implements Comparable<Exports>
+    {
 
         /**
-         * A modifier on a module export.
+         * A modifier on an exported package.
          *
+         * @see Exports#modifiers()
          * @since 9
+         * @spec JPMS
          */
         public static enum Modifier {
 
@@ -381,6 +430,52 @@
         }
 
         /**
+         * Compares this module export to another.
+         *
+         * <p> Two {@code Exports} objects are compared by comparing the package
+         * names lexicographically. Where the packages names are equal then the
+         * sets of modifiers are compared in the same way that module modifiers
+         * are compared (see {@link ModuleDescriptor#compareTo
+         * ModuleDescriptor.compareTo}). Where the package names are equal and
+         * the set of modifiers are equal then the set of target modules are
+         * compared. This is done by sorting the names of the target modules
+         * in ascending order, and according to their natural ordering, and then
+         * comparing the corresponding elements lexicographically. Where the
+         * sets differ in size, and the larger set contains all elements of the
+         * smaller set, then the larger set is considered to succeed the smaller
+         * set. </p>
+         *
+         * @param  that
+         *         The module export to compare
+         *
+         * @return A negative integer, zero, or a positive integer if this module
+         *         export is less than, equal to, or greater than the given
+         *         export dependence
+         */
+        @Override
+        public int compareTo(Exports that) {
+            if (this == that) return 0;
+
+            int c = source.compareTo(that.source);
+            if (c != 0)
+                return c;
+
+            // modifiers
+            long v1 = modsValue(this.modifiers());
+            long v2 = modsValue(that.modifiers());
+            c = Long.compare(v1, v2);
+            if (c != 0)
+                return c;
+
+            // targets
+            c = compare(targets, that.targets);
+            if (c != 0)
+                return c;
+
+            return 0;
+        }
+
+        /**
          * Computes a hash code for this module export.
          *
          * <p> The hash code is based upon the modifiers, the package name,
@@ -425,9 +520,9 @@
         }
 
         /**
-         * Returns a string describing module export.
+         * Returns a string describing the exported package.
          *
-         * @return A string describing module export
+         * @return A string describing the exported package
          */
         @Override
         public String toString() {
@@ -441,8 +536,7 @@
 
 
     /**
-     * <p> Represents a module <em>opens</em> directive, may be qualified or
-     * unqualified. </p>
+     * <p> A package opened by a module, may be qualified or unqualified. </p>
      *
      * <p> The <em>opens</em> directive in a module declaration declares a
      * package to be open to allow all types in the package, and all their
@@ -452,26 +546,30 @@
      *
      * @see ModuleDescriptor#opens()
      * @since 9
+     * @spec JPMS
      */
 
-    public final static class Opens {
-
+    public final static class Opens
+        implements Comparable<Opens>
+    {
         /**
-         * A modifier on a module <em>opens</em> directive.
+         * A modifier on an open package.
          *
+         * @see Opens#modifiers()
          * @since 9
+         * @spec JPMS
          */
         public static enum Modifier {
 
             /**
-             * The opens was not explicitly or implicitly declared in the
-             * source of the module declaration.
+             * The open package was not explicitly or implicitly declared in
+             * the source of the module declaration.
              */
             SYNTHETIC,
 
             /**
-             * The opens was implicitly declared in the source of the module
-             * declaration.
+             * The open package was implicitly declared in the source of the
+             * module declaration.
              */
             MANDATED;
 
@@ -544,6 +642,52 @@
         }
 
         /**
+         * Compares this module opens to another.
+         *
+         * <p> Two {@code Opens} objects are compared by comparing the package
+         * names lexicographically. Where the packages names are equal then the
+         * sets of modifiers are compared in the same way that module modifiers
+         * are compared (see {@link ModuleDescriptor#compareTo
+         * ModuleDescriptor.compareTo}). Where the package names are equal and
+         * the set of modifiers are equal then the set of target modules are
+         * compared. This is done by sorting the names of the target modules
+         * in ascending order, and according to their natural ordering, and then
+         * comparing the corresponding elements lexicographically. Where the
+         * sets differ in size, and the larger set contains all elements of the
+         * smaller set, then the larger set is considered to succeed the smaller
+         * set. </p>
+         *
+         * @param  that
+         *         The module opens to compare
+         *
+         * @return A negative integer, zero, or a positive integer if this module
+         *         opens is less than, equal to, or greater than the given
+         *         module opens
+         */
+        @Override
+        public int compareTo(Opens that) {
+            if (this == that) return 0;
+
+            int c = source.compareTo(that.source);
+            if (c != 0)
+                return c;
+
+            // modifiers
+            long v1 = modsValue(this.modifiers());
+            long v2 = modsValue(that.modifiers());
+            c = Long.compare(v1, v2);
+            if (c != 0)
+                return c;
+
+            // targets
+            c = compare(targets, that.targets);
+            if (c != 0)
+                return c;
+
+            return 0;
+        }
+
+        /**
          * Computes a hash code for this module opens.
          *
          * <p> The hash code is based upon the modifiers, the package name,
@@ -588,9 +732,9 @@
         }
 
         /**
-         * Returns a string describing module opens.
+         * Returns a string describing the open package.
          *
-         * @return A string describing module opens
+         * @return A string describing the open package
          */
         @Override
         public String toString() {
@@ -608,10 +752,12 @@
      *
      * @see ModuleDescriptor#provides()
      * @since 9
+     * @spec JPMS
      */
 
-    public final static class Provides {
-
+    public final static class Provides
+        implements Comparable<Provides>
+    {
         private final String service;
         private final List<String> providers;
 
@@ -642,6 +788,46 @@
         public List<String> providers() { return providers; }
 
         /**
+         * Compares this provides to another.
+         *
+         * <p> Two {@code Provides} objects are compared by comparing the fully
+         * qualified class name of the service type lexicographically. Where the
+         * class names are equal then the list of the provider class names are
+         * compared by comparing the corresponding elements of both lists
+         * lexicographically and in sequence. Where the lists differ in size,
+         * {@code N} is the size of the shorter list, and the first {@code N}
+         * corresponding elements are equal, then the longer list is considered
+         * to succeed the shorter list. </p>
+         *
+         * @param  that
+         *         The {@code Provides} to compare
+         *
+         * @return A negative integer, zero, or a positive integer if this provides
+         *         is less than, equal to, or greater than the given provides
+         */
+        public int compareTo(Provides that) {
+            if (this == that) return 0;
+
+            int c = service.compareTo(that.service);
+            if (c != 0) return c;
+
+            // compare provider class names in sequence
+            int size1 = this.providers.size();
+            int size2 = that.providers.size();
+            for (int index=0; index<Math.min(size1, size2); index++) {
+                String e1 = this.providers.get(index);
+                String e2 = that.providers.get(index);
+                c = e1.compareTo(e2);
+                if (c != 0) return c;
+            }
+            if (size1 == size2) {
+                return 0;
+            } else {
+                return (size1 > size2) ? 1 : -1;
+            }
+        }
+
+        /**
          * Computes a hash code for this provides.
          *
          * <p> The hash code is based upon the service type and the set of
@@ -699,7 +885,7 @@
      *
      * <p> A version string has three components: The version number itself, an
      * optional pre-release version, and an optional build version.  Each
-     * component is sequence of tokens; each token is either a non-negative
+     * component is a sequence of tokens; each token is either a non-negative
      * integer or a string.  Tokens are separated by the punctuation characters
      * {@code '.'}, {@code '-'}, or {@code '+'}, or by transitions from a
      * sequence of digits to a sequence of characters that are neither digits
@@ -740,6 +926,7 @@
      *
      * @see ModuleDescriptor#version()
      * @since 9
+     * @spec JPMS
      */
 
     public final static class Version
@@ -1009,36 +1196,26 @@
 
     }
 
-
+
     private final String name;
     private final Version version;
-    private final boolean open;
-
-    // Indicates if synthesised for a JAR file found on the module path
-    private final boolean automatic;
-
-    // Not generated from a module-info.java
-    private final boolean synthetic;
-
+    private final Set<Modifier> modifiers;
+    private final boolean open;  // true if modifiers contains OPEN
+    private final boolean automatic;  // true if modifiers contains AUTOMATIC
     private final Set<Requires> requires;
     private final Set<Exports> exports;
     private final Set<Opens> opens;
     private final Set<String> uses;
     private final Set<Provides> provides;
-
-    // Added post-compilation by tools
     private final Set<String> packages;
     private final String mainClass;
     private final String osName;
     private final String osArch;
     private final String osVersion;
 
-
     private ModuleDescriptor(String name,
                              Version version,
-                             boolean open,
-                             boolean automatic,
-                             boolean synthetic,
+                             Set<Modifier> modifiers,
                              Set<Requires> requires,
                              Set<Exports> exports,
                              Set<Opens> opens,
@@ -1052,10 +1229,9 @@
     {
         this.name = name;
         this.version = version;
-        this.open = open;
-        this.automatic = automatic;
-        this.synthetic = synthetic;
-
+        this.modifiers = emptyOrUnmodifiableSet(modifiers);
+        this.open = modifiers.contains(Modifier.OPEN);
+        this.automatic = modifiers.contains(Modifier.AUTOMATIC);
         assert (requires.stream().map(Requires::name).distinct().count()
                 == requires.size());
         this.requires = emptyOrUnmodifiableSet(requires);
@@ -1072,40 +1248,12 @@
     }
 
     /**
-     * Clones the given module descriptor with an augmented set of packages
-     */
-    ModuleDescriptor(ModuleDescriptor md, Set<String> pkgs) {
-        this.name = md.name;
-        this.version = md.version;
-        this.open = md.open;
-        this.automatic = md.automatic;
-        this.synthetic = md.synthetic;
-
-        this.requires = md.requires;
-        this.exports = md.exports;
-        this.opens = md.opens;
-        this.uses = md.uses;
-        this.provides = md.provides;
-
-        Set<String> packages = new HashSet<>(md.packages);
-        packages.addAll(pkgs);
-        this.packages = emptyOrUnmodifiableSet(packages);
-
-        this.mainClass = md.mainClass;
-        this.osName = md.osName;
-        this.osArch = md.osArch;
-        this.osVersion = md.osVersion;
-    }
-
-    /**
      * Creates a module descriptor from its components.
      * The arguments are pre-validated and sets are unmodifiable sets.
      */
     ModuleDescriptor(String name,
                      Version version,
-                     boolean open,
-                     boolean automatic,
-                     boolean synthetic,
+                     Set<Modifier> modifiers,
                      Set<Requires> requires,
                      Set<Exports> exports,
                      Set<Opens> opens,
@@ -1120,9 +1268,9 @@
                      boolean unused) {
         this.name = name;
         this.version = version;
-        this.open = open;
-        this.automatic = automatic;
-        this.synthetic = synthetic;
+        this.modifiers = modifiers;
+        this.open = modifiers.contains(Modifier.OPEN);
+        this.automatic = modifiers.contains(Modifier.AUTOMATIC);
         this.requires = requires;
         this.exports = exports;
         this.opens = opens;
@@ -1137,7 +1285,7 @@
     }
 
     /**
-     * <p> The module name. </p>
+     * <p> Returns the module name. </p>
      *
      * @return The module name
      */
@@ -1146,11 +1294,19 @@
     }
 
     /**
+     * <p> Returns the set of module modifiers. </p>
+     *
+     * @return A possibly-empty unmodifiable set of modifiers
+     */
+    public Set<Modifier> modifiers() {
+        return modifiers;
+    }
+
+    /**
      * <p> Returns {@code true} if this is an open module. </p>
      *
-     * <p> An open module does not declare any open packages (the {@link #opens()
-     * opens} method returns an empty set) but the resulting module is treated
-     * as if all packages are open. </p>
+     * <p> This method is equivalent to testing if the set of {@link #modifiers
+     * modifiers} contains the {@link Modifier#OPEN OPEN} modifier. </p>
      *
      * @return  {@code true} if this is an open module
      */
@@ -1161,12 +1317,8 @@
     /**
      * <p> Returns {@code true} if this is an automatic module. </p>
      *
-     * <p> An automatic module is defined implicitly rather than explicitly
-     * and therefore does not have a module declaration. JAR files located on
-     * the application module path, or by the {@link ModuleFinder} returned by
-     * {@link ModuleFinder#of(java.nio.file.Path[]) ModuleFinder.of}, are
-     * treated as automatic modules if they do have not have a module
-     * declaration. </p>
+     * <p> This method is equivalent to testing if the set of {@link #modifiers
+     * modifiers} contains the {@link Modifier#OPEN AUTOMATIC} modifier. </p>
      *
      * @return  {@code true} if this is an automatic module
      */
@@ -1175,20 +1327,13 @@
     }
 
     /**
-     * <p> Returns {@code true} if this module descriptor was not generated
-     * from an explicit module declaration ({@code module-info.java})
-     * or an implicit module declaration (an {@link #isAutomatic() automatic}
-     * module). </p>
+     * <p> Returns the set of {@code Requires} objects representing the module
+     * dependences. </p>
      *
-     * @return  {@code true} if this module descriptor was not generated by
-     *          an explicit or implicit module declaration
-     */
-    public boolean isSynthetic() {
-        return synthetic;
-    }
-
-    /**
-     * <p> The dependences of this module. </p>
+     * <p> The set includes a dependency on "{@code java.base}" when this
+     * module is not named "{@code java.base}". If this module is an automatic
+     * module then it does not have a dependency on any module other than
+     * "{@code java.base}". </p>
      *
      * @return  A possibly-empty unmodifiable set of {@link Requires} objects
      */
@@ -1197,7 +1342,11 @@
     }
 
     /**
-     * <p> The module exports. </p>
+     * <p> Returns the set of {@code Exports} objects representing the exported
+     * packages. </p>
+     *
+     * <p> If this module is an automatic module then the set of exports
+     * is empty. </p>
      *
      * @return  A possibly-empty unmodifiable set of exported packages
      */
@@ -1206,16 +1355,11 @@
     }
 
     /**
-     * <p> The module <em>opens</em> directives. </p>
+     * <p> Returns the set of {@code Opens} objects representing the open
+     * packages. </p>
      *
-     * <p> Each {@code Opens} object in the set represents a package (and
-     * the set of target module names when qualified) where all types in the
-     * package, and all their members, not just public types and their public
-     * members, can be reflected on when using APIs that bypass or suppress
-     * default Java language access control checks. </p>
-     *
-     * <p> This method returns an empty set when invoked on {@link #isOpen()
-     * open} module. </p>
+     * <p> If this module is an open module or an automatic module then the
+     * set of open packages is empty. </p>
      *
      * @return  A possibly-empty unmodifiable set of open packages
      */
@@ -1224,7 +1368,10 @@
     }
 
     /**
-     * <p> The service dependences of this module. </p>
+     * <p> Returns the set of service dependences. </p>
+     *
+     * <p> If this module is an automatic module then the set of service
+     * dependences is empty. </p>
      *
      * @return  A possibly-empty unmodifiable set of the fully qualified class
      *          names of the service types used
@@ -1234,7 +1381,8 @@
     }
 
     /**
-     * <p> The services that this module provides. </p>
+     * <p> Returns the set of {@code Provides} objects representing the
+     * services that the module provides. </p>
      *
      * @return The possibly-empty unmodifiable set of the services that this
      *         module provides
@@ -1244,7 +1392,7 @@
     }
 
     /**
-     * Returns this module's version.
+     * <p> Returns the module version. </p>
      *
      * @return This module's version
      */
@@ -1253,10 +1401,10 @@
     }
 
     /**
-     * Returns a string containing this module's name and, if present, its
-     * version.
+     * <p> Returns a string containing the module name and, if present, its
+     * version. </p>
      *
-     * @return A string containing this module's name and, if present, its
+     * @return A string containing the module name and, if present, its
      *         version.
      */
     public String toNameAndVersion() {
@@ -1268,51 +1416,51 @@
     }
 
     /**
-     * Returns the module's main class.
+     * <p> Returns the module main class. </p>
      *
-     * @return The fully qualified class name of this module's main class
+     * @return The fully qualified class name of the module's main class
      */
     public Optional<String> mainClass() {
         return Optional.ofNullable(mainClass);
     }
 
     /**
-     * Returns the operating system name if this module is operating system
+     * Returns the operating system name if the module is operating system
      * specific.
      *
      * @return The operating system name or an empty {@code Optional}
-     *         if this module is not operating system specific
+     *         if the module is not operating system specific
      */
     public Optional<String> osName() {
         return Optional.ofNullable(osName);
     }
 
     /**
-     * Returns the operating system architecture if this module is operating
+     * Returns the operating system architecture if the module is operating
      * system architecture specific.
      *
      * @return The operating system architecture or an empty {@code Optional}
-     *         if this module is not operating system architecture specific
+     *         if the module is not operating system architecture specific
      */
     public Optional<String> osArch() {
         return Optional.ofNullable(osArch);
     }
 
     /**
-     * Returns the operating system version if this module is operating
+     * Returns the operating system version if the module is operating
      * system version specific.
      *
      * @return The operating system version or an empty {@code Optional}
-     *         if this module is not operating system version specific
+     *         if the module is not operating system version specific
      */
     public Optional<String> osVersion() {
         return Optional.ofNullable(osVersion);
     }
 
     /**
-     * Returns the names of all packages in this module.
+     * Returns the set of packages in the module.
      *
-     * @return A possibly-empty unmodifiable set of all packages in the module
+     * @return A possibly-empty unmodifiable set of the packages in the module
      */
     public Set<String> packages() {
         return packages;
@@ -1320,37 +1468,53 @@
 
 
     /**
-     * A builder used for building {@link ModuleDescriptor} objects.
+     * A builder for building {@link ModuleDescriptor} objects.
+     *
+     * <p> {@code ModuleDescriptor} defines the {@link #newModule newModule},
+     * {@link #newOpenModule newOpenModule}, and {@link #newAutomaticModule
+     * newAutomaticModule} methods to create builders for building
+     * <em>normal</em>, open, and automatic modules. </p>
      *
-     * <p> {@code ModuleDescriptor} defines the {@link #module module}, {@link
-     * #openModule openModule}, and {@link #automaticModule automaticModule}
-     * methods to create builders for building different kinds of modules. </p>
+     * <p> The set of packages in the module are accumulated by the {@code
+     * Builder} as the {@link ModuleDescriptor.Builder#exports(String) exports},
+     * {@link ModuleDescriptor.Builder#opens(String) opens},
+     * {@link ModuleDescriptor.Builder#packages(Set) packages},
+     * {@link ModuleDescriptor.Builder#provides(String,List) provides}, and
+     * {@link ModuleDescriptor.Builder#mainClass(String) mainClass} methods are
+     * invoked. </p>
+     *
+     * <p> The module names, package names, and class names that are parameters
+     * specified to the builder methods are the module names, package names,
+     * and qualified names of classes (in named packages) as defined in the
+     * <cite>The Java&trade; Language Specification</cite>. </p>
      *
      * <p> Example usage: </p>
-     * <pre>{@code    ModuleDescriptor descriptor = ModuleDescriptor.module("m1")
-     *         .exports("p")
-     *         .requires("m2")
+     * <pre>{@code    ModuleDescriptor descriptor = ModuleDescriptor.newModule("stats.core")
+     *         .requires("java.base")
+     *         .exports("org.acme.stats.core.clustering")
+     *         .exports("org.acme.stats.core.regression")
+     *         .packages(Set.of("org.acme.stats.core.internal"))
      *         .build();
      * }</pre>
      *
      * @apiNote A {@code Builder} checks the components and invariants as
-     * components are added to the builder. The rational for this is to detect
+     * components are added to the builder. The rationale for this is to detect
      * errors as early as possible and not defer all validation to the
-     * {@link #build build} method. A {@code Builder} cannot be used to create
-     * a {@link ModuleDescriptor#isSynthetic() synthetic} module.
+     * {@link #build build} method.
      *
      * @since 9
+     * @spec JPMS
      */
     public static final class Builder {
         final String name;
-        final boolean strict; // true if module names are checked
+        final boolean strict;
+        final Set<Modifier> modifiers;
         final boolean open;
-        final boolean synthetic;
-        boolean automatic;
+        final boolean automatic;
+        final Set<String> packages = new HashSet<>();
         final Map<String, Requires> requires = new HashMap<>();
         final Map<String, Exports> exports = new HashMap<>();
         final Map<String, Opens> opens = new HashMap<>();
-        final Set<String> concealedPackages = new HashSet<>();
         final Set<String> uses = new HashSet<>();
         final Map<String, Provides> provides = new HashMap<>();
         Version version;
@@ -1362,35 +1526,25 @@
         /**
          * Initializes a new builder with the given module name.
          *
-         * @param strict
-         *        Indicates whether module names are checked or not
+         * If {@code strict} is {@code true} then module, package, and class
+         * names are checked to ensure they are legal names. In addition, the
+         * {@link #build buid} method will add "{@code requires java.base}" if
+         * the dependency is not declared.
          */
-        Builder(String name, boolean strict, boolean open, boolean synthetic) {
+        Builder(String name, boolean strict, Set<Modifier> modifiers) {
             this.name = (strict) ? requireModuleName(name) : name;
             this.strict = strict;
-            this.open = open;
-            this.synthetic = synthetic;
-        }
-
-        /* package */ Builder automatic(boolean automatic) {
-            this.automatic = automatic;
-            return this;
+            this.modifiers = modifiers;
+            this.open = modifiers.contains(Modifier.OPEN);
+            this.automatic = modifiers.contains(Modifier.AUTOMATIC);
+            assert !open || !automatic;
         }
 
         /**
-         * Returns the set of packages that are exported (unconditionally or
-         * unconditionally).
+         * Returns a snapshot of the packages in the module.
          */
-        /* package */ Set<String> exportedPackages() {
-            return exports.keySet();
-        }
-
-        /**
-         * Returns the set of packages that are opened (unconditionally or
-         * unconditionally).
-         */
-        /* package */Set<String> openPackages() {
-            return opens.keySet();
+        /* package */ Set<String> packages() {
+            return Collections.unmodifiableSet(packages);
         }
 
         /**
@@ -1406,8 +1560,12 @@
          *         initialized to build
          * @throws IllegalStateException
          *         If the dependence on the module has already been declared
+         *         or this builder is for an automatic module
          */
         public Builder requires(Requires req) {
+            if (automatic)
+                throw new IllegalStateException("Automatic modules cannot declare"
+                                                + " dependences");
             String mn = req.name();
             if (name.equals(mn))
                 throw new IllegalArgumentException("Dependence on self");
@@ -1433,11 +1591,12 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If the module name is {@code null}, is not a legal Java
-         *         identifier, or is equal to the module name that this builder
+         *         If the module name is {@code null}, is not a legal module
+         *         name, or is equal to the module name that this builder
          *         was initialized to build
          * @throws IllegalStateException
          *         If the dependence on the module has already been declared
+         *         or this builder is for an automatic module
          */
         public Builder requires(Set<Requires.Modifier> ms,
                                 String mn,
@@ -1448,6 +1607,23 @@
             return requires(new Requires(ms, mn, compiledVersion));
         }
 
+        /* package */Builder requires(Set<Requires.Modifier> ms,
+                                      String mn,
+                                      String compiledVersion) {
+            Version v = null;
+            try {
+                v = Version.parse(compiledVersion);
+            } catch (IllegalArgumentException e) {
+                // for now, drop un-parsable version when non-strict
+                if (strict) throw e;
+            }
+            if (v == null) {
+                return requires(ms, mn);
+            } else {
+                return requires(ms, mn, v);
+            }
+        }
+
         /**
          * Adds a dependence on a module with the given (and possibly empty)
          * set of modifiers.
@@ -1460,11 +1636,12 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If the module name is {@code null}, is not a legal Java
-         *         identifier, or is equal to the module name that this builder
+         *         If the module name is {@code null}, is not a legal module
+         *         name, or is equal to the module name that this builder
          *         was initialized to build
          * @throws IllegalStateException
          *         If the dependence on the module has already been declared
+         *         or this builder is for an automatic module
          */
         public Builder requires(Set<Requires.Modifier> ms, String mn) {
             if (strict)
@@ -1481,18 +1658,19 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If the module name is {@code null}, is not a legal Java
-         *         identifier, or is equal to the module name that this builder
+         *         If the module name is {@code null}, is not a legal module
+         *         name, or is equal to the module name that this builder
          *         was initialized to build
          * @throws IllegalStateException
          *         If the dependence on the module has already been declared
+         *         or this builder is for an automatic module
          */
         public Builder requires(String mn) {
             return requires(EnumSet.noneOf(Requires.Modifier.class), mn);
         }
 
         /**
-         * Adds an export.
+         * Adds an exported package.
          *
          * @param  e
          *         The export
@@ -1500,29 +1678,27 @@
          * @return This builder
          *
          * @throws IllegalStateException
-         *         If the package is already declared as a package with the
-         *         {@link #contains contains} method or the package is already
-         *         declared as exported
+         *         If the {@link Exports#source package} is already declared as
+         *         exported or this builder is for an automatic module
          */
         public Builder exports(Exports e) {
-            // can't be exported and concealed
+            if (automatic) {
+                throw new IllegalStateException("Automatic modules cannot declare"
+                                                 + " exported packages");
+            }
             String source = e.source();
-            if (concealedPackages.contains(source)) {
-                throw new IllegalStateException("Package " + source
-                                                 + " already declared");
-            }
             if (exports.containsKey(source)) {
                 throw new IllegalStateException("Exported package " + source
                                                  + " already declared");
             }
-
             exports.put(source, e);
+            packages.add(source);
             return this;
         }
 
         /**
-         * Adds an export, with the given (and possibly empty) set of modifiers,
-         * to export a package to a set of target modules.
+         * Adds an exported package with the given (and possibly empty) set of
+         * modifiers. The package is exported to a set of target modules.
          *
          * @param  ms
          *         The set of modifiers
@@ -1534,33 +1710,34 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If the package name or any of the target modules is {@code
-         *         null} or is not a legal Java identifier, or the set of
-         *         targets is empty
+         *         If the package name is {@code null} or is not a legal
+         *         package name, the set of target modules is empty, or the set
+         *         of target modules contains a name that is not a legal module
+         *         name
          * @throws IllegalStateException
-         *         If the package is already declared as a package with the
-         *         {@link #contains contains} method or the package is already
-         *         declared as exported
+         *         If the package is already declared as exported
+         *         or this builder is for an automatic module
          */
         public Builder exports(Set<Exports.Modifier> ms,
                                String pn,
                                Set<String> targets)
         {
-            Exports e = new Exports(ms, requirePackageName(pn), targets);
+            Exports e = new Exports(ms, pn, targets);
 
             // check targets
             targets = e.targets();
             if (targets.isEmpty())
                 throw new IllegalArgumentException("Empty target set");
-            if (strict)
+            if (strict) {
+                requirePackageName(e.source());
                 targets.stream().forEach(Checks::requireModuleName);
-
+            }
             return exports(e);
         }
 
         /**
-         * Adds an unqualified export with the given (and possibly empty) set
-         * of modifiers.
+         * Adds an exported package with the given (and possibly empty) set of
+         * modifiers. The package is exported to all modules.
          *
          * @param  ms
          *         The set of modifiers
@@ -1570,20 +1747,23 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If the package name is {@code null} or is not a legal Java
-         *         identifier
+         *         If the package name is {@code null} or is not a legal
+         *         package name
          * @throws IllegalStateException
-         *         If the package is already declared as a package with the
-         *         {@link #contains contains} method or the package is already
-         *         declared as exported
+         *         If the package is already declared as exported
+         *         or this builder is for an automatic module
          */
         public Builder exports(Set<Exports.Modifier> ms, String pn) {
-            Exports e = new Exports(ms, requirePackageName(pn), Collections.emptySet());
+            if (strict) {
+                requirePackageName(pn);
+            }
+            Exports e = new Exports(ms, pn, Collections.emptySet());
             return exports(e);
         }
 
         /**
-         * Adds an export to export a package to a set of target modules.
+         * Adds an exported package. The package is exported to a set of target
+         * modules.
          *
          * @param  pn
          *         The package name
@@ -1593,20 +1773,20 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If the package name or any of the target modules is {@code
-         *         null} or is not a legal Java identifier, or the set of
-         *         targets is empty
+         *         If the package name is {@code null} or is not a legal
+         *         package name, the set of target modules is empty, or the set
+         *         of target modules contains a name that is not a legal module
+         *         name
          * @throws IllegalStateException
-         *         If the package is already declared as a package with the
-         *         {@link #contains contains} method or the package is already
-         *         declared as exported
+         *         If the package is already declared as exported
+         *         or this builder is for an automatic module
          */
         public Builder exports(String pn, Set<String> targets) {
             return exports(Collections.emptySet(), pn, targets);
         }
 
         /**
-         * Adds an unqualified export.
+         * Adds an exported package. The package is exported to all modules.
          *
          * @param  pn
          *         The package name
@@ -1614,19 +1794,18 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If the package name is {@code null} or is not a legal Java
-         *         identifier
+         *         If the package name is {@code null} or is not a legal
+         *         package name
          * @throws IllegalStateException
-         *         If the package is already declared as a package with the
-         *         {@link #contains contains} method or the package is already
-         *         declared as exported
+         *         If the package is already declared as exported
+         *         or this builder is for an automatic module
          */
         public Builder exports(String pn) {
             return exports(Collections.emptySet(), pn);
         }
 
         /**
-         * Adds an <em>opens</em> directive.
+         * Adds an open package.
          *
          * @param  obj
          *         The {@code Opens} object
@@ -1634,35 +1813,28 @@
          * @return This builder
          *
          * @throws IllegalStateException
-         *         If the package is already declared as a package with the
-         *         {@link #contains contains} method, the package is already
-         *         declared as open, or this is a builder for an open module
+         *         If the package is already declared as open, or this is a
+         *         builder for an open module or automatic module
          */
         public Builder opens(Opens obj) {
-            if (open) {
-                throw new IllegalStateException("open modules cannot declare"
-                                                + " open packages");
+            if (open || automatic) {
+                throw new IllegalStateException("Open or automatic modules cannot"
+                                                + " declare open packages");
             }
-
-            // can't be open and concealed
             String source = obj.source();
-            if (concealedPackages.contains(source)) {
-                throw new IllegalStateException("Package " + source
-                                                + " already declared");
-            }
             if (opens.containsKey(source)) {
                 throw new IllegalStateException("Open package " + source
                                                 + " already declared");
             }
-
             opens.put(source, obj);
+            packages.add(source);
             return this;
         }
 
 
         /**
-         * Adds an <em>opens</em> directive, with the given (and possibly empty)
-         * set of modifiers, to open a package to a set of target modules.
+         * Adds an open package with the given (and possibly empty) set of
+         * modifiers. The package is open to a set of target modules.
          *
          * @param  ms
          *         The set of modifiers
@@ -1674,33 +1846,34 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If the package name or any of the target modules is {@code
-         *         null} or is not a legal Java identifier, or the set of
-         *         targets is empty
+         *         If the package name is {@code null} or is not a legal
+         *         package name, the set of target modules is empty, or the set
+         *         of target modules contains a name that is not a legal module
+         *         name
          * @throws IllegalStateException
-         *         If the package is already declared as a package with the
-         *         {@link #contains contains} method, the package is already
-         *         declared as open, or this is a builder for an open module
+         *         If the package is already declared as open, or this is a
+         *         builder for an open module or automatic module
          */
         public Builder opens(Set<Opens.Modifier> ms,
                              String pn,
                              Set<String> targets)
         {
-            Opens e = new Opens(ms, requirePackageName(pn), targets);
+            Opens opens = new Opens(ms, pn, targets);
 
             // check targets
-            targets = e.targets();
+            targets = opens.targets();
             if (targets.isEmpty())
                 throw new IllegalArgumentException("Empty target set");
-            if (strict)
+            if (strict) {
+                requirePackageName(opens.source());
                 targets.stream().forEach(Checks::requireModuleName);
-
-            return opens(e);
+            }
+            return opens(opens);
         }
 
         /**
-         * Adds an <em>opens</em> directive to open a package with the given (and
-         * possibly empty) set of modifiers.
+         * Adds an open package with the given (and possibly empty) set of
+         * modifiers. The package is open to all modules.
          *
          * @param  ms
          *         The set of modifiers
@@ -1710,21 +1883,22 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If the package name is {@code null} or is not a legal Java
-         *         identifier
+         *         If the package name is {@code null} or is not a legal
+         *         package name
          * @throws IllegalStateException
-         *         If the package is already declared as a package with the
-         *         {@link #contains contains} method, the package is already
-         *         declared as open, or this is a builder for an open module
+         *         If the package is already declared as open, or this is a
+         *         builder for an open module or automatic module
          */
         public Builder opens(Set<Opens.Modifier> ms, String pn) {
-            Opens e = new Opens(ms, requirePackageName(pn), Collections.emptySet());
+            if (strict) {
+                requirePackageName(pn);
+            }
+            Opens e = new Opens(ms, pn, Collections.emptySet());
             return opens(e);
         }
 
         /**
-         * Adds an <em>opens</em> directive to open a package to a set of target
-         * modules.
+         * Adds an open package. The package is open to a set of target modules.
          *
          * @param  pn
          *         The package name
@@ -1734,20 +1908,20 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If the package name or any of the target modules is {@code
-         *         null} or is not a legal Java identifier, or the set of
-         *         targets is empty
+         *         If the package name is {@code null} or is not a legal
+         *         package name, the set of target modules is empty, or the set
+         *         of target modules contains a name that is not a legal module
+         *         name
          * @throws IllegalStateException
-         *         If the package is already declared as a package with the
-         *         {@link #contains contains} method, the package is already
-         *         declared as open, or this is a builder for an open module
+         *         If the package is already declared as open, or this is a
+         *         builder for an open module or automatic module
          */
         public Builder opens(String pn, Set<String> targets) {
             return opens(Collections.emptySet(), pn, targets);
         }
 
         /**
-         * Adds an <em>opens</em> directive to open a package.
+         * Adds an open package. The package is open to all modules.
          *
          * @param  pn
          *         The package name
@@ -1755,12 +1929,11 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If the package name is {@code null} or is not a legal Java
-         *         identifier
+         *         If the package name is {@code null} or is not a legal
+         *         package name
          * @throws IllegalStateException
-         *         If the package is already declared as a package with the
-         *         {@link #contains contains} method, the package is already
-         *         declared as open, or this is a builder for an open module
+         *         If the package is already declared as open, or this is a
+         *         builder for an open module or automatic module
          */
         public Builder opens(String pn) {
             return opens(Collections.emptySet(), pn);
@@ -1775,12 +1948,16 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If the service type is {@code null} or is not a legal Java
-         *         identifier
+         *         If the service type is {@code null} or not a qualified name of
+         *         a class in a named package
          * @throws IllegalStateException
          *         If a dependency on the service type has already been declared
+         *         or this is a builder for an an automatic module
          */
         public Builder uses(String service) {
+            if (automatic)
+                throw new IllegalStateException("Automatic modules can not declare"
+                                                + " service dependences");
             if (uses.contains(requireServiceTypeName(service)))
                 throw new IllegalStateException("Dependence upon service "
                                                 + service + " already declared");
@@ -1789,7 +1966,9 @@
         }
 
         /**
-         * Provides a service with one or more implementations.
+         * Provides a service with one or more implementations. The package for
+         * each {@link Provides#providers provider} (or provider factory) is
+         * added to the module if not already added.
          *
          * @param  p
          *         The provides
@@ -1801,16 +1980,18 @@
          *         declared
          */
         public Builder provides(Provides p) {
-            String st = p.service();
-            if (provides.containsKey(st))
+            String service = p.service();
+            if (provides.containsKey(service))
                 throw new IllegalStateException("Providers of service "
-                                                + st + " already declared");
-            provides.put(st, p);
+                                                + service + " already declared");
+            provides.put(service, p);
+            p.providers().forEach(name -> packages.add(packageName(name)));
             return this;
         }
 
         /**
-         * Provides implementations of a service.
+         * Provides implementations of a service. The package for each provider
+         * (or provider factory) is added to the module if not already added.
          *
          * @param  service
          *         The service type
@@ -1821,103 +2002,59 @@
          *
          * @throws IllegalArgumentException
          *         If the service type or any of the provider class names is
-         *         {@code null} or is not a legal Java identifier, or the list
-         *         of provider class names is empty
+         *         {@code null} or not a qualified name of a class in a named
+         *         package, or the list of provider class names is empty
          * @throws IllegalStateException
          *         If the providers for the service type have already been
          *         declared
          */
         public Builder provides(String service, List<String> providers) {
-            if (provides.containsKey(service))
-                throw new IllegalStateException("Providers of service "
-                                                + service + " already declared by " + name);
-
-            Provides p = new Provides(requireServiceTypeName(service), providers);
+            Provides p = new Provides(service, providers);
 
             // check providers after the set has been copied.
             List<String> providerNames = p.providers();
             if (providerNames.isEmpty())
                 throw new IllegalArgumentException("Empty providers set");
-            providerNames.forEach(Checks::requireServiceProviderName);
-            provides.put(service, p);
-            return this;
+            if (strict) {
+                requireServiceTypeName(p.service());
+                providerNames.forEach(Checks::requireServiceProviderName);
+            } else {
+                // Disallow service/providers in unnamed package
+                String pn = packageName(service);
+                if (pn.isEmpty()) {
+                    throw new IllegalArgumentException(service
+                                                       + ": unnamed package");
+                }
+                for (String name : providerNames) {
+                    pn = packageName(name);
+                    if (pn.isEmpty()) {
+                        throw new IllegalArgumentException(name
+                                                           + ": unnamed package");
+                    }
+                }
+            }
+            return provides(p);
         }
 
         /**
-         * Provides an implementation of a service.
-         *
-         * @param  service
-         *         The service type
-         * @param  provider
-         *         The provider or provider factory class name
-         *
-         * @return This builder
-         *
-         * @throws IllegalArgumentException
-         *         If the service type or the provider class name is {@code
-         *         null} or is not a legal Java identifier
-         * @throws IllegalStateException
-         *         If the providers for the service type have already been
-         *         declared
-         */
-        public Builder provides(String service, String provider) {
-            if (provider == null)
-                throw new IllegalArgumentException("'provider' is null");
-            return provides(service, List.of(provider));
-        }
-
-        /**
-         * Adds a (possible empty) set of packages to the module
+         * Adds packages to the module. All packages in the set of package names
+         * that are not in the module are added to module.
          *
          * @param  pns
-         *         The set of package names
+         *         The (possibly empty) set of package names
          *
          * @return This builder
          *
          * @throws IllegalArgumentException
          *         If any of the package names is {@code null} or is not a
-         *         legal Java identifier
-         * @throws IllegalStateException
-         *         If any of packages are already declared as packages in
-         *         the module. This includes packages that are already
-         *         declared as exported or open packages.
+         *         legal package name
          */
-        public Builder contains(Set<String> pns) {
-            pns.forEach(this::contains);
-            return this;
-        }
-
-        /**
-         * Adds a package to the module.
-         *
-         * @param  pn
-         *         The package name
-         *
-         * @return This builder
-         *
-         * @throws IllegalArgumentException
-         *         If the package name is {@code null}, or is not a legal Java
-         *         identifier
-         * @throws IllegalStateException
-         *         If the package is already declared as a package in the
-         *         module. This includes the package already declared as an
-         *         exported or open package.
-         */
-        public Builder contains(String pn) {
-            Checks.requirePackageName(pn);
-            if (concealedPackages.contains(pn)) {
-                throw new IllegalStateException("Package " + pn
-                                                + " already declared");
+        public Builder packages(Set<String> pns) {
+            if (strict) {
+                pns = new HashSet<>(pns);
+                pns.forEach(Checks::requirePackageName);
             }
-            if (exports.containsKey(pn)) {
-                throw new IllegalStateException("Exported package "
-                                                + pn + " already declared");
-            }
-            if (opens.containsKey(pn)) {
-                throw new IllegalStateException("Open package "
-                                                 + pn + " already declared");
-            }
-            concealedPackages.add(pn);
+            this.packages.addAll(pns);
             return this;
         }
 
@@ -1937,22 +2074,35 @@
         /**
          * Sets the module version.
          *
-         * @param  v
+         * @param  vs
          *         The version string to parse
          *
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If {@code v} is null or cannot be parsed as a version string
+         *         If {@code vs} is {@code null} or cannot be parsed as a
+         *         version string
          *
          * @see Version#parse(String)
          */
-        public Builder version(String v) {
-            return version(Version.parse(v));
+        public Builder version(String vs) {
+            Version v;
+            if (strict) {
+                v = Version.parse(vs);
+            } else {
+                try {
+                    v = Version.parse(vs);
+                } catch (IllegalArgumentException ignore) {
+                    // for now, ignore when non-strict
+                    return this;
+                }
+            }
+            return version(v);
         }
 
         /**
-         * Sets the module main class.
+         * Sets the module main class. The package for the main class is added
+         * to the module if not already added.
          *
          * @param  mc
          *         The module main class
@@ -1960,10 +2110,24 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If {@code mainClass} is null or is not a legal Java identifier
+         *         If {@code mainClass} is {@code null} or not a qualified
+         *         name of a class in a named package
          */
         public Builder mainClass(String mc) {
-            mainClass = requireBinaryName("main class name", mc);
+            String pn;
+            if (strict) {
+                mc = requireQualifiedClassName("main class name", mc);
+                pn = packageName(mc);
+                assert !pn.isEmpty();
+            } else {
+                // Disallow main class in unnamed package
+                pn = packageName(mc);
+                if (pn.isEmpty()) {
+                    throw new IllegalArgumentException(mc + ": unnamed package");
+                }
+            }
+            mainClass = mc;
+            packages.add(pn);
             return this;
         }
 
@@ -1976,7 +2140,7 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If {@code name} is null or the empty String
+         *         If {@code name} is {@code null} or the empty String
          */
         public Builder osName(String name) {
             if (name == null || name.isEmpty())
@@ -1994,7 +2158,7 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If {@code name} is null or the empty String
+         *         If {@code name} is {@code null} or the empty String
          */
         public Builder osArch(String arch) {
             if (arch == null || arch.isEmpty())
@@ -2012,7 +2176,7 @@
          * @return This builder
          *
          * @throws IllegalArgumentException
-         *         If {@code name} is null or the empty String
+         *         If {@code name} is {@code null} or the empty String
          */
         public Builder osVersion(String version) {
             if (version == null || version.isEmpty())
@@ -2024,26 +2188,34 @@
         /**
          * Builds and returns a {@code ModuleDescriptor} from its components.
          *
+         * <p> The module will require "{@code java.base}" even if the dependence
+         * has not been declared (the exception is when building a module named
+         * "{@code java.base}" as it cannot require itself). The dependence on
+         * "{@code java.base}" will have the {@link
+         * java.lang.module.ModuleDescriptor.Requires.Modifier#MANDATED MANDATED}
+         * modifier if the dependence was not declared. </p>
+         *
          * @return The module descriptor
          */
         public ModuleDescriptor build() {
             Set<Requires> requires = new HashSet<>(this.requires.values());
-
-            Set<String> packages = new HashSet<>();
-            packages.addAll(exports.keySet());
-            packages.addAll(opens.keySet());
-            packages.addAll(concealedPackages);
-
             Set<Exports> exports = new HashSet<>(this.exports.values());
             Set<Opens> opens = new HashSet<>(this.opens.values());
 
+            // add dependency on java.base
+            if (strict
+                    && !name.equals("java.base")
+                    && !this.requires.containsKey("java.base")) {
+                requires.add(new Requires(Set.of(Requires.Modifier.MANDATED),
+                                          "java.base",
+                                          null));
+            }
+
             Set<Provides> provides = new HashSet<>(this.provides.values());
 
             return new ModuleDescriptor(name,
                                         version,
-                                        open,
-                                        automatic,
-                                        synthetic,
+                                        modifiers,
                                         requires,
                                         exports,
                                         opens,
@@ -2062,16 +2234,20 @@
      * Compares this module descriptor to another.
      *
      * <p> Two {@code ModuleDescriptor} objects are compared by comparing their
-     * module name lexicographically.  Where the module names are equal then
-     * the versions, if present, are compared. </p>
-     *
-     * @apiNote For now, the natural ordering is not consistent with equals.
-     * If two module descriptors have equal module names, equal versions if
-     * present, but their corresponding components are not equal, then they
-     * will be considered equal by this method.
+     * module names lexicographically. Where the module names are equal then the
+     * module versions are compared. When comparing the module versions then a
+     * module descriptor with a version is considered to succeed a module
+     * descriptor that does not have a version. Where the module names are equal
+     * and the versions are equal (or not present in both), then the set of
+     * modifiers are compared. Sets of modifiers are compared by comparing
+     * a <em>binary value</em> computed for each set. If a modifier is present
+     * in the set then the bit at the position of its ordinal is {@code 1}
+     * in the binary value, otherwise {@code 0}. If the two set of modifiers
+     * are also equal then the other components of the module descriptors are
+     * compared in a manner that is consistent with {@code equals}. </p>
      *
      * @param  that
-     *         The object to which this module descriptor is to be compared
+     *         The module descriptor to compare
      *
      * @return A negative integer, zero, or a positive integer if this module
      *         descriptor is less than, equal to, or greater than the given
@@ -2079,16 +2255,50 @@
      */
     @Override
     public int compareTo(ModuleDescriptor that) {
+        if (this == that) return 0;
+
         int c = this.name().compareTo(that.name());
         if (c != 0) return c;
-        if (version == null) {
-            if (that.version == null)
-                return 0;
-            return -1;
-        }
-        if (that.version == null)
-            return +1;
-        return version.compareTo(that.version);
+
+        c = compare(this.version, that.version);
+        if (c != 0) return c;
+
+        long v1 = modsValue(this.modifiers());
+        long v2 = modsValue(that.modifiers());
+        c = Long.compare(v1, v2);
+        if (c != 0) return c;
+
+        c = compare(this.requires, that.requires);
+        if (c != 0) return c;
+
+        c = compare(this.packages, that.packages);
+        if (c != 0) return c;
+
+        c = compare(this.exports, that.exports);
+        if (c != 0) return c;
+
+        c = compare(this.opens, that.opens);
+        if (c != 0) return c;
+
+        c = compare(this.uses, that.uses);
+        if (c != 0) return c;
+
+        c = compare(this.provides, that.provides);
+        if (c != 0) return c;
+
+        c = compare(this.mainClass, that.mainClass);
+        if (c != 0) return c;
+
+        c = compare(this.osName, that.osName);
+        if (c != 0) return c;
+
+        c = compare(this.osArch, that.osArch);
+        if (c != 0) return c;
+
+        c = compare(this.osVersion, that.osVersion);
+        if (c != 0) return c;
+
+        return 0;
     }
 
     /**
@@ -2115,10 +2325,9 @@
             return false;
         ModuleDescriptor that = (ModuleDescriptor)ob;
         return (name.equals(that.name)
-                && open == that.open
-                && automatic == that.automatic
-                && synthetic == that.synthetic
+                && modifiers.equals(that.modifiers)
                 && requires.equals(that.requires)
+                && Objects.equals(packages, that.packages)
                 && exports.equals(that.exports)
                 && opens.equals(that.opens)
                 && uses.equals(that.uses)
@@ -2127,12 +2336,9 @@
                 && Objects.equals(mainClass, that.mainClass)
                 && Objects.equals(osName, that.osName)
                 && Objects.equals(osArch, that.osArch)
-                && Objects.equals(osVersion, that.osVersion)
-                && Objects.equals(packages, that.packages));
+                && Objects.equals(osVersion, that.osVersion));
     }
 
-    private transient int hash;  // cached hash code
-
     /**
      * Computes a hash code for this module descriptor.
      *
@@ -2147,10 +2353,9 @@
         int hc = hash;
         if (hc == 0) {
             hc = name.hashCode();
-            hc = hc * 43 + Boolean.hashCode(open);
-            hc = hc * 43 + Boolean.hashCode(automatic);
-            hc = hc * 43 + Boolean.hashCode(synthetic);
+            hc = hc * 43 + Objects.hashCode(modifiers);
             hc = hc * 43 + requires.hashCode();
+            hc = hc * 43 + Objects.hashCode(packages);
             hc = hc * 43 + exports.hashCode();
             hc = hc * 43 + opens.hashCode();
             hc = hc * 43 + uses.hashCode();
@@ -2160,18 +2365,18 @@
             hc = hc * 43 + Objects.hashCode(osName);
             hc = hc * 43 + Objects.hashCode(osArch);
             hc = hc * 43 + Objects.hashCode(osVersion);
-            hc = hc * 43 + Objects.hashCode(packages);
             if (hc == 0)
                 hc = -1;
             hash = hc;
         }
         return hc;
     }
+    private transient int hash;  // cached hash code
 
     /**
-     * Returns a string describing this descriptor.
+     * <p> Returns a string describing the module. </p>
      *
-     * @return A string describing this descriptor
+     * @return A string describing the module
      */
     @Override
     public String toString() {
@@ -2201,31 +2406,50 @@
      *
      * @param  name
      *         The module name
+     * @param  ms
+     *         The set of module modifiers
      *
      * @return A new builder
      *
      * @throws IllegalArgumentException
-     *         If the module name is {@code null} or is not a legal Java
-     *         identifier
+     *         If the module name is {@code null} or is not a legal module
+     *         name, or the set of modifiers contains {@link
+     *         Modifier#AUTOMATIC AUTOMATIC} with other modifiers
      */
-    public static Builder module(String name) {
-        return new Builder(name, true, false, false);
+    public static Builder newModule(String name, Set<Modifier> ms) {
+        Set<Modifier> mods = new HashSet<>(ms);
+        if (mods.contains(Modifier.AUTOMATIC) && mods.size() > 1)
+            throw new IllegalArgumentException("AUTOMATIC cannot be used with"
+                                               + " other modifiers");
+
+        return new Builder(name, true, mods);
+    }
+
+    /**
+     * Instantiates a builder to build a module descriptor for a <em>normal</em>
+     * module. This method is equivalent to invoking {@link #newModule(String,Set)
+     * newModule} with an empty set of {@link ModuleDescriptor.Modifier modifiers}.
+     *
+     * @param  name
+     *         The module name
+     *
+     * @return A new builder
+     *
+     * @throws IllegalArgumentException
+     *         If the module name is {@code null} or is not a legal module
+     *         name
+     */
+    public static Builder newModule(String name) {
+        return new Builder(name, true, Set.of());
     }
 
     /**
      * Instantiates a builder to build a module descriptor for an open module.
-     * An open module does not declare any open packages but the resulting
-     * module is treated as if all packages are open.
+     * This method is equivalent to invoking {@link #newModule(String,Set)
+     * newModule} with the {@link ModuleDescriptor.Modifier#OPEN OPEN} modifier.
      *
-     * <p> As an example, the following creates a module descriptor for an open
-     * name "{@code m}" containing two packages, one of which is exported. </p>
-     * <pre>{@code
-     *     ModuleDescriptor descriptor = ModuleDescriptor.openModule("m")
-     *         .requires("java.base")
-     *         .exports("p")
-     *         .contains("q")
-     *         .build();
-     * }</pre>
+     * <p> The builder for an open module cannot be used to declare any open
+     * packages. </p>
      *
      * @param  name
      *         The module name
@@ -2233,19 +2457,22 @@
      * @return A new builder that builds an open module
      *
      * @throws IllegalArgumentException
-     *         If the module name is {@code null} or is not a legal Java
-     *         identifier
+     *         If the module name is {@code null} or is not a legal module
+     *         name
      */
-    public static Builder openModule(String name) {
-        return new Builder(name, true, true, false);
+    public static Builder newOpenModule(String name) {
+        return new Builder(name, true, Set.of(Modifier.OPEN));
     }
 
     /**
      * Instantiates a builder to build a module descriptor for an automatic
-     * module. Automatic modules receive special treatment during resolution
-     * (see {@link Configuration}) so that they read all other modules. When
-     * Instantiated in the Java virtual machine as a {@link java.lang.reflect.Module}
-     * then the Module reads every unnamed module in the Java virtual machine.
+     * module. This method is equivalent to invoking {@link #newModule(String,Set)
+     * newModule} with the {@link ModuleDescriptor.Modifier#AUTOMATIC AUTOMATIC}
+     * modifier.
+     *
+     * <p> The builder for an automatic module cannot be used to declare module
+     * or service dependences. It also cannot be used to declare any exported
+     * or open packages. </p>
      *
      * @param  name
      *         The module name
@@ -2253,13 +2480,13 @@
      * @return A new builder that builds an automatic module
      *
      * @throws IllegalArgumentException
-     *         If the module name is {@code null} or is not a legal Java
-     *         identifier
+     *         If the module name is {@code null} or is not a legal module
+     *         name
      *
      * @see ModuleFinder#of(Path[])
      */
-    public static Builder automaticModule(String name) {
-        return new Builder(name, true, false, false).automatic(true);
+    public static Builder newAutomaticModule(String name) {
+        return new Builder(name, true, Set.of(Modifier.AUTOMATIC));
     }
 
 
@@ -2269,8 +2496,12 @@
      *
      * <p> If the descriptor encoded in the input stream does not indicate a
      * set of packages in the module then the {@code packageFinder} will be
-     * invoked. If the {@code packageFinder} throws an {@link UncheckedIOException}
-     * then {@link IOException} cause will be re-thrown. </p>
+     * invoked. The set of packages that the {@code packageFinder} returns
+     * must include all the packages that the module exports, opens, as well
+     * as the packages of the service implementations that the module provides,
+     * and the package of the main class (if the module has a main class). If
+     * the {@code packageFinder} throws an {@link UncheckedIOException} then
+     * {@link IOException} cause will be re-thrown. </p>
      *
      * <p> If there are bytes following the module descriptor then it is
      * implementation specific as to whether those bytes are read, ignored,
@@ -2292,7 +2523,9 @@
      * @return The module descriptor
      *
      * @throws InvalidModuleDescriptorException
-     *         If an invalid module descriptor is detected
+     *         If an invalid module descriptor is detected or the set of
+     *         packages returned by the {@code packageFinder} does not include
+     *         all of the packages obtained from the module descriptor
      * @throws IOException
      *         If an I/O error occurs reading from the input stream or {@code
      *         UncheckedIOException} is thrown by the package finder
@@ -2305,8 +2538,12 @@
     }
 
     /**
-     * Reads the binary form of a module declaration from an input stream
-     * as a module descriptor.
+     * Reads the binary form of a module declaration from an input stream as a
+     * module descriptor. This method works exactly as specified by the 2-arg
+     * {@link #read(InputStream,Supplier) read} method with the exception that
+     * a packager finder is not used to find additional packages when the
+     * module descriptor read from the stream does not indicate the set of
+     * packages.
      *
      * @param  in
      *         The input stream
@@ -2327,7 +2564,13 @@
      * as a module descriptor.
      *
      * <p> If the descriptor encoded in the byte buffer does not indicate a
-     * set of packages then the {@code packageFinder} will be invoked. </p>
+     * set of packages in the module then the {@code packageFinder} will be
+     * invoked. The set of packages that the {@code packageFinder} returns
+     * must include all the packages that the module exports, opens, as well
+     * as the packages of the service implementations that the module provides,
+     * and the package of the main class (if the module has a main class). If
+     * the {@code packageFinder} throws an {@link UncheckedIOException} then
+     * {@link IOException} cause will be re-thrown. </p>
      *
      * <p> The module descriptor is read from the buffer stating at index
      * {@code p}, where {@code p} is the buffer's {@link ByteBuffer#position()
@@ -2353,7 +2596,9 @@
      * @return The module descriptor
      *
      * @throws InvalidModuleDescriptorException
-     *         If an invalid module descriptor is detected
+     *         If an invalid module descriptor is detected or the set of
+     *         packages returned by the {@code packageFinder} does not include
+     *         all of the packages obtained from the module descriptor
      */
     public static ModuleDescriptor read(ByteBuffer bb,
                                         Supplier<Set<String>> packageFinder)
@@ -2362,8 +2607,11 @@
     }
 
     /**
-     * Reads the binary form of a module declaration from a byte buffer
-     * as a module descriptor.
+     * Reads the binary form of a module declaration from a byte buffer as a
+     * module descriptor. This method works exactly as specified by the 2-arg
+     * {@link #read(ByteBuffer,Supplier) read} method with the exception that a
+     * packager finder is not used to find additional packages when the module
+     * descriptor encoded in the buffer does not indicate the set of packages.
      *
      * @param  bb
      *         The byte buffer
@@ -2398,6 +2646,11 @@
         }
     }
 
+    private static String packageName(String cn) {
+        int index = cn.lastIndexOf('.');
+        return (index == -1) ? "" : cn.substring(0, index);
+    }
+
     /**
      * Returns a string containing the given set of modifiers and label.
      */
@@ -2407,6 +2660,36 @@
                 .collect(Collectors.joining(" "));
     }
 
+    private static <T extends Object & Comparable<? super T>>
+    int compare(T obj1, T obj2) {
+        if (obj1 != null) {
+            return (obj2 != null) ? obj1.compareTo(obj2) : 1;
+        } else {
+            return (obj2 == null) ? 0 : -1;
+        }
+    }
+
+    /**
+     * Compares two sets of {@code Comparable} objects.
+     */
+    @SuppressWarnings("unchecked")
+    private static <T extends Object & Comparable<? super T>>
+    int compare(Set<T> s1, Set<T> s2) {
+        T[] a1 = (T[]) s1.toArray();
+        T[] a2 = (T[]) s2.toArray();
+        Arrays.sort(a1);
+        Arrays.sort(a2);
+        return Arrays.compare(a1, a2);
+    }
+
+    private static <E extends Enum<E>> long modsValue(Set<E> set) {
+        long value = 0;
+        for (Enum<E> e : set) {
+            value += 1 << e.ordinal();
+        }
+        return value;
+    }
+
     static {
         /**
          * Setup the shared secret to allow code in other packages access
@@ -2417,19 +2700,21 @@
                 @Override
                 public Builder newModuleBuilder(String mn,
                                                 boolean strict,
-                                                boolean open,
-                                                boolean synthetic) {
-                    return new Builder(mn, strict, open, synthetic);
+                                                Set<ModuleDescriptor.Modifier> modifiers) {
+                    return new Builder(mn, strict, modifiers);
                 }
 
                 @Override
-                public Set<String> exportedPackages(ModuleDescriptor.Builder builder) {
-                    return builder.exportedPackages();
+                public Set<String> packages(ModuleDescriptor.Builder builder) {
+                    return builder.packages();
                 }
 
                 @Override
-                public Set<String> openPackages(ModuleDescriptor.Builder builder) {
-                    return builder.openPackages();
+                public void requires(ModuleDescriptor.Builder builder,
+                                     Set<Requires.Modifier> ms,
+                                     String mn,
+                                     String compiledVersion) {
+                    builder.requires(ms, mn, compiledVersion);
                 }
 
                 @Override
@@ -2467,22 +2752,9 @@
                 }
 
                 @Override
-                public Version newVersion(String v) {
-                    return new Version(v);
-                }
-
-                @Override
-                public ModuleDescriptor newModuleDescriptor(ModuleDescriptor md,
-                                                            Set<String> pkgs) {
-                    return new ModuleDescriptor(md, pkgs);
-                }
-
-                @Override
                 public ModuleDescriptor newModuleDescriptor(String name,
                                                             Version version,
-                                                            boolean open,
-                                                            boolean automatic,
-                                                            boolean synthetic,
+                                                            Set<ModuleDescriptor.Modifier> modifiers,
                                                             Set<Requires> requires,
                                                             Set<Exports> exports,
                                                             Set<Opens> opens,
@@ -2496,9 +2768,7 @@
                                                             int hashCode) {
                     return new ModuleDescriptor(name,
                                                 version,
-                                                open,
-                                                automatic,
-                                                synthetic,
+                                                modifiers,
                                                 requires,
                                                 exports,
                                                 opens,
@@ -2514,12 +2784,12 @@
                 }
 
                 @Override
-                public Configuration resolveRequiresAndUses(ModuleFinder finder,
-                                                            Collection<String> roots,
-                                                            boolean check,
-                                                            PrintStream traceOutput)
+                public Configuration resolveAndBind(ModuleFinder finder,
+                                                    Collection<String> roots,
+                                                    boolean check,
+                                                    PrintStream traceOutput)
                 {
-                    return Configuration.resolveRequiresAndUses(finder, roots, check, traceOutput);
+                    return Configuration.resolveAndBind(finder, roots, check, traceOutput);
                 }
             });
     }
--- a/jdk/src/java.base/share/classes/java/lang/module/ModuleFinder.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/module/ModuleFinder.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -42,14 +42,15 @@
 import java.util.Optional;
 import java.util.Set;
 
+import jdk.internal.module.ModuleBootstrap;
 import jdk.internal.module.ModulePath;
 import jdk.internal.module.SystemModuleFinder;
 import sun.security.action.GetPropertyAction;
 
 /**
  * A finder of modules. A {@code ModuleFinder} is used to find modules during
- * <a href="Configuration.html#resolution">resolution</a> or
- * <a href="Configuration.html#servicebinding">service binding</a>.
+ * <a href="package-summary.html#resolution">resolution</a> or
+ * <a href="package-summary.html#servicebinding">service binding</a>.
  *
  * <p> A {@code ModuleFinder} can only find one module with a given name. A
  * {@code ModuleFinder} that finds modules in a sequence of directories, for
@@ -85,6 +86,7 @@
  * <p> A {@code ModuleFinder} is not required to be thread safe. </p>
  *
  * @since 9
+ * @spec JPMS
  */
 
 public interface ModuleFinder {
@@ -124,8 +126,8 @@
      * to find that module. </p>
      *
      * @apiNote This is important to have for methods such as {@link
-     * Configuration#resolveRequiresAndUses resolveRequiresAndUses} that need
-     * to scan the module path to find modules that provide a specific service.
+     * Configuration#resolveAndBind resolveAndBind} that need to scan the
+     * module path to find modules that provide a specific service.
      *
      * @return The set of all module references that this finder locates
      *
@@ -172,7 +174,8 @@
         } else {
             Path mlib = Paths.get(home, "modules");
             if (Files.isDirectory(mlib)) {
-                return of(mlib);
+                // exploded build may be patched
+                return ModulePath.of(ModuleBootstrap.patcher(), mlib);
             } else {
                 throw new InternalError("Unable to detect the run-time image");
             }
@@ -198,13 +201,9 @@
      *
      * <p> If an element is a path to a directory of modules then each entry in
      * the directory is a packaged module or the top-level directory of an
-     * exploded module. The module finder's {@link #find(String) find} or
-     * {@link #findAll() findAll} methods throw {@link FindException} if a
-     * directory containing more than one module with the same name is
-     * encountered. </p>
-     *
-     * <p> If an element in the array is a path to a directory, and that
-     * directory contains a file named {@code module-info.class}, then the
+     * exploded module. It it an error if a directory contains more than one
+     * module with the same name. If an element is a path to a directory, and
+     * that directory contains a file named {@code module-info.class}, then the
      * directory is treated as an exploded module rather than a directory of
      * modules. </p>
      *
@@ -214,9 +213,8 @@
      * entry in a {@link java.util.jar.JarFile#isMultiRelease() multi-release}
      * JAR file) is a modular JAR and is an <em>explicit module</em>.
      * A JAR file that does not have a {@code module-info.class} in the
-     * top-level directory is an {@link ModuleDescriptor#isAutomatic automatic}
-     * module. The {@link ModuleDescriptor} for an automatic module is created as
-     * follows:
+     * top-level directory is created as an automatic module. The components
+     * for the automatic module are derived as follows:
      *
      * <ul>
      *
@@ -248,46 +246,48 @@
      *
      *     </ul></li>
      *
-     *     <li><p> It {@link ModuleDescriptor#requires() requires} {@code
-     *     java.base}. </p></li>
-     *
-     *     <li><p> The set of packages in the module is derived from the names
-     *     of non-directory entries in the JAR file. A candidate package name
-     *     is derived from an entry using the characters up to, but not
-     *     including, the last forward slash. All remaining forward slashes are
-     *     replaced with dot ({@code "."}). If the resulting string is a valid
-     *     Java identifier then it is assumed to be a package name. For example,
-     *     if the JAR file contains an entry "{@code p/q/Foo.class}" then the
-     *     package name derived is "{@code p.q}". All packages are {@link
-     *     ModuleDescriptor#exports() exported}. </p></li>
+     *     <li><p> The set of packages in the module is derived from the
+     *     non-directory entries in the JAR file that have names ending in
+     *     "{@code .class}". A candidate package name is derived from the name
+     *     using the characters up to, but not including, the last forward slash.
+     *     All remaining forward slashes are replaced with dot ({@code "."}). If
+     *     the resulting string is a legal package name then it is assumed to be
+     *     a package name. For example, if the JAR file contains the entry
+     *     "{@code p/q/Foo.class}" then the package name derived is
+     *     "{@code p.q}".</p></li>
      *
      *     <li><p> The contents of entries starting with {@code
      *     META-INF/services/} are assumed to be service configuration files
      *     (see {@link java.util.ServiceLoader}). If the name of a file
-     *     (that follows {@code META-INF/services/}) is a legal Java identifier
-     *     then it is assumed to be the fully-qualified binary name of a
-     *     service type. The entries in the file are assumed to be the
-     *     fully-qualified binary names of provider classes. </p></li>
+     *     (that follows {@code META-INF/services/}) is a legal class name
+     *     then it is assumed to be the fully-qualified class name of a service
+     *     type. The entries in the file are assumed to be the fully-qualified
+     *     class names of provider classes. </p></li>
      *
      *     <li><p> If the JAR file has a {@code Main-Class} attribute in its
-     *     main manifest then its value is the {@link
+     *     main manifest then its value is the module {@link
      *     ModuleDescriptor#mainClass() main class}. </p></li>
      *
      * </ul>
      *
      * <p> If a {@code ModuleDescriptor} cannot be created (by means of the
      * {@link ModuleDescriptor.Builder ModuleDescriptor.Builder} API) for an
-     * automatic module then {@code FindException} is thrown. This can arise,
-     * for example, when a legal Java identifier name cannot be derived from
-     * the file name of the JAR file or where the JAR file contains a {@code
-     * .class} in the top-level directory of the JAR file. </p>
+     * automatic module then {@code FindException} is thrown. This can arise
+     * when a legal module name cannot be derived from the file name of the JAR
+     * file, where the JAR file contains a {@code .class} in the top-level
+     * directory of the JAR file, where an entry in a service configuration
+     * file is not a legal class name or its package name is not in the set of
+     * packages derived for the module, or where the module main class is not
+     * a legal class name or its package is not in the module. </p>
      *
      * <p> In addition to JAR files, an implementation may also support modules
-     * that are packaged in other implementation specific module formats. When
-     * a file is encountered that is not recognized as a packaged module then
-     * {@code FindException} is thrown. An implementation may choose to ignore
-     * some files, {@link java.nio.file.Files#isHidden hidden} files for
-     * example. Paths to files that do not exist are always ignored. </p>
+     * that are packaged in other implementation specific module formats. If
+     * an element in the array specified to this method is a path to a directory
+     * of modules then entries in the directory that not recognized as modules
+     * are ignored. If an element in the array is a path to a packaged module
+     * that is not recognized then a {@code FindException} is thrown when the
+     * file is encountered. Paths to files that do not exist are always ignored.
+     * </p>
      *
      * <p> As with automatic modules, the contents of a packaged or exploded
      * module may need to be <em>scanned</em> in order to determine the packages
@@ -325,7 +325,7 @@
             };
         }
 
-        return new ModulePath(entries);
+        return ModulePath.of(entries);
     }
 
     /**
--- a/jdk/src/java.base/share/classes/java/lang/module/ModuleReader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/module/ModuleReader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -45,7 +45,7 @@
  * module. A module reader is also intended to be used by {@code ClassLoader}
  * implementations that load classes and resources from modules. </p>
  *
- * <p> A resource in a module is identified by a name that is a
+ * <p> A resource in a module is identified by an abstract name that is a
  * '{@code /}'-separated path string. For example, module {@code java.base} may
  * have a resource "{@code java/lang/Object.class}" that, by convention, is the
  * class file for {@code java.lang.Object}. </p>
@@ -61,8 +61,18 @@
  * open}, {@link #read read}, and {@link #list list} methods may throw {@code
  * SecurityException} if access is denied by the security manager. </p>
  *
+ * @implSpec Implementations of {@code ModuleReader} should take great care
+ * when translating an abstract resource name to the location of a resource in
+ * a packaged module or on the file system. Implementations are advised to
+ * treat resource names with elements such as '{@code .},  '{@code ..}',
+ * elements containing file separators, or empty elements as "not found". More
+ * generally, if the resource name is not in the stream of elements that the
+ * {@code list} method returns then the resource should be treated as "not
+ * found" to avoid inconsistencies.
+ *
  * @see ModuleReference
  * @since 9
+ * @spec JPMS
  */
 
 public interface ModuleReader extends Closeable {
@@ -148,6 +158,9 @@
      *         If an I/O error occurs or the module reader is closed
      * @throws SecurityException
      *         If denied by the security manager
+     * @throws OutOfMemoryError
+     *         If the resource is larger than {@code Integer.MAX_VALUE},
+     *         the maximum capacity of a byte buffer
      *
      * @see ClassLoader#defineClass(String, ByteBuffer, java.security.ProtectionDomain)
      */
--- a/jdk/src/java.base/share/classes/java/lang/module/ModuleReference.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/module/ModuleReference.java	Thu Mar 16 20:47:03 2017 +0000
@@ -44,6 +44,7 @@
  * @see ModuleFinder
  * @see ModuleReader
  * @since 9
+ * @spec JPMS
  */
 
 public abstract class ModuleReference {
@@ -76,7 +77,7 @@
     /**
      * Returns the location of this module's content, if known.
      *
-     * <p> This URI, when present, is used as the {@linkplain
+     * <p> This URI, when present, can be used as the {@linkplain
      * java.security.CodeSource#getLocation location} value of a {@link
      * java.security.CodeSource CodeSource} so that a module's classes can be
      * granted specific permissions when loaded by a {@link
--- a/jdk/src/java.base/share/classes/java/lang/module/ResolutionException.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/module/ResolutionException.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -26,10 +26,12 @@
 package java.lang.module;
 
 /**
- * Thrown when resolving a set of modules or binding fails.
+ * Thrown when resolving a set of modules, or resolving a set of modules with
+ * service binding, fails.
  *
  * @see Configuration
  * @since 9
+ * @spec JPMS
  */
 public class ResolutionException extends RuntimeException {
     private static final long serialVersionUID = -1031186845316729450L;
--- a/jdk/src/java.base/share/classes/java/lang/module/ResolvedModule.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/module/ResolvedModule.java	Thu Mar 16 20:47:03 2017 +0000
@@ -37,6 +37,7 @@
  * module's content.
  *
  * @since 9
+ * @spec JPMS
  * @see Configuration#modules()
  */
 public final class ResolvedModule {
--- a/jdk/src/java.base/share/classes/java/lang/module/Resolver.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/module/Resolver.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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,8 +49,8 @@
 import jdk.internal.module.ModuleReferenceImpl;
 
 /**
- * The resolver used by {@link Configuration#resolveRequires} and
- * {@link Configuration#resolveRequiresAndUses}.
+ * The resolver used by {@link Configuration#resolve} and {@link
+ * Configuration#resolveAndBind}.
  *
  * @implNote The resolver is used at VM startup and so deliberately avoids
  * using lambda and stream usages in code paths used during startup.
@@ -66,7 +66,19 @@
     // maps module name to module reference
     private final Map<String, ModuleReference> nameToReference = new HashMap<>();
 
+    // module constraints on target platform
+    private String osName;
+    private String osArch;
+    private String osVersion;
 
+    String osName() { return osName; }
+    String osArch() { return osArch; }
+    String osVersion() { return osVersion; }
+
+    /**
+     * @throws IllegalArgumentException if there are more than one parent and
+     *         the constraints on the target platform conflict
+     */
     Resolver(ModuleFinder beforeFinder,
              List<Configuration> parents,
              ModuleFinder afterFinder,
@@ -75,15 +87,54 @@
         this.parents = parents;
         this.afterFinder = afterFinder;
         this.traceOutput = traceOutput;
+
+        // record constraints on target platform, checking that they don't conflict
+        for (Configuration parent : parents) {
+            String value = parent.osName();
+            if (value != null) {
+                if (osName == null) {
+                    osName = value;
+                } else {
+                    if (!value.equals(osName)) {
+                        failParentConflict("Operating System", osName, value);
+                    }
+                }
+            }
+            value = parent.osArch();
+            if (value != null) {
+                if (osArch == null) {
+                    osArch = value;
+                } else {
+                    if (!value.equals(osArch)) {
+                        failParentConflict("OS architecture", osArch, value);
+                    }
+                }
+            }
+            value = parent.osVersion();
+            if (value != null) {
+                if (osVersion == null) {
+                    osVersion  = value;
+                } else {
+                    if (!value.equals(osVersion)) {
+                        failParentConflict("OS version", osVersion, value);
+                    }
+                }
+            }
+        }
     }
 
+    private void failParentConflict(String constraint, String s1, String s2) {
+        String msg = "Parents have conflicting constraints on target "
+                     + constraint + ": " + s1 + ", " + s2;
+        throw new IllegalArgumentException(msg);
+    }
 
     /**
      * Resolves the given named modules.
      *
      * @throws ResolutionException
      */
-    Resolver resolveRequires(Collection<String> roots) {
+    Resolver resolve(Collection<String> roots) {
 
         // create the visit stack to get us started
         Deque<ModuleDescriptor> q = new ArrayDeque<>();
@@ -100,7 +151,7 @@
 
                 mref = findWithAfterFinder(root);
                 if (mref == null) {
-                    fail("Module %s not found", root);
+                    findFail("Module %s not found", root);
                 }
             }
 
@@ -109,8 +160,7 @@
                 mref.location().ifPresent(uri -> trace("  (%s)", uri));
             }
 
-            assert mref.descriptor().name().equals(root);
-            nameToReference.put(root, mref);
+            addFoundModule(mref);
             q.push(mref.descriptor());
         }
 
@@ -152,19 +202,19 @@
 
                     mref = findWithAfterFinder(dn);
                     if (mref == null) {
-                        fail("Module %s not found, required by %s",
-                                dn, descriptor.name());
+                        findFail("Module %s not found, required by %s",
+                                 dn, descriptor.name());
                     }
                 }
 
                 if (!nameToReference.containsKey(dn)) {
-                    nameToReference.put(dn, mref);
+                    addFoundModule(mref);
                     q.offer(mref.descriptor());
                     resolved.add(mref.descriptor());
 
                     if (isTracing()) {
                         trace("Module %s located, required by %s",
-                                dn, descriptor.name());
+                              dn, descriptor.name());
                         mref.location().ifPresent(uri -> trace("  (%s)", uri));
                     }
                 }
@@ -181,7 +231,7 @@
      * Augments the set of resolved modules with modules induced by the
      * service-use relation.
      */
-    Resolver resolveUses() {
+    Resolver bind() {
 
         // Scan the finders for all available service provider modules. As
         // java.base uses services then then module finders will be scanned
@@ -246,7 +296,7 @@
                                             mref.location()
                                                 .ifPresent(uri -> trace("  (%s)", uri));
                                         }
-                                        nameToReference.put(pn, mref);
+                                        addFoundModule(mref);
                                         q.push(provider);
                                     }
                                 }
@@ -264,6 +314,81 @@
 
 
     /**
+     * Add the module to the nameToReference map. Also check any constraints on
+     * the target platform with the constraints of other modules.
+     */
+    private void addFoundModule(ModuleReference mref) {
+        ModuleDescriptor descriptor = mref.descriptor();
+        nameToReference.put(descriptor.name(), mref);
+
+        if (descriptor.osName().isPresent()
+                || descriptor.osArch().isPresent()
+                || descriptor.osVersion().isPresent())
+            checkTargetConstraints(descriptor);
+    }
+
+    /**
+     * Check that the module's constraints on the target platform do not
+     * conflict with the constraints of other modules resolved so far or
+     * modules in parent configurations.
+     */
+    private void checkTargetConstraints(ModuleDescriptor descriptor) {
+        String value = descriptor.osName().orElse(null);
+        if (value != null) {
+            if (osName == null) {
+                osName = value;
+            } else {
+                if (!value.equals(osName)) {
+                    failTargetConstraint(descriptor);
+                }
+            }
+        }
+        value = descriptor.osArch().orElse(null);
+        if (value != null) {
+            if (osArch == null) {
+                osArch = value;
+            } else {
+                if (!value.equals(osArch)) {
+                    failTargetConstraint(descriptor);
+                }
+            }
+        }
+        value = descriptor.osVersion().orElse(null);
+        if (value != null) {
+            if (osVersion == null) {
+                osVersion = value;
+            } else {
+                if (!value.equals(osVersion)) {
+                    failTargetConstraint(descriptor);
+                }
+            }
+        }
+    }
+
+    private void failTargetConstraint(ModuleDescriptor md) {
+        String s1 = targetAsString(osName, osArch, osVersion);
+        String s2 = targetAsString(md);
+        findFail("Module %s has constraints on target platform that conflict" +
+                 " with other modules: %s, %s", md.name(), s1, s2);
+    }
+
+    private String targetAsString(ModuleDescriptor descriptor) {
+        String osName = descriptor.osName().orElse(null);
+        String osArch = descriptor.osArch().orElse(null);
+        String osVersion = descriptor.osVersion().orElse(null);
+        return targetAsString(osName, osArch, osVersion);
+    }
+
+    private String targetAsString(String osName, String osArch, String osVersion) {
+        return new StringJoiner("-")
+                .add(Objects.toString(osName, "*"))
+                .add(Objects.toString(osArch, "*"))
+                .add(Objects.toString(osVersion, "*"))
+                .toString();
+    }
+
+
+    /**
      * Execute post-resolution checks and returns the module graph of resolved
      * modules as {@code Map}. The resolved modules will be in the given
      * configuration.
@@ -281,7 +406,6 @@
 
         if (check) {
             detectCycles();
-            checkPlatformConstraints();
             checkHashes();
         }
 
@@ -319,8 +443,7 @@
         if (!visited.contains(descriptor)) {
             boolean added = visitPath.add(descriptor);
             if (!added) {
-                throw new ResolutionException("Cycle detected: " +
-                        cycleAsString(descriptor));
+                resolveFail("Cycle detected: %s", cycleAsString(descriptor));
             }
             for (ModuleDescriptor.Requires requires : descriptor.requires()) {
                 String dn = requires.name();
@@ -354,86 +477,6 @@
 
 
     /**
-     * If there are platform specific modules then check that the OS name,
-     * architecture and version match.
-     *
-     * @apiNote This method does not currently check if the OS matches
-     *          platform specific modules in parent configurations.
-     */
-    private void checkPlatformConstraints() {
-
-        // first module encountered that is platform specific
-        String savedModuleName = null;
-        String savedOsName = null;
-        String savedOsArch = null;
-        String savedOsVersion = null;
-
-        for (ModuleReference mref : nameToReference.values()) {
-            ModuleDescriptor descriptor = mref.descriptor();
-
-            String osName = descriptor.osName().orElse(null);
-            String osArch = descriptor.osArch().orElse(null);
-            String osVersion = descriptor.osVersion().orElse(null);
-
-            if (osName != null || osArch != null || osVersion != null) {
-
-                if (savedModuleName == null) {
-
-                    savedModuleName = descriptor.name();
-                    savedOsName = osName;
-                    savedOsArch = osArch;
-                    savedOsVersion = osVersion;
-
-                } else {
-
-                    boolean matches = platformMatches(osName, savedOsName)
-                            && platformMatches(osArch, savedOsArch)
-                            && platformMatches(osVersion, savedOsVersion);
-
-                    if (!matches) {
-                        String s1 = platformAsString(savedOsName,
-                                                     savedOsArch,
-                                                     savedOsVersion);
-
-                        String s2 = platformAsString(osName, osArch, osVersion);
-                        fail("Mismatching constraints on target platform: "
-                                + savedModuleName + ": " + s1
-                                + ", " + descriptor.name() + ": " + s2);
-                    }
-
-                }
-
-            }
-        }
-
-    }
-
-    /**
-     * Returns true if the s1 and s2 are equal or one of them is null.
-     */
-    private boolean platformMatches(String s1, String s2) {
-        if (s1 == null || s2 == null)
-            return true;
-        else
-            return Objects.equals(s1, s2);
-    }
-
-    /**
-     * Return a string that encodes the OS name/arch/version.
-     */
-    private String platformAsString(String osName,
-                                    String osArch,
-                                    String osVersion) {
-
-        return new StringJoiner("-")
-                .add(Objects.toString(osName, "*"))
-                .add(Objects.toString(osArch, "*"))
-                .add(Objects.toString(osVersion, "*"))
-                .toString();
-
-    }
-
-    /**
      * Checks the hashes in the module descriptor to ensure that they match
      * any recorded hashes.
      */
@@ -460,7 +503,7 @@
                     continue;
 
                 if (!(mref2 instanceof ModuleReferenceImpl)) {
-                    fail("Unable to compute the hash of module %s", dn);
+                    findFail("Unable to compute the hash of module %s", dn);
                 }
 
                 // skip checking the hash if the module has been patched
@@ -469,11 +512,11 @@
                     byte[] recordedHash = hashes.hashFor(dn);
                     byte[] actualHash = other.computeHash(algorithm);
                     if (actualHash == null)
-                        fail("Unable to compute the hash of module %s", dn);
+                        findFail("Unable to compute the hash of module %s", dn);
                     if (!Arrays.equals(recordedHash, actualHash)) {
-                        fail("Hash of %s (%s) differs to expected hash (%s)" +
-                             " recorded in %s", dn, toHexString(actualHash),
-                             toHexString(recordedHash), descriptor.name());
+                        findFail("Hash of %s (%s) differs to expected hash (%s)" +
+                                 " recorded in %s", dn, toHexString(actualHash),
+                                 toHexString(recordedHash), descriptor.name());
                     }
                 }
             }
@@ -694,37 +737,38 @@
             for (ResolvedModule endpoint : reads) {
                 ModuleDescriptor descriptor2 = endpoint.descriptor();
 
-                for (ModuleDescriptor.Exports export : descriptor2.exports()) {
-
-                    if (export.isQualified()) {
-                        if (!export.targets().contains(descriptor1.name()))
-                            continue;
-                    }
-
-                    // source is exported to descriptor2
-                    String source = export.source();
-                    ModuleDescriptor other
-                        = packageToExporter.putIfAbsent(source, descriptor2);
+                if (descriptor2.isAutomatic()) {
+                    // automatic modules read self and export all packages
+                    if (descriptor2 != descriptor1){
+                        for (String source : descriptor2.packages()) {
+                            ModuleDescriptor supplier
+                                = packageToExporter.putIfAbsent(source, descriptor2);
 
-                    if (other != null && other != descriptor2) {
-                        // package might be local to descriptor1
-                        if (other == descriptor1) {
-                            fail("Module %s contains package %s"
-                                 + ", module %s exports package %s to %s",
-                                    descriptor1.name(),
-                                    source,
-                                    descriptor2.name(),
-                                    source,
-                                    descriptor1.name());
-                        } else {
-                            fail("Modules %s and %s export package %s to module %s",
-                                    descriptor2.name(),
-                                    other.name(),
-                                    source,
-                                    descriptor1.name());
+                            // descriptor2 and 'supplier' export source to descriptor1
+                            if (supplier != null) {
+                                failTwoSuppliers(descriptor1, source, descriptor2, supplier);
+                            }
                         }
 
                     }
+                } else {
+                    for (ModuleDescriptor.Exports export : descriptor2.exports()) {
+                        if (export.isQualified()) {
+                            if (!export.targets().contains(descriptor1.name()))
+                                continue;
+                        }
+
+                        // source is exported by descriptor2
+                        String source = export.source();
+                        ModuleDescriptor supplier
+                            = packageToExporter.putIfAbsent(source, descriptor2);
+
+                        // descriptor2 and 'supplier' export source to descriptor1
+                        if (supplier != null) {
+                            failTwoSuppliers(descriptor1, source, descriptor2, supplier);
+                        }
+                    }
+
                 }
             }
 
@@ -735,8 +779,8 @@
                 for (String service : descriptor1.uses()) {
                     String pn = packageName(service);
                     if (!packageToExporter.containsKey(pn)) {
-                        fail("Module %s does not read a module that exports %s",
-                             descriptor1.name(), pn);
+                        resolveFail("Module %s does not read a module that exports %s",
+                                    descriptor1.name(), pn);
                     }
                 }
 
@@ -744,15 +788,8 @@
                 for (ModuleDescriptor.Provides provides : descriptor1.provides()) {
                     String pn = packageName(provides.service());
                     if (!packageToExporter.containsKey(pn)) {
-                        fail("Module %s does not read a module that exports %s",
-                             descriptor1.name(), pn);
-                    }
-
-                    for (String provider : provides.providers()) {
-                        if (!packages.contains(packageName(provider))) {
-                            fail("Provider %s not in module %s",
-                                 provider, descriptor1.name());
-                        }
+                        resolveFail("Module %s does not read a module that exports %s",
+                                    descriptor1.name(), pn);
                     }
                 }
 
@@ -763,6 +800,42 @@
     }
 
     /**
+     * Fail because a module in the configuration exports the same package to
+     * a module that reads both. This includes the case where a module M
+     * containing a package p reads another module that exports p to at least
+     * module M.
+     */
+    private void failTwoSuppliers(ModuleDescriptor descriptor,
+                                  String source,
+                                  ModuleDescriptor supplier1,
+                                  ModuleDescriptor supplier2) {
+
+        if (supplier2 == descriptor) {
+            ModuleDescriptor tmp = supplier1;
+            supplier1 = supplier2;
+            supplier2 = tmp;
+        }
+
+        if (supplier1 == descriptor) {
+            resolveFail("Module %s contains package %s"
+                         + ", module %s exports package %s to %s",
+                    descriptor.name(),
+                    source,
+                    supplier2.name(),
+                    source,
+                    descriptor.name());
+        } else {
+            resolveFail("Modules %s and %s export package %s to module %s",
+                    supplier1.name(),
+                    supplier2.name(),
+                    source,
+                    descriptor.name());
+        }
+
+    }
+
+
+    /**
      * Find a module of the given name in the parent configurations
      */
     private ResolvedModule findInParent(String mn) {
@@ -779,24 +852,16 @@
      * Invokes the beforeFinder to find method to find the given module.
      */
     private ModuleReference findWithBeforeFinder(String mn) {
-        try {
-            return beforeFinder.find(mn).orElse(null);
-        } catch (FindException e) {
-            // unwrap
-            throw new ResolutionException(e.getMessage(), e.getCause());
-        }
+
+        return beforeFinder.find(mn).orElse(null);
+
     }
 
     /**
      * Invokes the afterFinder to find method to find the given module.
      */
     private ModuleReference findWithAfterFinder(String mn) {
-        try {
-            return afterFinder.find(mn).orElse(null);
-        } catch (FindException e) {
-            // unwrap
-            throw new ResolutionException(e.getMessage(), e.getCause());
-        }
+        return afterFinder.find(mn).orElse(null);
     }
 
     /**
@@ -804,34 +869,27 @@
      * and after ModuleFinders.
      */
     private Set<ModuleReference> findAll() {
-        try {
-
-            Set<ModuleReference> beforeModules = beforeFinder.findAll();
-            Set<ModuleReference> afterModules = afterFinder.findAll();
+        Set<ModuleReference> beforeModules = beforeFinder.findAll();
+        Set<ModuleReference> afterModules = afterFinder.findAll();
 
-            if (afterModules.isEmpty())
-                return beforeModules;
+        if (afterModules.isEmpty())
+            return beforeModules;
 
-            if (beforeModules.isEmpty()
-                    && parents.size() == 1
-                    && parents.get(0) == Configuration.empty())
-                return afterModules;
+        if (beforeModules.isEmpty()
+                && parents.size() == 1
+                && parents.get(0) == Configuration.empty())
+            return afterModules;
 
-            Set<ModuleReference> result = new HashSet<>(beforeModules);
-            for (ModuleReference mref : afterModules) {
-                String name = mref.descriptor().name();
-                if (!beforeFinder.find(name).isPresent()
-                        && findInParent(name) == null) {
-                    result.add(mref);
-                }
+        Set<ModuleReference> result = new HashSet<>(beforeModules);
+        for (ModuleReference mref : afterModules) {
+            String name = mref.descriptor().name();
+            if (!beforeFinder.find(name).isPresent()
+                    && findInParent(name) == null) {
+                result.add(mref);
             }
-
-            return result;
+        }
 
-        } catch (FindException e) {
-            // unwrap
-            throw new ResolutionException(e.getMessage(), e.getCause());
-        }
+        return result;
     }
 
     /**
@@ -843,9 +901,17 @@
     }
 
     /**
+     * Throw FindException with the given format string and arguments
+     */
+    private static void findFail(String fmt, Object ... args) {
+        String msg = String.format(fmt, args);
+        throw new FindException(msg);
+    }
+
+    /**
      * Throw ResolutionException with the given format string and arguments
      */
-    private static void fail(String fmt, Object ... args) {
+    private static void resolveFail(String fmt, Object ... args) {
         String msg = String.format(fmt, args);
         throw new ResolutionException(msg);
     }
--- a/jdk/src/java.base/share/classes/java/lang/module/package-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/module/package-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,112 @@
  * Classes to support module descriptors and creating configurations of modules
  * by means of resolution and service binding.
  *
+ * <h2><a name="resolution">Resolution</a></h2>
+ *
+ * <p> Resolution is the process of computing the transitive closure of a set
+ * of root modules over a set of observable modules by resolving the
+ * dependences expressed by {@link
+ * java.lang.module.ModuleDescriptor.Requires requires} clauses.
+ * The <em>dependence graph</em> is augmented with edges that take account of
+ * implicitly declared dependences ({@code requires transitive}) to create a
+ * <em>readability graph</em>. The result of resolution is a {@link
+ * java.lang.module.Configuration Configuration} that encapsulates the
+ * readability graph. </p>
+ *
+ * <p> As an example, suppose we have the following observable modules: </p>
+ * <pre> {@code
+ *     module m1 { requires m2; }
+ *     module m2 { requires transitive m3; }
+ *     module m3 { }
+ *     module m4 { }
+ * } </pre>
+ *
+ * <p> If the module {@code m1} is resolved then the resulting configuration
+ * contains three modules ({@code m1}, {@code m2}, {@code m3}). The edges in
+ * its readability graph are: </p>
+ * <pre> {@code
+ *     m1 --> m2  (meaning m1 reads m2)
+ *     m1 --> m3
+ *     m2 --> m3
+ * } </pre>
+ *
+ * <p> Resolution is an additive process. When computing the transitive closure
+ * then the dependence relation may include dependences on modules in {@link
+ * java.lang.module.Configuration#parents() parent} configurations. The result
+ * is a <em>relative configuration</em> that is relative to one or more parent
+ * configurations and where the readability graph may have edges from modules
+ * in the configuration to modules in parent configurations. </p>
+ *
+ * <p> As an example, suppose we have the following observable modules: </p>
+ * <pre> {@code
+ *     module m1 { requires m2; requires java.xml; }
+ *     module m2 { }
+ * } </pre>
+ *
+ * <p> If module {@code m1} is resolved with the configuration for the {@link
+ * java.lang.reflect.Layer#boot() boot} layer as the parent then the resulting
+ * configuration contains two modules ({@code m1}, {@code m2}). The edges in
+ * its readability graph are:
+ * <pre> {@code
+ *     m1 --> m2
+ *     m1 --> java.xml
+ * } </pre>
+ * where module {@code java.xml} is in the parent configuration. For
+ * simplicity, this example omits the implicitly declared dependence on the
+ * {@code java.base} module.
+ *
+ * <p> Requires clauses that are "{@code requires static}" express an optional
+ * dependence (except at compile-time). If a module declares that it
+ * "{@code requires static M}" then resolution does not search the observable
+ * modules for "{@code M}". However, if "{@code M}" is resolved (because resolution
+ * resolves a module that requires "{@code M}" without the {@link
+ * java.lang.module.ModuleDescriptor.Requires.Modifier#STATIC static} modifier)
+ * then the readability graph will contain read edges for each module that
+ * "{@code requires static M}". </p>
+ *
+ * <p> {@link java.lang.module.ModuleDescriptor#isAutomatic() Automatic} modules
+ * receive special treatment during resolution. Each automatic module is resolved
+ * so that it reads all other modules in the configuration and all parent
+ * configurations. Each automatic module is also resolved as if it
+ * "{@code requires transitive}" all other automatic modules in the configuration
+ * (and all automatic modules in parent configurations). </p>
+ *
+ * <h2><a name="servicebinding">Service binding</a></h2>
+ *
+ * <p> Service binding is the process of augmenting a graph of resolved modules
+ * from the set of observable modules induced by the service-use dependence
+ * ({@code uses} and {@code provides} clauses). Any module that was not
+ * previously in the graph requires resolution to compute its transitive
+ * closure. Service binding is an iterative process in that adding a module
+ * that satisfies some service-use dependence may introduce new service-use
+ * dependences. </p>
+ *
+ * <p> Suppose we have the following observable modules: </p>
+ * <pre> {@code
+ *     module m1 { exports p; uses p.S; }
+ *     module m2 { requires m1; provides p.S with p2.S2; }
+ *     module m3 { requires m1; requires m4; provides p.S with p3.S3; }
+ *     module m4 { }
+ * } </pre>
+ *
+ * <p> If the module {@code m1} is resolved then the resulting graph of modules
+ * has one module ({@code m1}). If the graph is augmented with modules induced
+ * by the service-use dependence relation then the configuration will contain
+ * four modules ({@code m1}, {@code m2}, {@code m3}, {@code m4}). The edges in
+ * its readability graph are: </p>
+ * <pre> {@code
+ *     m2 --> m1
+ *     m3 --> m1
+ *     m3 --> m4
+ * } </pre>
+ * <p> The edges in the conceptual service-use graph are: </p>
+ * <pre> {@code
+ *     m1 --> m2  (meaning m1 uses a service that is provided by m2)
+ *     m1 --> m3
+ * } </pre>
+ *
+ * <h2>General Exceptions</h2>
+ *
  * <p> Unless otherwise noted, passing a {@code null} argument to a constructor
  * or method of any class or interface in this package will cause a {@link
  * java.lang.NullPointerException NullPointerException} to be thrown. Additionally,
@@ -34,6 +140,7 @@
  * will cause a {@code NullPointerException}, unless otherwise specified. </p>
  *
  * @since 9
+ * @spec JPMS
  */
 
 package java.lang.module;
--- a/jdk/src/java.base/share/classes/java/lang/reflect/AccessibleObject.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/reflect/AccessibleObject.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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,38 +28,44 @@
 import java.lang.annotation.Annotation;
 import java.security.AccessController;
 
-import jdk.internal.misc.VM;
 import jdk.internal.reflect.CallerSensitive;
 import jdk.internal.reflect.Reflection;
 import jdk.internal.reflect.ReflectionFactory;
-import sun.security.action.GetPropertyAction;
 
 /**
- * The AccessibleObject class is the base class for Field, Method and
- * Constructor objects.  It provides the ability to flag a reflected
- * object as suppressing default Java language access control checks
- * when it is used. The access checks -- <em>module boundaries</em>,
- * public, default (package) access, protected, and private members --
- * are performed when Fields, Methods or Constructors are used to set
- * or get fields, to invoke methods or to create and initialize new
- * instances of classes, respectively. Unlike access control specified
- * in the <cite>The Java&trade; Language Specification</cite> and
- * <cite>The Java Virtual Machine Specification</cite>, access checks
- * with reflected objects assume {@link Module#canRead readability}.
+ * The {@code AccessibleObject} class is the base class for {@code Field},
+ * {@code Method}, and {@code Constructor} objects (known as <em>reflected
+ * objects</em>). It provides the ability to flag a reflected object as
+ * suppressing checks for Java language access control when it is used. This
+ * permits sophisticated applications with sufficient privilege, such as Java
+ * Object Serialization or other persistence mechanisms, to manipulate objects
+ * in a manner that would normally be prohibited.
  *
- * <p>Setting the {@code accessible} flag in a reflected object
- * permits sophisticated applications with sufficient privilege, such
- * as Java Object Serialization or other persistence mechanisms, to
- * manipulate objects in a manner that would normally be prohibited.
- *
- * <p>By default, a reflected object is <em>not</em> accessible.
+ * <p> Java language access control prevents use of private members outside
+ * their class; package access members outside their package; protected members
+ * outside their package or subclasses; and public members outside their
+ * module unless they are declared in an {@link Module#isExported(String,Module)
+ * exported} package and the user {@link Module#canRead reads} their module. By
+ * default, Java language access control is enforced (with one variation) when
+ * {@code Field}s, {@code Method}s, or {@code Constructor}s are used to get or
+ * set fields, to invoke methods, or to create and initialize new instances of
+ * classes, respectively. Every reflected object checks that the code using it
+ * is in an appropriate class, package, or module. </p>
  *
- * @see Field
- * @see Method
- * @see Constructor
- * @see ReflectPermission
+ * <p> The one variation from Java language access control is that the checks
+ * by reflected objects assume readability. That is, the module containing
+ * the use of a reflected object is assumed to read the module in which
+ * the underlying field, method, or constructor is declared. </p>
  *
+ * <p> Whether the checks for Java language access control can be suppressed
+ * (and thus, whether access can be enabled) depends on whether the reflected
+ * object corresponds to a member in an exported or open package
+ * (see {@link #setAccessible(boolean)}). </p>
+ *
+ * @jls 6.6 Access Control
  * @since 1.2
+ * @revised 9
+ * @spec JPMS
  */
 public class AccessibleObject implements AnnotatedElement {
 
@@ -78,15 +84,11 @@
 
     /**
      * Convenience method to set the {@code accessible} flag for an
-     * array of objects with a single security check (for efficiency).
+     * array of reflected objects with a single security check (for efficiency).
      *
-     * <p>This method cannot be used to enable access to an object that is a
-     * {@link Member member} of a class in a different module to the caller and
-     * where the class is in a package that is not exported to the caller's
-     * module. Additionally, if the member is non-public or its declaring
-     * class is non-public, then this method can only be used to enable access
-     * if the package is {@link Module#isOpen(String,Module) open} to at least
-     * the caller's module.
+     * <p> This method may be used to enable access to all reflected objects in
+     * the array when access to each reflected object can be enabled as
+     * specified by {@link #setAccessible(boolean) setAccessible(boolean)}. </p>
      *
      * <p>If there is a security manager, its
      * {@code checkPermission} method is first called with a
@@ -99,10 +101,15 @@
      * @param array the array of AccessibleObjects
      * @param flag  the new value for the {@code accessible} flag
      *              in each object
-     * @throws InaccessibleObjectException if access cannot be enabled
-     * @throws SecurityException if the request is denied.
+     * @throws InaccessibleObjectException if access cannot be enabled for all
+     *         objects in the array
+     * @throws SecurityException if the request is denied by the security manager
+     *         or an element in the array is a constructor for {@code
+     *         java.lang.Class}
      * @see SecurityManager#checkPermission
      * @see ReflectPermission
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static void setAccessible(AccessibleObject[] array, boolean flag) {
@@ -120,41 +127,143 @@
     }
 
     /**
-     * Set the {@code accessible} flag for this object to
+     * Set the {@code accessible} flag for this reflected object to
      * the indicated boolean value.  A value of {@code true} indicates that
-     * the reflected object should suppress Java language access
-     * checking when it is used.  A value of {@code false} indicates
-     * that the reflected object should enforce Java language access checks
-     * while assuming readability (as noted in the class description).
+     * the reflected object should suppress checks for Java language access
+     * control when it is used. A value of {@code false} indicates that
+     * the reflected object should enforce checks for Java language access
+     * control when it is used, with the variation noted in the class description.
+     *
+     * <p> This method may be used by a caller in class {@code C} to enable
+     * access to a {@link Member member} of {@link Member#getDeclaringClass()
+     * declaring class} {@code D} if any of the following hold: </p>
+     *
+     * <ul>
+     *     <li> {@code C} and {@code D} are in the same module. </li>
+     *
+     *     <li> The member is {@code public} and {@code D} is {@code public} in
+     *     a package that the module containing {@code D} {@link
+     *     Module#isExported(String,Module) exports} to at least the module
+     *     containing {@code C}. </li>
      *
-     * <p>This method cannot be used to enable access to an object that is a
-     * {@link Member member} of a class in a different module to the caller and
-     * where the class is in a package that is not exported to the caller's
-     * module. Additionally, if the member is non-public or its declaring
-     * class is non-public, then this method can only be used to enable access
-     * if the package is {@link Module#isOpen(String,Module) open} to at least
-     * the caller's module.
+     *     <li> The member is {@code protected} {@code static}, {@code D} is
+     *     {@code public} in a package that the module containing {@code D}
+     *     exports to at least the module containing {@code C}, and {@code C}
+     *     is a subclass of {@code D}. </li>
      *
-     * <p>If there is a security manager, its
+     *     <li> {@code D} is in a package that the module containing {@code D}
+     *     {@link Module#isOpen(String,Module) opens} to at least the module
+     *     containing {@code C}.
+     *     All packages in unnamed and open modules are open to all modules and
+     *     so this method always succeeds when {@code D} is in an unnamed or
+     *     open module. </li>
+     * </ul>
+     *
+     * <p> This method cannot be used to enable access to private members,
+     * members with default (package) access, protected instance members, or
+     * protected constructors when the declaring class is in a different module
+     * to the caller and the package containing the declaring class is not open
+     * to the caller's module. </p>
+     *
+     * <p> If there is a security manager, its
      * {@code checkPermission} method is first called with a
      * {@code ReflectPermission("suppressAccessChecks")} permission.
      *
      * @param flag the new value for the {@code accessible} flag
      * @throws InaccessibleObjectException if access cannot be enabled
-     * @throws SecurityException if the request is denied
-     * @see SecurityManager#checkPermission
-     * @see ReflectPermission
+     * @throws SecurityException if the request is denied by the security manager
+     * @see #trySetAccessible
      * @see java.lang.invoke.MethodHandles#privateLookupIn
+     * @revised 9
+     * @spec JPMS
      */
     public void setAccessible(boolean flag) {
         AccessibleObject.checkPermission();
         setAccessible0(flag);
     }
 
-    void setAccessible0(boolean flag) {
+    /**
+     * Sets the accessible flag and returns the new value
+     */
+    boolean setAccessible0(boolean flag) {
         this.override = flag;
+        return flag;
     }
 
+    /**
+     * Set the {@code accessible} flag for this reflected object to {@code true}
+     * if possible. This method sets the {@code accessible} flag, as if by
+     * invoking {@link #setAccessible(boolean) setAccessible(true)}, and returns
+     * the possibly-updated value for the {@code accessible} flag. If access
+     * cannot be enabled, i.e. the checks or Java language access control cannot
+     * be suppressed, this method returns {@code false} (as opposed to {@code
+     * setAccessible(true)} throwing {@code InaccessibleObjectException} when
+     * it fails).
+     *
+     * <p> This method is a no-op if the {@code accessible} flag for
+     * this reflected object is {@code true}.
+     *
+     * <p> For example, a caller can invoke {@code trySetAccessible}
+     * on a {@code Method} object for a private instance method
+     * {@code p.T::privateMethod} to suppress the checks for Java language access
+     * control when the {@code Method} is invoked.
+     * If {@code p.T} class is in a different module to the caller and
+     * package {@code p} is open to at least the caller's module,
+     * the code below successfully sets the {@code accessible} flag
+     * to {@code true}.
+     *
+     * <pre>
+     * {@code
+     *     p.T obj = ....;  // instance of p.T
+     *     :
+     *     Method m = p.T.class.getDeclaredMethod("privateMethod");
+     *     if (m.trySetAccessible()) {
+     *         m.invoke(obj);
+     *     } else {
+     *         // package p is not opened to the caller to access private member of T
+     *         ...
+     *     }
+     * }</pre>
+     *
+     * <p> If there is a security manager, its {@code checkPermission} method
+     * is first called with a {@code ReflectPermission("suppressAccessChecks")}
+     * permission. </p>
+     *
+     * @return {@code true} if the {@code accessible} flag is set to {@code true};
+     *         {@code false} if access cannot be enabled.
+     * @throws SecurityException if the request is denied by the security manager
+     *
+     * @since 9
+     * @spec JPMS
+     * @see java.lang.invoke.MethodHandles#privateLookupIn
+     */
+    @CallerSensitive
+    public final boolean trySetAccessible() {
+        AccessibleObject.checkPermission();
+
+        if (override == true) return true;
+
+        // if it's not a Constructor, Method, Field then no access check
+        if (!Member.class.isInstance(this)) {
+            return setAccessible0(true);
+        }
+
+        // does not allow to suppress access check for Class's constructor
+        Class<?> declaringClass = ((Member) this).getDeclaringClass();
+        if (declaringClass == Class.class && this instanceof Constructor) {
+            return false;
+        }
+
+        if (checkCanSetAccessible(Reflection.getCallerClass(),
+                                  declaringClass,
+                                  false)) {
+            return setAccessible0(true);
+        } else {
+            return false;
+        }
+    }
+
+
    /**
     * If the given AccessibleObject is a {@code Constructor}, {@code Method}
     * or {@code Field} then checks that its declaring class is in a package
@@ -164,22 +273,29 @@
         // do nothing, needs to be overridden by Constructor, Method, Field
     }
 
+
     void checkCanSetAccessible(Class<?> caller, Class<?> declaringClass) {
+        checkCanSetAccessible(caller, declaringClass, true);
+    }
+
+    private boolean checkCanSetAccessible(Class<?> caller,
+                                          Class<?> declaringClass,
+                                          boolean throwExceptionIfDenied) {
         Module callerModule = caller.getModule();
         Module declaringModule = declaringClass.getModule();
 
-        if (callerModule == declaringModule) return;
-        if (callerModule == Object.class.getModule()) return;
-        if (!declaringModule.isNamed()) return;
+        if (callerModule == declaringModule) return true;
+        if (callerModule == Object.class.getModule()) return true;
+        if (!declaringModule.isNamed()) return true;
 
         // package is open to caller
         String pn = packageName(declaringClass);
         if (declaringModule.isOpen(pn, callerModule)) {
-            printStackTraceIfOpenedReflectively(declaringModule, pn, callerModule);
-            return;
+            dumpStackIfOpenedReflectively(declaringModule, pn, callerModule);
+            return true;
         }
 
-        // package is exported to caller and class/member is public
+        // package is exported to caller
         boolean isExported = declaringModule.isExported(pn, callerModule);
         boolean isClassPublic = Modifier.isPublic(declaringClass.getModifiers());
         int modifiers;
@@ -188,48 +304,72 @@
         } else {
             modifiers = ((Field) this).getModifiers();
         }
-        boolean isMemberPublic = Modifier.isPublic(modifiers);
-        if (isExported && isClassPublic && isMemberPublic) {
-            printStackTraceIfExportedReflectively(declaringModule, pn, callerModule);
-            return;
+        if (isExported && isClassPublic) {
+
+            // member is public
+            if (Modifier.isPublic(modifiers)) {
+                dumpStackIfExportedReflectively(declaringModule, pn, callerModule);
+                return true;
+            }
+
+            // member is protected-static
+            if (Modifier.isProtected(modifiers)
+                && Modifier.isStatic(modifiers)
+                && isSubclassOf(caller, declaringClass)) {
+                dumpStackIfExportedReflectively(declaringModule, pn, callerModule);
+                return true;
+            }
         }
 
-        // not accessible
-        String msg = "Unable to make ";
-        if (this instanceof Field)
-            msg += "field ";
-        msg += this + " accessible: " + declaringModule + " does not \"";
-        if (isClassPublic && isMemberPublic)
-            msg += "exports";
-        else
-            msg += "opens";
-        msg += " " + pn + "\" to " + callerModule;
-        InaccessibleObjectException e = new InaccessibleObjectException(msg);
-        if (Reflection.printStackTraceWhenAccessFails()) {
-            e.printStackTrace(System.err);
+        if (throwExceptionIfDenied) {
+            // not accessible
+            String msg = "Unable to make ";
+            if (this instanceof Field)
+                msg += "field ";
+            msg += this + " accessible: " + declaringModule + " does not \"";
+            if (isClassPublic && Modifier.isPublic(modifiers))
+                msg += "exports";
+            else
+                msg += "opens";
+            msg += " " + pn + "\" to " + callerModule;
+            InaccessibleObjectException e = new InaccessibleObjectException(msg);
+            if (Reflection.printStackTraceWhenAccessFails()) {
+                e.printStackTrace(System.err);
+            }
+            throw e;
         }
-        throw e;
+        return false;
     }
 
-    private void printStackTraceIfOpenedReflectively(Module module,
-                                                     String pn,
-                                                     Module other) {
-        printStackTraceIfExposedReflectively(module, pn, other, true);
+    private boolean isSubclassOf(Class<?> queryClass, Class<?> ofClass) {
+        while (queryClass != null) {
+            if (queryClass == ofClass) {
+                return true;
+            }
+            queryClass = queryClass.getSuperclass();
+        }
+        return false;
     }
 
-    private void printStackTraceIfExportedReflectively(Module module,
-                                                       String pn,
-                                                       Module other) {
-        printStackTraceIfExposedReflectively(module, pn, other, false);
+    private void dumpStackIfOpenedReflectively(Module module,
+                                               String pn,
+                                               Module other) {
+        dumpStackIfExposedReflectively(module, pn, other, true);
     }
 
-    private void printStackTraceIfExposedReflectively(Module module,
-                                                      String pn,
-                                                      Module other,
-                                                      boolean open)
+    private void dumpStackIfExportedReflectively(Module module,
+                                                 String pn,
+                                                 Module other) {
+        dumpStackIfExposedReflectively(module, pn, other, false);
+    }
+
+    private void dumpStackIfExposedReflectively(Module module,
+                                                String pn,
+                                                Module other,
+                                                boolean open)
     {
         if (Reflection.printStackTraceWhenAccessSucceeds()
-            && !module.isStaticallyExportedOrOpen(pn, other, open))
+                && !module.isStaticallyExportedOrOpen(pn, other, open))
         {
             String msg = other + " allowed to invoke setAccessible on ";
             if (this instanceof Field)
@@ -256,15 +396,100 @@
     }
 
     /**
-     * Get the value of the {@code accessible} flag for this object.
+     * Get the value of the {@code accessible} flag for this reflected object.
      *
      * @return the value of the object's {@code accessible} flag
+     *
+     * @deprecated
+     * This method is deprecated because its name hints that it checks
+     * if the reflected object is accessible when it actually indicates
+     * if the checks for Java language access control are suppressed.
+     * This method may return {@code false} on a reflected object that is
+     * accessible to the caller. To test if this reflected object is accessible,
+     * it should use {@link #canAccess(Object)}.
+     *
+     * @revised 9
      */
+    @Deprecated(since="9")
     public boolean isAccessible() {
         return override;
     }
 
     /**
+     * Test if the caller can access this reflected object. If this reflected
+     * object corresponds to an instance method or field then this method tests
+     * if the caller can access the given {@code obj} with the reflected object.
+     * For instance methods or fields then the {@code obj} argument must be an
+     * instance of the {@link Member#getDeclaringClass() declaring class}. For
+     * static members and constructors then {@code obj} must be {@code null}.
+     *
+     * <p> This method returns {@code true} if the {@code accessible} flag
+     * is set to {@code true}, i.e. the checks for Java language access control
+     * are suppressed, or if the caller can access the member as
+     * specified in <cite>The Java&trade; Language Specification</cite>,
+     * with the variation noted in the class description. </p>
+     *
+     * @param obj an instance object of the declaring class of this reflected
+     *            object if it is an instance method or field
+     *
+     * @return {@code true} if the caller can access this reflected object.
+     *
+     * @throws IllegalArgumentException
+     *         <ul>
+     *         <li> if this reflected object is a static member or constructor and
+     *              the given {@code obj} is non-{@code null}, or </li>
+     *         <li> if this reflected object is an instance method or field
+     *              and the given {@code obj} is {@code null} or of type
+     *              that is not a subclass of the {@link Member#getDeclaringClass()
+     *              declaring class} of the member.</li>
+     *         </ul>
+     *
+     * @since 9
+     * @spec JPMS
+     * @jls 6.6 Access Control
+     * @see #trySetAccessible
+     * @see #setAccessible(boolean)
+     */
+    @CallerSensitive
+    public final boolean canAccess(Object obj) {
+        if (!Member.class.isInstance(this)) {
+            return override;
+        }
+
+        Class<?> declaringClass = ((Member) this).getDeclaringClass();
+        int modifiers = ((Member) this).getModifiers();
+        if (!Modifier.isStatic(modifiers) &&
+                (this instanceof Method || this instanceof Field)) {
+            if (obj == null) {
+                throw new IllegalArgumentException("null object for " + this);
+            }
+            // if this object is an instance member, the given object
+            // must be a subclass of the declaring class of this reflected object
+            if (!declaringClass.isAssignableFrom(obj.getClass())) {
+                throw new IllegalArgumentException("object is not an instance of "
+                                                   + declaringClass.getName());
+            }
+        } else if (obj != null) {
+            throw new IllegalArgumentException("non-null object for " + this);
+        }
+
+        // access check is suppressed
+        if (override) return true;
+
+        Class<?> caller = Reflection.getCallerClass();
+        Class<?> targetClass;
+        if (this instanceof Constructor) {
+            targetClass = declaringClass;
+        } else {
+            targetClass = Modifier.isStatic(modifiers) ? null : obj.getClass();
+        }
+        return Reflection.verifyMemberAccess(caller,
+                                             declaringClass,
+                                             targetClass,
+                                             modifiers);
+    }
+
+    /**
      * Constructor: only used by the Java Virtual Machine.
      */
     protected AccessibleObject() {}
--- a/jdk/src/java.base/share/classes/java/lang/reflect/Constructor.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/reflect/Constructor.java	Thu Mar 16 20:47:03 2017 +0000
@@ -168,6 +168,13 @@
      * is true. </p>
      *
      * @param flag {@inheritDoc}
+     *
+     * @throws InaccessibleObjectException {@inheritDoc}
+     * @throws SecurityException if the request is denied by the security manager
+     *         or this is a constructor for {@code java.lang.Class}
+     *
+     * @since 9
+     * @spec JPMS
      */
     @Override
     @CallerSensitive
--- a/jdk/src/java.base/share/classes/java/lang/reflect/Field.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/reflect/Field.java	Thu Mar 16 20:47:03 2017 +0000
@@ -158,6 +158,10 @@
         return res;
     }
 
+    /**
+     * @throws InaccessibleObjectException {@inheritDoc}
+     * @throws SecurityException {@inheritDoc}
+     */
     @Override
     @CallerSensitive
     public void setAccessible(boolean flag) {
--- a/jdk/src/java.base/share/classes/java/lang/reflect/InaccessibleObjectException.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/reflect/InaccessibleObjectException.java	Thu Mar 16 20:47:03 2017 +0000
@@ -30,6 +30,7 @@
  *
  * @see AccessibleObject#setAccessible(boolean)
  * @since 9
+ * @spec JPMS
  */
 
 public class InaccessibleObjectException extends RuntimeException {
--- a/jdk/src/java.base/share/classes/java/lang/reflect/Layer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/reflect/Layer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -56,20 +56,19 @@
 /**
  * A layer of modules in the Java virtual machine.
  *
- * <p> A layer is created from a graph of modules that is the {@link
- * Configuration} and a function that maps each module to a {@link ClassLoader}.
+ * <p> A layer is created from a graph of modules in a {@link Configuration}
+ * and a function that maps each module to a {@link ClassLoader}.
  * Creating a layer informs the Java virtual machine about the classes that
- * may be loaded from modules so that the Java virtual machine knows which
- * module that each class is a member of. Each layer, except the {@link
- * #empty() empty} layer, has at least one {@link #parents() parent}. </p>
+ * may be loaded from the modules so that the Java virtual machine knows which
+ * module that each class is a member of. </p>
  *
  * <p> Creating a layer creates a {@link Module} object for each {@link
  * ResolvedModule} in the configuration. For each resolved module that is
  * {@link ResolvedModule#reads() read}, the {@code Module} {@link
  * Module#canRead reads} the corresponding run-time {@code Module}, which may
- * be in the same layer or a parent layer. The {@code Module} {@link
- * Module#isExported(String) exports} the packages described by its {@link
- * ModuleDescriptor}. </p>
+ * be in the same layer or a {@link #parents() parent} layer. The {@code Module}
+ * {@link Module#isExported(String) exports} and {@link Module#isOpen(String)
+ * opens} the packages described by its {@link ModuleDescriptor}. </p>
  *
  * <p> The {@link #defineModulesWithOneLoader defineModulesWithOneLoader} and
  * {@link #defineModulesWithManyLoaders defineModulesWithManyLoaders} methods
@@ -80,7 +79,7 @@
  * a function specified to the method. Each of these methods has an instance
  * and static variant. The instance methods create a layer with the receiver
  * as the parent layer. The static methods are for more advanced cases where
- * there can be more than one parent layer or a {@link Layer.Controller
+ * there can be more than one parent layer or where a {@link Layer.Controller
  * Controller} is needed to control modules in the layer. </p>
  *
  * <p> A Java virtual machine has at least one non-empty layer, the {@link
@@ -93,9 +92,8 @@
  * the {@link #parents() parent} when creating additional layers. </p>
  *
  * <p> As when creating a {@code Configuration},
- * {@link ModuleDescriptor#isAutomatic() automatic} modules receive
- * <a href="../module/Configuration.html#automaticmoduleresolution">special
- * treatment</a> when creating a layer. An automatic module is created in the
+ * {@link ModuleDescriptor#isAutomatic() automatic} modules receive special
+ * treatment when creating a layer. An automatic module is created in the
  * Java virtual machine as a {@code Module} that reads every unnamed {@code
  * Module} in the Java virtual machine. </p>
  *
@@ -115,8 +113,7 @@
  *
  *     Layer parent = Layer.boot();
  *
- *     Configuration cf = parent.configuration()
- *         .resolveRequires(finder, ModuleFinder.of(), Set.of("myapp"));
+ *     Configuration cf = parent.configuration().resolve(finder, ModuleFinder.of(), Set.of("myapp"));
  *
  *     ClassLoader scl = ClassLoader.getSystemClassLoader();
  *
@@ -126,6 +123,7 @@
  * }</pre>
  *
  * @since 9
+ * @spec JPMS
  * @see Module#getLayer()
  */
 
@@ -168,10 +166,15 @@
      * module layers return a {@code Controller} that can be used to control
      * modules in the layer.
      *
+     * <p> Unless otherwise specified, passing a {@code null} argument to a
+     * method in this class causes a {@link NullPointerException
+     * NullPointerException} to be thrown. </p>
+     *
      * @apiNote Care should be taken with {@code Controller} objects, they
      * should never be shared with untrusted code.
      *
      * @since 9
+     * @spec JPMS
      */
     public static final class Controller {
         private final Layer layer;
@@ -281,10 +284,8 @@
      *         If the parent of the given configuration is not the configuration
      *         for this layer
      * @throws LayerInstantiationException
-     *         If all modules cannot be defined to the same class loader for any
-     *         of the reasons listed above or the layer cannot be created because
-     *         the configuration contains a module named "{@code java.base}" or
-     *         a module with a package name starting with "{@code java.}"
+     *         If the layer cannot be created for any of the reasons specified
+     *         by the static {@code defineModulesWithOneLoader} method
      * @throws SecurityException
      *         If {@code RuntimePermission("createClassLoader")} or
      *         {@code RuntimePermission("getClassLoader")} is denied by
@@ -325,9 +326,8 @@
      *         If the parent of the given configuration is not the configuration
      *         for this layer
      * @throws LayerInstantiationException
-     *         If the layer cannot be created because the configuration contains
-     *         a module named "{@code java.base}" or a module with a package
-     *         name starting with "{@code java.}"
+     *         If the layer cannot be created for any of the reasons specified
+     *         by the static {@code defineModulesWithManyLoaders} method
      * @throws SecurityException
      *         If {@code RuntimePermission("createClassLoader")} or
      *         {@code RuntimePermission("getClassLoader")} is denied by
@@ -365,14 +365,8 @@
      *         If the parent of the given configuration is not the configuration
      *         for this layer
      * @throws LayerInstantiationException
-     *         If creating the {@code Layer} fails for any of the reasons
-     *         listed above, the layer cannot be created because the
-     *         configuration contains a module named "{@code java.base}",
-     *         a module with a package name starting with "{@code java.}" is
-     *         mapped to a class loader other than the {@link
-     *         ClassLoader#getPlatformClassLoader() platform class loader},
-     *         or the function to map a module name to a class loader returns
-     *         {@code null}
+     *         If the layer cannot be created for any of the reasons specified
+     *         by the static {@code defineModules} method
      * @throws SecurityException
      *         If {@code RuntimePermission("getClassLoader")} is denied by
      *         the security manager
@@ -396,7 +390,6 @@
      * exported to one or more of the modules in this layer. The class
      * loader delegates to the class loader of the module, throwing {@code
      * ClassNotFoundException} if not found by that class loader.
-     *
      * When {@code loadClass} is invoked to load classes that do not map to a
      * module then it delegates to the parent class loader. </p>
      *
@@ -414,6 +407,10 @@
      *
      * </ul>
      *
+     * <p> In addition, a layer cannot be created if the configuration contains
+     * a module named "{@code java.base}" or a module with a package name
+     * starting with "{@code java.}". </p>
+     *
      * <p> If there is a security manager then the class loader created by
      * this method will load classes and resources with privileges that are
      * restricted by the calling context of this method. </p>
@@ -433,9 +430,7 @@
      *         the parent layers, including order
      * @throws LayerInstantiationException
      *         If all modules cannot be defined to the same class loader for any
-     *         of the reasons listed above or the layer cannot be created because
-     *         the configuration contains a module named "{@code java.base}" or
-     *         a module with a package name starting with "{@code java.}"
+     *         of the reasons listed above
      * @throws SecurityException
      *         If {@code RuntimePermission("createClassLoader")} or
      *         {@code RuntimePermission("getClassLoader")} is denied by
@@ -480,7 +475,6 @@
      * module in a parent layer. The class loader delegates to the class loader
      * of the module, throwing {@code ClassNotFoundException} if not found by
      * that class loader.
-     *
      * When {@code loadClass} is invoked to load classes that do not map to a
      * module then it delegates to the parent class loader. </p>
      *
@@ -533,15 +527,19 @@
 
     /**
      * Creates a new layer by defining the modules in the given {@code
-     * Configuration} to the Java virtual machine.
-     * Each module is mapped, by name, to its class loader by means of the
-     * given function. The class loader delegation implemented by these class
-     * loaders must respect module readability. The class loaders should be
+     * Configuration} to the Java virtual machine. The given function maps each
+     * module in the configuration, by name, to a class loader. Creating the
+     * layer informs the Java virtual machine about the classes that may be
+     * loaded so that the Java virtual machine knows which module that each
+     * class is a member of.
+     *
+     * <p> The class loader delegation implemented by the class loaders must
+     * respect module readability. The class loaders should be
      * {@link ClassLoader#registerAsParallelCapable parallel-capable} so as to
      * avoid deadlocks during class loading. In addition, the entity creating
-     * a new layer with this method should arrange that the class loaders are
+     * a new layer with this method should arrange that the class loaders be
      * ready to load from these modules before there are any attempts to load
-     * classes or resources.
+     * classes or resources. </p>
      *
      * <p> Creating a {@code Layer} can fail for the following reasons: </p>
      *
@@ -558,6 +556,13 @@
      *
      * </ul>
      *
+     * <p> In addition, a layer cannot be created if the configuration contains
+     * a module named "{@code java.base}", a configuration contains a module
+     * with a package name starting with "{@code java.}" is mapped to a class
+     * loader other than the {@link ClassLoader#getPlatformClassLoader()
+     * platform class loader}, or the function to map a module name to a class
+     * loader returns {@code null}. </p>
+     *
      * <p> If the function to map a module name to class loader throws an error
      * or runtime exception then it is propagated to the caller of this method.
      * </p>
@@ -565,7 +570,7 @@
      * @apiNote It is implementation specific as to whether creating a Layer
      * with this method is an atomic operation or not. Consequentially it is
      * possible for this method to fail with some modules, but not all, defined
-     * to Java virtual machine.
+     * to the Java virtual machine.
      *
      * @param  cf
      *         The configuration for the layer
@@ -580,14 +585,7 @@
      *         If the parent configurations do not match the configuration of
      *         the parent layers, including order
      * @throws LayerInstantiationException
-     *         If creating the {@code Layer} fails for any of the reasons
-     *         listed above, the layer cannot be created because the
-     *         configuration contains a module named "{@code java.base}",
-     *         a module with a package name starting with "{@code java.}" is
-     *         mapped to a class loader other than the {@link
-     *         ClassLoader#getPlatformClassLoader() platform class loader},
-     *         or the function to map a module name to a class loader returns
-     *         {@code null}
+     *         If creating the layer fails for any of the reasons listed above
      * @throws SecurityException
      *         If {@code RuntimePermission("getClassLoader")} is denied by
      *         the security manager
@@ -763,7 +761,7 @@
 
     /**
      * Returns the module with the given name in this layer, or if not in this
-     * layer, the {@linkplain #parents parents} layers. Finding a module in
+     * layer, the {@linkplain #parents parent} layers. Finding a module in
      * parent layers is equivalent to invoking {@code findModule} on each
      * parent, in search order, until the module is found or all parents have
      * been searched. In a <em>tree of layers</em>  then this is equivalent to
--- a/jdk/src/java.base/share/classes/java/lang/reflect/LayerInstantiationException.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/reflect/LayerInstantiationException.java	Thu Mar 16 20:47:03 2017 +0000
@@ -31,6 +31,7 @@
  * @see Layer
  *
  * @since 9
+ * @spec JPMS
  */
 public class LayerInstantiationException extends RuntimeException {
     private static final long serialVersionUID = -906239691613568347L;
--- a/jdk/src/java.base/share/classes/java/lang/reflect/Method.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/reflect/Method.java	Thu Mar 16 20:47:03 2017 +0000
@@ -179,6 +179,10 @@
         return res;
     }
 
+    /**
+     * @throws InaccessibleObjectException {@inheritDoc}
+     * @throws SecurityException {@inheritDoc}
+     */
     @Override
     @CallerSensitive
     public void setAccessible(boolean flag) {
--- a/jdk/src/java.base/share/classes/java/lang/reflect/Module.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/reflect/Module.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -39,7 +39,6 @@
 import java.net.URL;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
-import java.util.Collections;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.Map;
@@ -74,16 +73,15 @@
  * Java Virtual Machine when a graph of modules is defined to the Java virtual
  * machine to create a module {@link Layer Layer}. </p>
  *
- * <p> An unnamed module does not have a name. There is an unnamed module
- * per {@link ClassLoader ClassLoader} that is obtained by invoking the class
- * loader's {@link ClassLoader#getUnnamedModule() getUnnamedModule} method. The
- * {@link Class#getModule() getModule} method of all types defined by a class
- * loader that are not in a named module return the class loader's unnamed
+ * <p> An unnamed module does not have a name. There is an unnamed module for
+ * each {@link ClassLoader ClassLoader}, obtained by invoking its {@link
+ * ClassLoader#getUnnamedModule() getUnnamedModule} method. All types that are
+ * not in a named module are members of their defining class loader's unnamed
  * module. </p>
  *
  * <p> The package names that are parameters or returned by methods defined in
  * this class are the fully-qualified names of the packages as defined in
- * section 6.5.3 of <cite>The Java&trade; Language Specification </cite>, for
+ * section 6.5.3 of <cite>The Java&trade; Language Specification</cite>, for
  * example, {@code "java.lang"}. </p>
  *
  * <p> Unless otherwise specified, passing a {@code null} argument to a method
@@ -91,6 +89,7 @@
  * be thrown. </p>
  *
  * @since 9
+ * @spec JPMS
  * @see java.lang.Class#getModule
  */
 
@@ -327,8 +326,9 @@
      *
      * @return this module
      *
-     * @throws IllegalStateException
-     *         If this is a named module and the caller is not this module
+     * @throws IllegalCallerException
+     *         If this is a named module and the caller's module is not this
+     *         module
      *
      * @see #canRead
      */
@@ -338,7 +338,7 @@
         if (this.isNamed()) {
             Module caller = Reflection.getCallerClass().getModule();
             if (caller != this) {
-                throw new IllegalStateException(caller + " != " + this);
+                throw new IllegalCallerException(caller + " != " + this);
             }
             implAddReads(other, true);
         }
@@ -533,8 +533,8 @@
         if (other == this && containsPackage(pn))
             return true;
 
-        // all packages in open modules are open
-        if (descriptor.isOpen())
+        // all packages in open and automatic modules are open
+        if (descriptor.isOpen() || descriptor.isAutomatic())
             return containsPackage(pn);
 
         // exported/opened via module declaration/descriptor
@@ -634,8 +634,7 @@
      * the given package to the given module.
      *
      * <p> This method has no effect if the package is already exported (or
-     * <em>open</em>) to the given module. It also has no effect if
-     * invoked on an {@link ModuleDescriptor#isOpen open} module. </p>
+     * <em>open</em>) to the given module. </p>
      *
      * @apiNote As specified in section 5.4.3 of the <cite>The Java&trade;
      * Virtual Machine Specification </cite>, if an attempt to resolve a
@@ -653,8 +652,9 @@
      * @throws IllegalArgumentException
      *         If {@code pn} is {@code null}, or this is a named module and the
      *         package {@code pn} is not a package in this module
-     * @throws IllegalStateException
-     *         If this is a named module and the caller is not this module
+     * @throws IllegalCallerException
+     *         If this is a named module and the caller's module is not this
+     *         module
      *
      * @jvms 5.4.3 Resolution
      * @see #isExported(String,Module)
@@ -665,10 +665,10 @@
             throw new IllegalArgumentException("package is null");
         Objects.requireNonNull(other);
 
-        if (isNamed() && !descriptor.isOpen()) {
+        if (isNamed()) {
             Module caller = Reflection.getCallerClass().getModule();
             if (caller != this) {
-                throw new IllegalStateException(caller + " != " + this);
+                throw new IllegalCallerException(caller + " != " + this);
             }
             implAddExportsOrOpens(pn, other, /*open*/false, /*syncVM*/true);
         }
@@ -686,8 +686,7 @@
      * access control checks.
      *
      * <p> This method has no effect if the package is already <em>open</em>
-     * to the given module. It also has no effect if invoked on an {@link
-     * ModuleDescriptor#isOpen open} module. </p>
+     * to the given module. </p>
      *
      * @param  pn
      *         The package name
@@ -699,9 +698,9 @@
      * @throws IllegalArgumentException
      *         If {@code pn} is {@code null}, or this is a named module and the
      *         package {@code pn} is not a package in this module
-     * @throws IllegalStateException
+     * @throws IllegalCallerException
      *         If this is a named module and this module has not opened the
-     *         package to at least the caller
+     *         package to at least the caller's module
      *
      * @see #isOpen(String,Module)
      * @see AccessibleObject#setAccessible(boolean)
@@ -713,10 +712,10 @@
             throw new IllegalArgumentException("package is null");
         Objects.requireNonNull(other);
 
-        if (isNamed() && !descriptor.isOpen()) {
+        if (isNamed()) {
             Module caller = Reflection.getCallerClass().getModule();
             if (caller != this && !isOpen(pn, caller))
-                throw new IllegalStateException(pn + " is not open to " + caller);
+                throw new IllegalCallerException(pn + " is not open to " + caller);
             implAddExportsOrOpens(pn, other, /*open*/true, /*syncVM*/true);
         }
 
@@ -767,8 +766,8 @@
         Objects.requireNonNull(other);
         Objects.requireNonNull(pn);
 
-        // all packages are open in unnamed and open modules
-        if (!isNamed() || descriptor.isOpen())
+        // all packages are open in unnamed, open, and automatic modules
+        if (!isNamed() || descriptor.isOpen() || descriptor.isAutomatic())
             return;
 
         // nothing to do if already exported/open to other
@@ -819,17 +818,17 @@
      * passed a reference to the service type by other code. This method is
      * a no-op when invoked on an unnamed module or an automatic module.
      *
-     * <p> This method does not cause {@link
-     * Configuration#resolveRequiresAndUses resolveRequiresAndUses} to be
-     * re-run. </p>
+     * <p> This method does not cause {@link Configuration#resolveAndBind
+     * resolveAndBind} to be re-run. </p>
      *
      * @param  service
      *         The service type
      *
      * @return this module
      *
-     * @throws IllegalStateException
-     *         If this is a named module and the caller is not this module
+     * @throws IllegalCallerException
+     *         If this is a named module and the caller's module is not this
+     *         module
      *
      * @see #canUse(Class)
      * @see ModuleDescriptor#uses()
@@ -841,7 +840,7 @@
         if (isNamed() && !descriptor.isAutomatic()) {
             Module caller = Reflection.getCallerClass().getModule();
             if (caller != this) {
-                throw new IllegalStateException(caller + " != " + this);
+                throw new IllegalCallerException(caller + " != " + this);
             }
             implAddUses(service);
         }
@@ -894,14 +893,13 @@
     // -- packages --
 
     // Additional packages that are added to the module at run-time.
-    // The field is volatile as it may be replaced at run-time
-    private volatile Set<String> extraPackages;
+    private volatile Map<String, Boolean> extraPackages;
 
     private boolean containsPackage(String pn) {
         if (descriptor.packages().contains(pn))
             return true;
-        Set<String> extraPackages = this.extraPackages;
-        if (extraPackages != null && extraPackages.contains(pn))
+        Map<String, Boolean> extraPackages = this.extraPackages;
+        if (extraPackages != null && extraPackages.containsKey(pn))
             return true;
         return false;
     }
@@ -915,7 +913,7 @@
      * added to the module, <a href="Proxy.html#dynamicmodule">dynamic modules</a>
      * for example, after it was loaded.
      *
-     * <p> For unnamed modules, this method is the equivalent of invoking the
+     * <p> For unnamed modules, this method is the equivalent to invoking the
      * {@link ClassLoader#getDefinedPackages() getDefinedPackages} method of
      * this module's class loader and returning the array of package names. </p>
      *
@@ -930,12 +928,12 @@
         if (isNamed()) {
 
             Set<String> packages = descriptor.packages();
-            Set<String> extraPackages = this.extraPackages;
+            Map<String, Boolean> extraPackages = this.extraPackages;
             if (extraPackages == null) {
                 return packages.toArray(new String[0]);
             } else {
                 return Stream.concat(packages.stream(),
-                                     extraPackages.stream())
+                                     extraPackages.keySet().stream())
                         .toArray(String[]::new);
             }
 
@@ -955,10 +953,6 @@
      * Add a package to this module.
      *
      * @apiNote This method is for Proxy use.
-     *
-     * @apiNote This is an expensive operation, not expected to be used often.
-     * At this time then it does not validate that the package name is a
-     * valid java identifier.
      */
     void addPackage(String pn) {
         implAddPackage(pn, true);
@@ -976,49 +970,52 @@
     /**
      * Add a package to this module.
      *
-     * If {@code syncVM} is {@code true} then the VM is notified.
+     * If {@code syncVM} is {@code true} then the VM is notified. This method is
+     * a no-op if this is an unnamed module or the module already contains the
+     * package.
+     *
+     * @throws IllegalArgumentException if the package name is not legal
+     * @throws IllegalStateException if the package is defined to another module
      */
     private void implAddPackage(String pn, boolean syncVM) {
+        // no-op if unnamed module
         if (!isNamed())
-            throw new InternalError("adding package to unnamed module?");
-        if (descriptor.isOpen())
-            throw new InternalError("adding package to open module?");
+            return;
+
+        // no-op if module contains the package
+        if (containsPackage(pn))
+            return;
+
+        // check package name is legal for named modules
         if (pn.isEmpty())
-            throw new InternalError("adding <unnamed> package to module?");
-
-        if (descriptor.packages().contains(pn)) {
-            // already in module
-            return;
+            throw new IllegalArgumentException("Cannot add <unnamed> package");
+        for (int i=0; i<pn.length(); i++) {
+            char c = pn.charAt(i);
+            if (c == '/' || c == ';' || c == '[') {
+                throw new IllegalArgumentException("Illegal character: " + c);
+            }
         }
 
-        Set<String> extraPackages = this.extraPackages;
-        if (extraPackages != null && extraPackages.contains(pn)) {
-            // already added
-            return;
+        // create extraPackages if needed
+        Map<String, Boolean> extraPackages = this.extraPackages;
+        if (extraPackages == null) {
+            synchronized (this) {
+                extraPackages = this.extraPackages;
+                if (extraPackages == null)
+                    this.extraPackages = extraPackages = new ConcurrentHashMap<>();
+            }
         }
-        synchronized (this) {
-            // recheck under lock
-            extraPackages = this.extraPackages;
-            if (extraPackages != null) {
-                if (extraPackages.contains(pn)) {
-                    // already added
-                    return;
-                }
 
-                // copy the set
-                extraPackages = new HashSet<>(extraPackages);
-                extraPackages.add(pn);
-            } else {
-                extraPackages = Collections.singleton(pn);
+        // update VM first in case it fails. This is a no-op if another thread
+        // beats us to add the package first
+        if (syncVM) {
+            // throws IllegalStateException if defined to another module
+            addPackage0(this, pn);
+            if (descriptor.isOpen() || descriptor.isAutomatic()) {
+                addExportsToAll0(this, pn);
             }
-
-            // update VM first, just in case it fails
-            if (syncVM)
-                addPackage0(this, pn);
-
-            // replace with new set
-            this.extraPackages = extraPackages; // volatile write
         }
+        extraPackages.putIfAbsent(pn, Boolean.TRUE);
     }
 
 
@@ -1169,8 +1166,9 @@
                                             Map<String, Module> nameToModule,
                                             Module m)
     {
-        // The VM doesn't know about open modules so need to export all packages
-        if (descriptor.isOpen()) {
+        // The VM doesn't special case open or automatic modules so need to
+        // export all packages
+        if (descriptor.isOpen() || descriptor.isAutomatic()) {
             assert descriptor.opens().isEmpty();
             for (String source : descriptor.packages()) {
                 addExportsToAll0(m, source);
@@ -1375,35 +1373,44 @@
 
 
     /**
-     * Returns an input stream for reading a resource in this module. The
-     * {@code name} parameter is a {@code '/'}-separated path name that
-     * identifies the resource.
+     * Returns an input stream for reading a resource in this module.
+     * The {@code name} parameter is a {@code '/'}-separated path name that
+     * identifies the resource. As with {@link Class#getResourceAsStream
+     * Class.getResourceAsStream}, this method delegates to the module's class
+     * loader {@link ClassLoader#findResource(String,String)
+     * findResource(String,String)} method, invoking it with the module name
+     * (or {@code null} when the module is unnamed) and the name of the
+     * resource. If the resource name has a leading slash then it is dropped
+     * before delegation.
      *
-     * <p> A resource in a named modules may be <em>encapsulated</em> so that
+     * <p> A resource in a named module may be <em>encapsulated</em> so that
      * it cannot be located by code in other modules. Whether a resource can be
-     * located or not is determined as follows:
+     * located or not is determined as follows: </p>
      *
      * <ul>
-     *     <li> The <em>package name</em> of the resource is derived from the
-     *     subsequence of characters that precedes the last {@code '/'} and then
-     *     replacing each {@code '/'} character in the subsequence with
-     *     {@code '.'}. For example, the package name derived for a resource
-     *     named "{@code a/b/c/foo.properties}" is "{@code a.b.c}". </li>
+     *     <li> If the resource name ends with  "{@code .class}" then it is not
+     *     encapsulated. </li>
      *
-     *     <li> If the package name is a package in the module then the package
-     *     must be {@link #isOpen open} the module of the caller of this method.
-     *     If the package is not in the module then the resource is not
-     *     encapsulated. Resources in the unnamed package or "{@code META-INF}",
-     *     for example, are never encapsulated because they can never be
-     *     packages in a named module. </li>
+     *     <li> A <em>package name</em> is derived from the resource name. If
+     *     the package name is a {@link #getPackages() package} in the module
+     *     then the resource can only be located by the caller of this method
+     *     when the package is {@link #isOpen(String,Module) open} to at least
+     *     the caller's module. If the resource is not in a package in the module
+     *     then the resource is not encapsulated. </li>
+     * </ul>
      *
-     *     <li> As a special case, resources ending with "{@code .class}" are
-     *     never encapsulated. </li>
-     * </ul>
+     * <p> In the above, the <em>package name</em> for a resource is derived
+     * from the subsequence of characters that precedes the last {@code '/'} in
+     * the name and then replacing each {@code '/'} character in the subsequence
+     * with {@code '.'}. A leading slash is ignored when deriving the package
+     * name. As an example, the package name derived for a resource named
+     * "{@code a/b/c/foo.properties}" is "{@code a.b.c}". A resource name
+     * with the name "{@code META-INF/MANIFEST.MF}" is never encapsulated
+     * because "{@code META-INF}" is not a legal package name. </p>
      *
      * <p> This method returns {@code null} if the resource is not in this
      * module, the resource is encapsulated and cannot be located by the caller,
-     * or access to the resource is denied by the security manager.
+     * or access to the resource is denied by the security manager. </p>
      *
      * @param  name
      *         The resource name
@@ -1413,11 +1420,13 @@
      * @throws IOException
      *         If an I/O error occurs
      *
-     * @see java.lang.module.ModuleReader#open(String)
+     * @see Class#getResourceAsStream(String)
      */
     @CallerSensitive
     public InputStream getResourceAsStream(String name) throws IOException {
-        Objects.requireNonNull(name);
+        if (name.startsWith("/")) {
+            name = name.substring(1);
+        }
 
         if (isNamed() && !ResourceHelper.isSimpleResource(name)) {
             Module caller = Reflection.getCallerClass().getModule();
--- a/jdk/src/java.base/share/classes/java/lang/reflect/Proxy.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/reflect/Proxy.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,7 @@
 
 package java.lang.reflect;
 
+import java.lang.module.ModuleDescriptor;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
 import java.util.Arrays;
@@ -52,6 +53,9 @@
 import sun.security.action.GetPropertyAction;
 import sun.security.util.SecurityConstants;
 
+import static java.lang.module.ModuleDescriptor.Modifier.SYNTHETIC;
+
+
 /**
  *
  * {@code Proxy} provides static methods for creating objects that act like instances
@@ -164,7 +168,8 @@
  * methods is specified as follows:
  *
  * <ol>
- * <li>If all the proxy interfaces are in <em>exported</em> packages:
+ * <li>If all the proxy interfaces are in <em>exported</em> or <em>open</em>
+ *     packages:
  * <ol type="a">
  * <li>if all the proxy interfaces are <em>public</em>, then the proxy class is
  *     <em>public</em> in a package exported by the
@@ -178,10 +183,11 @@
  *     <a href="#restrictions">not possible</a>.</li>
  * </ol>
  * </li>
- * <li>If at least one proxy interface is a <em>non-exported</em> package:
+ * <li>If at least one proxy interface is in a package that is
+ *     <em>non-exported</em> and <em>non-open</em>:
  * <ol type="a">
  * <li>if all the proxy interfaces are <em>public</em>, then the proxy class is
- *     <em>public</em> in a <em>non-exported</em> package of
+ *     <em>public</em> in a <em>non-exported</em>, <em>non-open</em> package of
  *     <a href="#dynamicmodule"><em>dynamic module</em>.</a>
  *     The names of the package and the module are unspecified.</li>
  *
@@ -195,21 +201,22 @@
  * </ol>
  *
  * <p>
- * Note that if proxy interfaces with a mix of accessibilities --
- * exported public, exported non-public, non-exported public, non-exported non-public --
- * are proxied by the same instance, then the proxy class's accessibility is
+ * Note that if proxy interfaces with a mix of accessibilities -- for example,
+ * an exported public interface and a non-exported non-public interface -- are
+ * proxied by the same instance, then the proxy class's accessibility is
  * governed by the least accessible proxy interface.
  * <p>
  * Note that it is possible for arbitrary code to obtain access to a proxy class
- * in an exported package with {@link AccessibleObject#setAccessible setAccessible},
- * whereas a proxy class in a non-exported package is never accessible to
+ * in an open package with {@link AccessibleObject#setAccessible setAccessible},
+ * whereas a proxy class in a non-open package is never accessible to
  * code outside the module of the proxy class.
  *
  * <p>
- * Throughout this specification, a "non-exported package" refers to a package that
- * is not exported to all modules. Specifically, it refers to a package that
- * either is not exported at all by its containing module or is exported in a
- * qualified fashion by its containing module.
+ * Throughout this specification, a "non-exported package" refers to a package
+ * that is not exported to all modules, and a "non-open package" refers to
+ * a package that is not open to all modules.  Specifically, these terms refer to
+ * a package that either is not exported/open by its containing module or is
+ * exported/open in a qualified fashion by its containing module.
  *
  * <h3><a name="dynamicmodule">Dynamic Modules</a></h3>
  * <p>
@@ -272,6 +279,8 @@
  * @author      Peter Jones
  * @see         InvocationHandler
  * @since       1.3
+ * @revised 9
+ * @spec JPMS
  */
 public class Proxy implements java.io.Serializable {
     private static final long serialVersionUID = -2222568056686623797L;
@@ -358,6 +367,8 @@
      *      to create a proxy instance instead.
      *
      * @see <a href="#membership">Package and Module Membership of Proxy Class</a>
+     * @revised 9
+     * @spec JPMS
      */
     @Deprecated
     @CallerSensitive
@@ -855,7 +866,11 @@
                 // create a dynamic module and setup module access
                 String mn = "jdk.proxy" + counter.incrementAndGet();
                 String pn = PROXY_PACKAGE_PREFIX + "." + mn;
-                Module m = Modules.defineModule(ld, mn, Collections.singleton(pn));
+                ModuleDescriptor descriptor =
+                    ModuleDescriptor.newModule(mn, Set.of(SYNTHETIC))
+                                    .packages(Set.of(pn))
+                                    .build();
+                Module m = Modules.defineModule(ld, descriptor, null);
                 Modules.addReads(m, Proxy.class.getModule());
                 // java.base to create proxy instance
                 Modules.addExports(m, pn, Object.class.getModule());
@@ -955,6 +970,8 @@
      *          {@code null}
      *
      * @see <a href="#membership">Package and Module Membership of Proxy Class</a>
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static Object newProxyInstance(ClassLoader loader,
@@ -1039,6 +1056,9 @@
      * @return  {@code true} if the class is a proxy class and
      *          {@code false} otherwise
      * @throws  NullPointerException if {@code cl} is {@code null}
+     *
+     * @revised 9
+     * @spec JPMS
      */
     public static boolean isProxyClass(Class<?> cl) {
         return Proxy.class.isAssignableFrom(cl) && ProxyBuilder.isProxyClass(cl);
--- a/jdk/src/java.base/share/classes/java/lang/reflect/package-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/lang/reflect/package-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -45,5 +45,7 @@
  * members declared by a given class.
  *
  * @since 1.1
+ * @revised 9
+ * @spec JPMS
  */
 package java.lang.reflect;
--- a/jdk/src/java.base/share/classes/java/net/URL.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/net/URL.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,6 +41,8 @@
 import java.util.ServiceConfigurationError;
 import java.util.ServiceLoader;
 
+import jdk.internal.misc.JavaNetURLAccess;
+import jdk.internal.misc.SharedSecrets;
 import sun.security.util.SecurityConstants;
 import sun.security.action.GetPropertyAction;
 
@@ -1614,6 +1616,17 @@
     private void setSerializedHashCode(int hc) {
         this.hashCode = hc;
     }
+
+    static {
+        SharedSecrets.setJavaNetURLAccess(
+                new JavaNetURLAccess() {
+                    @Override
+                    public URLStreamHandler getHandler(URL u) {
+                        return u.handler;
+                    }
+                }
+        );
+    }
 }
 
 final class UrlDeserializedState {
--- a/jdk/src/java.base/share/classes/java/net/URLClassLoader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/net/URLClassLoader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -228,6 +228,7 @@
      *         allow creation of a class loader.
      *
      * @since 9
+     * @spec JPMS
      */
     public URLClassLoader(String name,
                           URL[] urls,
@@ -262,6 +263,7 @@
      *         creation of a class loader.
      *
      * @since 9
+     * @spec JPMS
      */
     public URLClassLoader(String name, URL[] urls, ClassLoader parent,
                           URLStreamHandlerFactory factory) {
@@ -558,6 +560,9 @@
      * @throws      IllegalArgumentException if the package name is
      *              already defined by this class loader
      * @return      the newly defined {@code Package} object
+     *
+     * @revised 9
+     * @spec JPMS
      */
     protected Package definePackage(String name, Manifest man, URL url) {
         String path = name.replace('.', '/').concat("/");
--- a/jdk/src/java.base/share/classes/java/nio/charset/Charset.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/nio/charset/Charset.java	Thu Mar 16 20:47:03 2017 +0000
@@ -300,9 +300,8 @@
      */
     private static void checkName(String s) {
         int n = s.length();
-        if (!atBugLevel("1.4")) {
-            if (n == 0)
-                throw new IllegalCharsetNameException(s);
+        if (n == 0 && !atBugLevel("1.4")) {
+            throw new IllegalCharsetNameException(s);
         }
         for (int i = 0; i < n; i++) {
             char c = s.charAt(i);
@@ -319,7 +318,9 @@
     }
 
     /* The standard set of charsets */
-    private static CharsetProvider standardProvider = new StandardCharsets();
+    private static final CharsetProvider standardProvider = new StandardCharsets();
+
+    private static final String[] zeroAliases = new String[0];
 
     // Cache of the most-recently-returned charsets,
     // along with the names that were used to find them
@@ -626,7 +627,6 @@
 
     private final String name;          // tickles a bug in oldjavac
     private final String[] aliases;     // tickles a bug in oldjavac
-    private final String[] zeroAliases = new String[0];
     private Set<String> aliasSet = null;
 
     /**
--- a/jdk/src/java.base/share/classes/java/security/DrbgParameters.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/security/DrbgParameters.java	Thu Mar 16 20:47:03 2017 +0000
@@ -53,8 +53,8 @@
  * for CTR_DRBG. Please note that it is not the algorithm used in
  * {@link SecureRandom#getInstance}, which we will call a
  * <em>SecureRandom algorithm</em> below),
- * <li> optionally features, including prediction resistance
- * and reseeding supports.
+ * <li> optional features, including prediction resistance
+ * and reseeding supports,
  * <li> highest security strength.
  * </ul>
  * <p>
--- a/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/security/ProtectionDomain.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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,7 @@
 import jdk.internal.misc.JavaSecurityProtectionDomainAccess;
 import static jdk.internal.misc.JavaSecurityProtectionDomainAccess.ProtectionDomainCache;
 import jdk.internal.misc.SharedSecrets;
+import sun.security.action.GetPropertyAction;
 import sun.security.provider.PolicyFile;
 import sun.security.util.Debug;
 import sun.security.util.FilePermCompat;
@@ -62,6 +63,14 @@
 
 public class ProtectionDomain {
 
+    /**
+     * If true, {@link #impliesWithAltFilePerm} will try to be compatible on
+     * FilePermission checking even if a 3rd-party Policy implementation is set.
+     */
+    private static final boolean filePermCompatInPD =
+            "true".equals(GetPropertyAction.privilegedGetProperty(
+                "jdk.security.filePermCompat"));
+
     private static class JavaSecurityAccessImpl implements JavaSecurityAccess {
 
         private JavaSecurityAccessImpl() {
@@ -321,19 +330,27 @@
     }
 
     /**
-     * This method has the same logic flow as {@link #implies} except that
-     * when the {@link FilePermCompat#compat} flag is on it ensures
-     * FilePermission compatibility after JDK-8164705. {@code implies()}
-     * is called when compat flag is not on or user has extended
-     * {@code ProtectionDomain}.
+     * This method has almost the same logic flow as {@link #implies} but
+     * it ensures some level of FilePermission compatibility after JDK-8164705.
      *
      * This method is called by {@link AccessControlContext#checkPermission}
      * and not intended to be called by an application.
      */
     boolean impliesWithAltFilePerm(Permission perm) {
 
-        // If this is a subclass of ProtectionDomain. Call the old method.
-        if (!FilePermCompat.compat || getClass() != ProtectionDomain.class) {
+        // If FilePermCompat.compat is set (default value), FilePermission
+        // checking compatibility should be considered.
+
+        // If filePermCompatInPD is set, this method checks for alternative
+        // FilePermission to keep compatibility for any Policy implementation.
+        // When set to false (default value), implies() is called since
+        // the PolicyFile implementation already supports compatibility.
+
+        // If this is a subclass of ProtectionDomain, call implies()
+        // because most likely user has overridden it.
+
+        if (!filePermCompatInPD || !FilePermCompat.compat ||
+                getClass() != ProtectionDomain.class) {
             return implies(perm);
         }
 
--- a/jdk/src/java.base/share/classes/java/security/SecureClassLoader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/security/SecureClassLoader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -125,6 +125,7 @@
      *         doesn't allow creation of a class loader.
      *
      * @since 9
+     * @spec JPMS
      */
     protected SecureClassLoader(String name, ClassLoader parent) {
         super(name, parent);
--- a/jdk/src/java.base/share/classes/java/security/SecureRandom.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/security/SecureRandom.java	Thu Mar 16 20:47:03 2017 +0000
@@ -64,8 +64,8 @@
  * <blockquote><pre>
  * SecureRandom r1 = new SecureRandom();
  * SecureRandom r2 = SecureRandom.getInstance("NativePRNG");
- * SecureRandom r3 = SecureRandom("DRBG",
- *         DrbgParameters.Instantiation(128, RESEED_ONLY, null));</pre>
+ * SecureRandom r3 = SecureRandom.getInstance("DRBG",
+ *         DrbgParameters.instantiation(128, RESEED_ONLY, null));</pre>
  * </blockquote>
  *
  * <p> The third statement above returns a {@code SecureRandom} object of the
--- a/jdk/src/java.base/share/classes/java/security/Security.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/security/Security.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,11 +25,12 @@
 
 package java.security;
 
-import java.lang.reflect.*;
 import java.util.*;
 import java.util.concurrent.ConcurrentHashMap;
 import java.io.*;
 import java.net.URL;
+
+import jdk.internal.misc.SharedSecrets;
 import sun.security.util.Debug;
 import sun.security.util.PropertyExpander;
 
@@ -800,9 +801,6 @@
      * "package.definition", we need to signal to the SecurityManager
      * class that the value has just changed, and that it should
      * invalidate it's local cache values.
-     *
-     * Rather than create a new API entry for this function,
-     * we use reflection to set a private variable.
      */
     private static void invalidateSMCache(String key) {
 
@@ -810,42 +808,8 @@
         final boolean pd = key.equals("package.definition");
 
         if (pa || pd) {
-            AccessController.doPrivileged(new PrivilegedAction<>() {
-                public Void run() {
-                    try {
-                        /* Get the class via the bootstrap class loader. */
-                        Class<?> cl = Class.forName(
-                            "java.lang.SecurityManager", false, null);
-                        Field f = null;
-                        boolean accessible = false;
-
-                        if (pa) {
-                            f = cl.getDeclaredField("packageAccessValid");
-                            accessible = f.isAccessible();
-                            f.setAccessible(true);
-                        } else {
-                            f = cl.getDeclaredField("packageDefinitionValid");
-                            accessible = f.isAccessible();
-                            f.setAccessible(true);
-                        }
-                        f.setBoolean(f, false);
-                        f.setAccessible(accessible);
-                    }
-                    catch (Exception e1) {
-                        /* If we couldn't get the class, it hasn't
-                         * been loaded yet.  If there is no such
-                         * field, we shouldn't try to set it.  There
-                         * shouldn't be a security execption, as we
-                         * are loaded by boot class loader, and we
-                         * are inside a doPrivileged() here.
-                         *
-                         * NOOP: don't do anything...
-                         */
-                    }
-                    return null;
-                }  /* run */
-            });  /* PrivilegedAction */
-        }  /* if */
+            SharedSecrets.getJavaLangAccess().invalidatePackageAccessCache();
+        }
     }
 
     private static void check(String directive) {
--- a/jdk/src/java.base/share/classes/java/util/Objects.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/util/Objects.java	Thu Mar 16 20:47:03 2017 +0000
@@ -343,7 +343,8 @@
      */
     public static <T> T requireNonNull(T obj, Supplier<String> messageSupplier) {
         if (obj == null)
-            throw new NullPointerException(messageSupplier.get());
+            throw new NullPointerException(messageSupplier == null ?
+                                           null : messageSupplier.get());
         return obj;
     }
 
--- a/jdk/src/java.base/share/classes/java/util/ResourceBundle.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/util/ResourceBundle.java	Thu Mar 16 20:47:03 2017 +0000
@@ -350,6 +350,8 @@
  * @see MissingResourceException
  * @see ResourceBundleProvider
  * @since 1.1
+ * @revised 9
+ * @spec JPMS
  */
 public abstract class ResourceBundle {
 
@@ -870,6 +872,8 @@
      * @throws UnsupportedOperationException
      *         if this method is called in a named module
      * @since 1.6
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static final ResourceBundle getBundle(String baseName,
@@ -938,6 +942,7 @@
      *         specified module
      * @return a resource bundle for the given base name and the default locale
      * @since 9
+     * @spec JPMS
      * @see ResourceBundleProvider
      */
     @CallerSensitive
@@ -991,6 +996,7 @@
      *         be found in the specified {@code module}
      * @return a resource bundle for the given base name and locale in the module
      * @since 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static ResourceBundle getBundle(String baseName, Locale targetLocale, Module module) {
@@ -1036,6 +1042,8 @@
      * @throws UnsupportedOperationException
      *         if this method is called in a named module
      * @since 1.6
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static final ResourceBundle getBundle(String baseName, Locale targetLocale,
@@ -1243,6 +1251,8 @@
      * @exception MissingResourceException
      *        if no resource bundle for the specified base name can be found
      * @since 1.2
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static ResourceBundle getBundle(String baseName, Locale locale,
@@ -1465,6 +1475,8 @@
      * @throws UnsupportedOperationException
      *         if this method is called in a named module
      * @since 1.6
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static ResourceBundle getBundle(String baseName, Locale targetLocale,
@@ -2194,6 +2206,8 @@
      * by the caller's module.
      *
      * @since 1.6
+     * @revised 9
+     * @spec JPMS
      * @see ResourceBundle.Control#getTimeToLive(String,Locale)
      */
     @CallerSensitive
@@ -2475,6 +2489,8 @@
      * of {@link ResourceBundleControlProvider} are ignored in named modules.
      *
      * @since 1.6
+     * @revised 9
+     * @spec JPMS
      * @see java.util.spi.ResourceBundleProvider
      */
     public static class Control {
@@ -3103,6 +3119,8 @@
          *        if an error occurred when reading resources using
          *        any I/O operations
          * @see java.util.spi.ResourceBundleProvider#getBundle(String, Locale)
+         * @revised 9
+         * @spec JPMS
          */
         public ResourceBundle newBundle(String baseName, Locale locale, String format,
                                         ClassLoader loader, boolean reload)
--- a/jdk/src/java.base/share/classes/java/util/ServiceLoader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/util/ServiceLoader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -119,7 +119,7 @@
  * and deployed as an explicit module must have an appropriate <i>uses</i>
  * clause in its <i>module descriptor</i> to declare that the module uses
  * implementations of the service. A corresponding requirement is that a
- * provider deployed as a named module must have an appropriate
+ * provider deployed as an explicit module must have an appropriate
  * <i>provides</i> clause in its module descriptor to declare that the module
  * provides an implementation of the service. The <i>uses</i> and
  * <i>provides</i> allow consumers of a service to be <i>linked</i> to modules
@@ -203,8 +203,11 @@
  *     ordering of modules in a layer, is not defined. </li>
  *
  *     <li> If a named module declares more than one provider then the providers
- *     are located in the order that they appear in the {@code provides} table of
- *     the {@code Module} class file attribute ({@code module-info.class}). </li>
+ *     are located in the iteration order of the {@link
+ *     java.lang.module.ModuleDescriptor.Provides#providers() providers} list.
+ *     Providers added dynamically by instrumentation agents ({@link
+ *     java.lang.instrument.Instrumentation#redefineModule redefineModule})
+ *     are always located after providers declared by the module. </li>
  *
  *     <li> When locating providers in unnamed modules then the ordering is
  *     based on the order that the class loader's {@link
@@ -335,6 +338,8 @@
  *
  * @author Mark Reinhold
  * @since 1.6
+ * @revised 9
+ * @spec JPMS
  */
 
 public final class ServiceLoader<S>
@@ -386,6 +391,7 @@
      *
      * @param  <S> The service type
      * @since 9
+     * @spec JPMS
      */
     public static interface Provider<S> extends Supplier<S> {
         /**
@@ -927,26 +933,28 @@
             } else {
                 catalog = ServicesCatalog.getServicesCatalogOrNull(loader);
             }
-            Stream<ServiceProvider> stream1;
+            List<ServiceProvider> providers;
             if (catalog == null) {
-                stream1 = Stream.empty();
+                providers = List.of();
             } else {
-                stream1 = catalog.findServices(serviceName).stream();
+                providers = catalog.findServices(serviceName);
             }
 
             // modules in custom layers that define modules to the class loader
-            Stream<ServiceProvider> stream2;
             if (loader == null) {
-                stream2 = Stream.empty();
+                return providers.iterator();
             } else {
+                List<ServiceProvider> allProviders = new ArrayList<>(providers);
                 Layer bootLayer = Layer.boot();
-                stream2 = JLRM_ACCESS.layers(loader)
-                        .filter(l -> (l != bootLayer))
-                        .map(l -> providers(l))
-                        .flatMap(List::stream);
+                Iterator<Layer> iterator = JLRM_ACCESS.layers(loader).iterator();
+                while (iterator.hasNext()) {
+                    Layer layer = iterator.next();
+                    if (layer != bootLayer) {
+                        allProviders.addAll(providers(layer));
+                    }
+                }
+                return allProviders.iterator();
             }
-
-            return Stream.concat(stream1, stream2).iterator();
         }
 
         @Override
@@ -1214,6 +1222,9 @@
      *
      * @return  An iterator that lazily loads providers for this loader's
      *          service
+     *
+     * @revised 9
+     * @spec JPMS
      */
     public Iterator<S> iterator() {
 
@@ -1279,8 +1290,10 @@
      * provider to be loaded. </p>
      *
      * <p> If this loader's provider caches are cleared by invoking the {@link
-     * #reload() reload} method then existing streams for this service
-     * loader should be discarded. </p>
+     * #reload() reload} method then existing streams for this service loader
+     * should be discarded. The returned stream's source {@code Spliterator} is
+     * <em>fail-fast</em> and will throw {@link ConcurrentModificationException}
+     * if the provider cache has been cleared. </p>
      *
      * <p> The following examples demonstrate usage. The first example
      * creates a stream of providers, the second example is the same except
@@ -1300,6 +1313,7 @@
      * @return  A stream that lazily loads providers for this loader's service
      *
      * @since 9
+     * @spec JPMS
      */
     public Stream<Provider<S>> stream() {
         // use cached providers as the source when all providers loaded
@@ -1414,6 +1428,9 @@
      *         if the service type is not accessible to the caller or the
      *         caller is in an explicit module and its module descriptor does
      *         not declare that it uses {@code service}
+     *
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static <S> ServiceLoader<S> load(Class<S> service,
@@ -1457,6 +1474,9 @@
      *         if the service type is not accessible to the caller or the
      *         caller is in an explicit module and its module descriptor does
      *         not declare that it uses {@code service}
+     *
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static <S> ServiceLoader<S> load(Class<S> service) {
@@ -1490,6 +1510,9 @@
      *         if the service type is not accessible to the caller or the
      *         caller is in an explicit module and its module descriptor does
      *         not declare that it uses {@code service}
+     *
+     * @revised 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static <S> ServiceLoader<S> loadInstalled(Class<S> service) {
@@ -1522,6 +1545,7 @@
      *         not declare that it uses {@code service}
      *
      * @since 9
+     * @spec JPMS
      */
     @CallerSensitive
     public static <S> ServiceLoader<S> load(Layer layer, Class<S> service) {
@@ -1551,6 +1575,7 @@
      *         or error is thrown when locating or instantiating the provider.
      *
      * @since 9
+     * @spec JPMS
      */
     public Optional<S> findFirst() {
         Iterator<S> iterator = iterator();
--- a/jdk/src/java.base/share/classes/java/util/spi/AbstractResourceBundleProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/util/spi/AbstractResourceBundleProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -81,6 +81,7 @@
  *     ResourceBundleProvider Service Providers</a>
  *
  * @since 9
+ * @spec JPMS
  */
 public abstract class AbstractResourceBundleProvider implements ResourceBundleProvider {
     private static final JavaUtilResourceBundleAccess RB_ACCESS =
--- a/jdk/src/java.base/share/classes/java/util/spi/ResourceBundleControlProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/util/spi/ResourceBundleControlProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -44,6 +44,8 @@
  *
  * @author Masayoshi Okutsu
  * @since 1.8
+ * @revised 9
+ * @spec JPMS
  * @see ResourceBundle#getBundle(String, java.util.Locale, ClassLoader, ResourceBundle.Control)
  *      ResourceBundle.getBundle
  * @see java.util.ServiceLoader#load(Class)
--- a/jdk/src/java.base/share/classes/java/util/spi/ResourceBundleProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/util/spi/ResourceBundleProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -57,6 +57,7 @@
  * @see <a href="../ResourceBundle.html#RBP_support">
  *     ResourceBundleProvider Service Providers</a>
  * @since 9
+ * @spec JPMS
  */
 public interface ResourceBundleProvider {
     /**
--- a/jdk/src/java.base/share/classes/java/util/zip/ZipEntry.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/util/zip/ZipEntry.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2017, 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
@@ -441,7 +441,7 @@
     /**
      * Sets the size of the compressed entry data.
      *
-     * @param csize the compressed size to set to
+     * @param csize the compressed size to set
      *
      * @see #getCompressedSize()
      */
--- a/jdk/src/java.base/share/classes/java/util/zip/ZipFile.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/java/util/zip/ZipFile.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2017, 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
@@ -274,7 +274,7 @@
      *
      * @throws IllegalStateException if the zip file has been closed
      *
-     * Since 1.7
+     * @since 1.7
      */
     public String getComment() {
         synchronized (this) {
--- a/jdk/src/java.base/share/classes/jdk/internal/jimage/BasicImageReader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/jimage/BasicImageReader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -137,10 +137,15 @@
         int headerSize = ImageHeader.getHeaderSize();
 
         // If no memory map then read header from image file
-        if (map == null) {
+        if (headerBuffer == null) {
             headerBuffer = ByteBuffer.allocateDirect(headerSize);
-            channel.read(headerBuffer, 0L);
-            headerBuffer.rewind();
+            if (channel.read(headerBuffer, 0L) == headerSize) {
+                headerBuffer.rewind();
+            } else {
+                throw new IOException("\"" + name + "\" is not an image file");
+            }
+        } else if (headerBuffer.capacity() < headerSize) {
+            throw new IOException("\"" + name + "\" is not an image file");
         }
 
         // Interpret the image file header
@@ -156,6 +161,9 @@
         memoryMap = map.asReadOnlyBuffer();
 
         // Interpret the image index
+        if (memoryMap.capacity() < indexSize) {
+            throw new IOException("The image file \"" + name + "\" is corrupted");
+        }
         redirect = intBuffer(memoryMap, header.getRedirectOffset(), header.getRedirectSize());
         offsets = intBuffer(memoryMap, header.getOffsetsOffset(), header.getOffsetsSize());
         locations = slice(memoryMap, header.getLocationsOffset(), header.getLocationsSize());
--- a/jdk/src/java.base/share/classes/jdk/internal/jimage/ImageReader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/jimage/ImageReader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -52,7 +52,9 @@
  * to the jimage file provided by the shipped JDK by tools running on JDK 8.
  */
 public final class ImageReader implements AutoCloseable {
-    private SharedImageReader reader;
+    private final SharedImageReader reader;
+
+    private volatile boolean closed;
 
     private ImageReader(SharedImageReader reader) {
         this.reader = reader;
@@ -71,45 +73,49 @@
 
     @Override
     public void close() throws IOException {
-        if (reader == null) {
+        if (closed) {
             throw new IOException("image file already closed");
         }
+        reader.close(this);
+        closed = true;
+    }
 
-        reader.close(this);
-        reader = null;
+    private void ensureOpen() throws IOException {
+        if (closed) {
+            throw new IOException("image file closed");
+        }
+    }
+
+    private void requireOpen() {
+        if (closed) {
+            throw new IllegalStateException("image file closed");
+        }
     }
 
     // directory management interface
     public Directory getRootDirectory() throws IOException {
-        if (reader == null) {
-            throw new IOException("image file closed");
-        }
+        ensureOpen();
         return reader.getRootDirectory();
     }
 
+
     public Node findNode(String name) throws IOException {
-        if (reader == null) {
-            throw new IOException("image file closed");
-        }
+        ensureOpen();
         return reader.findNode(name);
     }
 
     public byte[] getResource(Node node) throws IOException {
-        if (reader == null) {
-            throw new IOException("image file closed");
-        }
+        ensureOpen();
         return reader.getResource(node);
     }
 
     public byte[] getResource(Resource rs) throws IOException {
-        if (reader == null) {
-            throw new IOException("image file closed");
-        }
+        ensureOpen();
         return reader.getResource(rs);
     }
 
     public ImageHeader getHeader() {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.getHeader();
     }
 
@@ -118,42 +124,42 @@
     }
 
     public String getName() {
-        Objects.requireNonNull(reader, "image file closed");
-        return reader.getName() ;
+        requireOpen();
+        return reader.getName();
     }
 
     public ByteOrder getByteOrder() {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.getByteOrder();
     }
 
     public Path getImagePath() {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.getImagePath();
     }
 
     public ImageStringsReader getStrings() {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.getStrings();
     }
 
     public ImageLocation findLocation(String mn, String rn) {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.findLocation(mn, rn);
     }
 
     public ImageLocation findLocation(String name) {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.findLocation(name);
     }
 
     public String[] getEntryNames() {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.getEntryNames();
     }
 
     public String[] getModuleNames() {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         int off = "/modules/".length();
         return reader.findNode("/modules")
                      .getChildren()
@@ -164,32 +170,32 @@
     }
 
     public long[] getAttributes(int offset) {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.getAttributes(offset);
     }
 
     public String getString(int offset) {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.getString(offset);
     }
 
     public byte[] getResource(String name) {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.getResource(name);
     }
 
     public byte[] getResource(ImageLocation loc) {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.getResource(loc);
     }
 
     public ByteBuffer getResourceBuffer(ImageLocation loc) {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.getResourceBuffer(loc);
     }
 
     public InputStream getResourceStream(ImageLocation loc) {
-        Objects.requireNonNull(reader, "image file closed");
+        requireOpen();
         return reader.getResourceStream(loc);
     }
 
--- a/jdk/src/java.base/share/classes/jdk/internal/jimage/ImageReaderFactory.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/jimage/ImageReaderFactory.java	Thu Mar 16 20:47:03 2017 +0000
@@ -32,6 +32,7 @@
 import java.util.concurrent.ConcurrentHashMap;
 import java.util.Map;
 import java.util.Objects;
+import java.util.function.Function;
 
 /**
  * Factory to get ImageReader
@@ -56,21 +57,23 @@
      */
     public static ImageReader get(Path jimage) throws IOException {
         Objects.requireNonNull(jimage);
-        ImageReader reader = readers.get(jimage);
-        if (reader != null) {
-            return reader;
-        }
-        reader = ImageReader.open(jimage);
-        // potential race with other threads opening the same URL
-        ImageReader r = readers.putIfAbsent(jimage, reader);
-        if (r == null) {
-            return reader;
-        } else {
-            reader.close();
-            return r;
+        try {
+            return readers.computeIfAbsent(jimage, OPENER);
+        } catch (UncheckedIOException io) {
+            throw io.getCause();
         }
     }
 
+    private static Function<Path, ImageReader> OPENER = new Function<Path, ImageReader>() {
+        public ImageReader apply(Path path) {
+            try {
+                return ImageReader.open(path);
+            } catch (IOException io) {
+                throw new UncheckedIOException(io);
+            }
+        }
+    };
+
     /**
      * Returns the {@code ImageReader} to read the image file in this
      * run-time image.
--- a/jdk/src/java.base/share/classes/jdk/internal/jmod/JmodFile.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/jmod/JmodFile.java	Thu Mar 16 20:47:03 2017 +0000
@@ -78,7 +78,7 @@
         HEADER_FILES("include"),
         LEGAL_NOTICES("legal"),
         MAN_PAGES("man"),
-        NATIVE_LIBS("native"),
+        NATIVE_LIBS("lib"),
         NATIVE_CMDS("bin");
 
         private final String jmodDir;
@@ -186,7 +186,7 @@
     public Entry getEntry(Section section, String name) {
         String entry = section.jmodDir() + "/" + name;
         ZipEntry ze = zipfile.getEntry(entry);
-        return (ze != null) ? new Entry(ze) : null;
+        return (ze == null || ze.isDirectory()) ? null : new Entry(ze);
     }
 
     /**
@@ -201,7 +201,7 @@
     {
         String entry = section.jmodDir() + "/" + name;
         ZipEntry e = zipfile.getEntry(entry);
-        if (e == null) {
+        if (e == null || e.isDirectory()) {
             throw new IOException(name + " not found: " + file);
         }
         return zipfile.getInputStream(e);
--- a/jdk/src/java.base/share/classes/jdk/internal/loader/BuiltinClassLoader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/loader/BuiltinClassLoader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -57,8 +57,9 @@
 import java.util.jar.Manifest;
 import java.util.stream.Stream;
 
+import jdk.internal.misc.VM;
 import jdk.internal.module.ModulePatcher.PatchedModuleReader;
-import jdk.internal.misc.VM;
+import jdk.internal.module.SystemModules;
 
 
 /**
@@ -135,7 +136,7 @@
 
     // maps package name to loaded module for modules in the boot layer
     private static final Map<String, LoadedModule> packageToModule
-        = new ConcurrentHashMap<>(1024);
+        = new ConcurrentHashMap<>(SystemModules.PACKAGES_IN_BOOT_LAYER);
 
     // maps a module name to a module reference
     private final Map<String, ModuleReference> nameToModule;
@@ -922,13 +923,13 @@
      * Returns the ModuleReader for the given module.
      */
     private ModuleReader moduleReaderFor(ModuleReference mref) {
-        return moduleToReader.computeIfAbsent(mref, m -> createModuleReader(mref));
+        return moduleToReader.computeIfAbsent(mref, BuiltinClassLoader::createModuleReader);
     }
 
     /**
      * Creates a ModuleReader for the given module.
      */
-    private ModuleReader createModuleReader(ModuleReference mref) {
+    private static ModuleReader createModuleReader(ModuleReference mref) {
         try {
             return mref.open();
         } catch (IOException e) {
--- a/jdk/src/java.base/share/classes/jdk/internal/loader/ResourceHelper.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/loader/ResourceHelper.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -24,6 +24,10 @@
  */
 package jdk.internal.loader;
 
+import java.io.File;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
 import jdk.internal.module.Checks;
 
 /**
@@ -34,7 +38,8 @@
     private ResourceHelper() { }
 
     /**
-     * Returns the <em>package name</em> for a resource.
+     * Returns the <em>package name</em> for a resource or the empty package if
+     * the resource name does not contain a slash.
      */
     public static String getPackageName(String name) {
         int index = name.lastIndexOf('/');
@@ -46,19 +51,75 @@
     }
 
     /**
-     * Returns true if the resource is a <em>simple resource</em> that can
-     * never be encapsulated. Resources ending in "{@code .class}" or where
-     * the package name is not a Java identifier are resources that can
-     * never be encapsulated.
+     * Returns true if the resource is a <em>simple resource</em>. Simple
+     * resources can never be encapsulated. Resources ending in "{@code .class}"
+     * or where the package name is not a legal package name can not be
+     * encapsulated.
      */
     public static boolean isSimpleResource(String name) {
         int len = name.length();
         if (len > 6 && name.endsWith(".class")) {
             return true;
         }
-        if (!Checks.isJavaIdentifier(getPackageName(name))) {
+        if (!Checks.isPackageName(getPackageName(name))) {
             return true;
         }
         return false;
     }
+
+    /**
+     * Converts a resource name to a file path. Returns {@code null} if the
+     * resource name cannot be converted into a file path. Resource names
+     * with empty elements, or elements that are "." or ".." are rejected,
+     * as is a resource name that translates to a file path with a root
+     * component.
+     */
+    public static Path toFilePath(String name) {
+        // scan the resource name to eagerly reject obviously invalid names
+        int next;
+        int off = 0;
+        while ((next = name.indexOf('/', off)) != -1) {
+            int len = next - off;
+            if (!mayTranslate(name, off, len)) {
+                return null;
+            }
+            off = next + 1;
+        }
+        int rem = name.length() - off;
+        if (!mayTranslate(name, off, rem)) {
+            return null;
+        }
+
+        // convert to file path
+        Path path;
+        if (File.separatorChar == '/') {
+            path = Paths.get(name);
+        } else {
+            // not allowed to embed file separators
+            if (name.contains(File.separator))
+                return null;
+            path = Paths.get(name.replace('/', File.separatorChar));
+        }
+
+        // file path not allowed to have root component
+        return (path.getRoot() == null) ? path : null;
+    }
+
+    /**
+     * Returns {@code true} if the element in a resource name is a candidate
+     * to translate to the element of a file path.
+     */
+    private static boolean mayTranslate(String name, int off, int len) {
+        if (len <= 2) {
+            if (len == 0)
+                return false;
+            boolean starsWithDot = (name.charAt(off) == '.');
+            if (len == 1 && starsWithDot)
+                return false;
+            if (len == 2 && starsWithDot && (name.charAt(off+1) == '.'))
+                return false;
+        }
+        return true;
+    }
+
 }
--- a/jdk/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/loader/URLClassPath.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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,6 +65,8 @@
 import java.util.jar.Attributes.Name;
 import java.util.zip.ZipFile;
 
+import jdk.internal.misc.JavaNetURLAccess;
+import jdk.internal.misc.JavaNetURLClassLoaderAccess;
 import jdk.internal.misc.JavaUtilZipFileAccess;
 import jdk.internal.misc.SharedSecrets;
 import jdk.internal.util.jar.InvalidJarIndexError;
@@ -346,7 +348,7 @@
      * path. The URLs are opened and expanded as needed. Returns null
      * if the specified index is out of range.
      */
-     private synchronized Loader getLoader(int index) {
+    private synchronized Loader getLoader(int index) {
         if (closed) {
             return null;
         }
@@ -404,31 +406,40 @@
     private Loader getLoader(final URL url) throws IOException {
         try {
             return java.security.AccessController.doPrivileged(
-                new java.security.PrivilegedExceptionAction<>() {
-                public Loader run() throws IOException {
-                    String protocol = url.getProtocol();  // lower cased in URL
-                    String file = url.getFile();
-                    if ("jar".equals(protocol)
-                            && file != null && (file.indexOf("!/") == file.length() - 2)) {
-                        // extract the nested URL
-                        URL nestedUrl = new URL(file.substring(0, file.length() - 2));
-                        return new JarLoader(nestedUrl, jarHandler, lmap, acc);
-                    } else if (file != null && file.endsWith("/")) {
-                        if ("file".equals(protocol)) {
-                            return new FileLoader(url);
-                        } else {
-                            return new Loader(url);
+                    new java.security.PrivilegedExceptionAction<>() {
+                        public Loader run() throws IOException {
+                            String protocol = url.getProtocol();  // lower cased in URL
+                            String file = url.getFile();
+                            if (file != null && file.endsWith("/")) {
+                                if ("file".equals(protocol)) {
+                                    return new FileLoader(url);
+                                } else if ("jar".equals(protocol) &&
+                                        isDefaultJarHandler(url) &&
+                                        file.endsWith("!/")) {
+                                    // extract the nested URL
+                                    URL nestedUrl = new URL(file.substring(0, file.length() - 2));
+                                    return new JarLoader(nestedUrl, jarHandler, lmap, acc);
+                                } else {
+                                    return new Loader(url);
+                                }
+                            } else {
+                                return new JarLoader(url, jarHandler, lmap, acc);
+                            }
                         }
-                    } else {
-                        return new JarLoader(url, jarHandler, lmap, acc);
-                    }
-                }
-            }, acc);
+                    }, acc);
         } catch (java.security.PrivilegedActionException pae) {
             throw (IOException)pae.getException();
         }
     }
 
+    private static final JavaNetURLAccess JNUA
+            = SharedSecrets.getJavaNetURLAccess();
+
+    private static boolean isDefaultJarHandler(URL u) {
+        URLStreamHandler h = JNUA.getHandler(u);
+        return h instanceof sun.net.www.protocol.jar.Handler;
+    }
+
     /*
      * Pushes the specified URLs onto the list of unopened URLs.
      */
@@ -493,7 +504,7 @@
     }
 
     /**
-     * Inner class used to represent a loader of resources and classes
+     * Nested class used to represent a loader of resources and classes
      * from a base URL.
      */
     private static class Loader implements Closeable {
@@ -600,7 +611,8 @@
          * close this loader and release all resources
          * method overridden in sub-classes
          */
-        public void close () throws IOException {
+        @Override
+        public void close() throws IOException {
             if (jarfile != null) {
                 jarfile.close();
             }
@@ -615,7 +627,7 @@
     }
 
     /*
-     * Inner class used to represent a Loader of resources from a JAR URL.
+     * Nested class class used to represent a Loader of resources from a JAR URL.
      */
     static class JarLoader extends Loader {
         private JarFile jar;
@@ -798,7 +810,7 @@
 
 
         /*
-         * Returns true iff atleast one resource in the jar file has the same
+         * Returns true iff at least one resource in the jar file has the same
          * package name as that of the specified resource name.
          */
         boolean validIndex(final String name) {
@@ -826,6 +838,7 @@
         /*
          * Returns the URL for a resource with the specified name
          */
+        @Override
         URL findResource(final String name, boolean check) {
             Resource rsc = getResource(name, check);
             if (rsc != null) {
@@ -837,6 +850,7 @@
         /*
          * Returns the JAR Resource for the specified name.
          */
+        @Override
         Resource getResource(final String name, boolean check) {
             try {
                 ensureOpen();
@@ -863,7 +877,6 @@
          */
         Resource getResource(final String name, boolean check,
                              Set<String> visited) {
-
             Resource res;
             String[] jarFiles;
             int count = 0;
@@ -919,7 +932,6 @@
                         continue;
                     }
 
-
                     /* Note that the addition of the url to the list of visited
                      * jars incorporates a check for presence in the hashmap
                      */
@@ -975,6 +987,7 @@
         /*
          * Returns the JAR file local class path, or null if none.
          */
+        @Override
         URL[] getClassPath() throws IOException {
             if (index != null) {
                 return null;
@@ -1002,7 +1015,7 @@
          * Parses value of the Class-Path manifest attribute and returns
          * an array of URLs relative to the specified base URL.
          */
-        private URL[] parseClassPath(URL base, String value)
+        private static URL[] parseClassPath(URL base, String value)
             throws MalformedURLException
         {
             StringTokenizer st = new StringTokenizer(value);
@@ -1018,7 +1031,7 @@
     }
 
     /*
-     * Inner class used to represent a loader of classes and resources
+     * Nested class used to represent a loader of classes and resources
      * from a file URL that refers to a directory.
      */
     private static class FileLoader extends Loader {
@@ -1038,6 +1051,7 @@
         /*
          * Returns the URL for a resource with the specified name
          */
+        @Override
         URL findResource(final String name, boolean check) {
             Resource rsc = getResource(name, check);
             if (rsc != null) {
@@ -1046,6 +1060,7 @@
             return null;
         }
 
+        @Override
         Resource getResource(final String name, boolean check) {
             final URL url;
             try {
--- a/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangAccess.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangAccess.java	Thu Mar 16 20:47:03 2017 +0000
@@ -174,4 +174,9 @@
      * Invokes Long.fastUUID
      */
     String fastUUID(long lsb, long msb);
+
+    /**
+     * Invalidate package access cache
+     */
+    void invalidatePackageAccessCache();
 }
--- a/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangModuleAccess.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/misc/JavaLangModuleAccess.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -59,20 +59,21 @@
      */
     ModuleDescriptor.Builder newModuleBuilder(String mn,
                                               boolean strict,
-                                              boolean open,
-                                              boolean synthetic);
+                                              Set<ModuleDescriptor.Modifier> ms);
+
+    /**
+     * Returns a snapshot of the packages in the module.
+     */
+    Set<String> packages(ModuleDescriptor.Builder builder);
 
     /**
-     * Returns the set of packages that are exported (unconditionally or
-     * unconditionally).
+     * Adds a dependence on a module with the given (possibly un-parsable)
+     * version string.
      */
-    Set<String> exportedPackages(ModuleDescriptor.Builder builder);
-
-    /**
-     * Returns the set of packages that are opened (unconditionally or
-     * unconditionally).
-     */
-    Set<String> openPackages(ModuleDescriptor.Builder builder);
+    void requires(ModuleDescriptor.Builder builder,
+                  Set<Requires.Modifier> ms,
+                  String mn,
+                  String compiledVersion);
 
     /**
      * Returns a {@code ModuleDescriptor.Requires} of the given modifiers
@@ -114,23 +115,11 @@
     Provides newProvides(String service, List<String> providers);
 
     /**
-     * Returns a {@code ModuleDescriptor.Version} of the given version.
-     */
-    Version newVersion(String v);
-
-    /**
-     * Clones the given module descriptor with an augmented set of packages
-     */
-    ModuleDescriptor newModuleDescriptor(ModuleDescriptor md, Set<String> pkgs);
-
-    /**
      * Returns a new {@code ModuleDescriptor} instance.
      */
     ModuleDescriptor newModuleDescriptor(String name,
                                          Version version,
-                                         boolean open,
-                                         boolean automatic,
-                                         boolean synthetic,
+                                         Set<ModuleDescriptor.Modifier> ms,
                                          Set<Requires> requires,
                                          Set<Exports> exports,
                                          Set<Opens> opens,
@@ -148,9 +137,9 @@
      * and the empty configuration as the parent. The post resolution
      * checks are optionally run.
      */
-    Configuration resolveRequiresAndUses(ModuleFinder finder,
-                                         Collection<String> roots,
-                                         boolean check,
-                                         PrintStream traceOutput);
+    Configuration resolveAndBind(ModuleFinder finder,
+                                 Collection<String> roots,
+                                 boolean check,
+                                 PrintStream traceOutput);
 
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/misc/JavaNetURLAccess.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package jdk.internal.misc;
+
+import java.net.URL;
+import java.net.URLStreamHandler;
+
+public interface JavaNetURLAccess {
+    URLStreamHandler getHandler(URL u);
+}
--- a/jdk/src/java.base/share/classes/jdk/internal/misc/SharedSecrets.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/misc/SharedSecrets.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, 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
@@ -58,6 +58,7 @@
     private static JavaNetHttpCookieAccess javaNetHttpCookieAccess;
     private static JavaNetSocketAccess javaNetSocketAccess;
     private static JavaNetUriAccess javaNetUriAccess;
+    private static JavaNetURLAccess javaNetURLAccess;
     private static JavaNetURLClassLoaderAccess javaNetURLClassLoaderAccess;
     private static JavaNioAccess javaNioAccess;
     private static JavaIOFileDescriptorAccess javaIOFileDescriptorAccess;
@@ -146,6 +147,16 @@
         return javaNetUriAccess;
     }
 
+    public static void setJavaNetURLAccess(JavaNetURLAccess jnua) {
+        javaNetURLAccess = jnua;
+    }
+
+    public static JavaNetURLAccess getJavaNetURLAccess() {
+        if (javaNetURLAccess == null)
+            unsafe.ensureClassInitialized(java.net.URL.class);
+        return javaNetURLAccess;
+    }
+
     public static void setJavaNetURLClassLoaderAccess(JavaNetURLClassLoaderAccess jnua) {
         javaNetURLClassLoaderAccess = jnua;
     }
--- a/jdk/src/java.base/share/classes/jdk/internal/module/Builder.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/Builder.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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,7 +38,7 @@
 import jdk.internal.misc.SharedSecrets;
 
 /**
- * This builder is optimized for reconstituting ModuleDescriptor
+ * This builder is optimized for reconstituting the {@code ModuleDescriptor}s
  * for system modules.  The validation should be done at jlink time.
  *
  * 1. skip name validation
@@ -136,9 +136,7 @@
     }
 
     final String name;
-    boolean open;
-    boolean automatic;
-    boolean synthetic;
+    boolean open, synthetic, mandated;
     Set<Requires> requires;
     Set<Exports> exports;
     Set<Opens> opens;
@@ -165,13 +163,13 @@
         return this;
     }
 
-    Builder automatic(boolean value) {
-        this.automatic = value;
+    Builder synthetic(boolean value) {
+        this.synthetic = value;
         return this;
     }
 
-    Builder synthetic(boolean value) {
-        this.synthetic = value;
+    Builder mandated(boolean value) {
+        this.mandated = value;
         return this;
     }
 
@@ -228,13 +226,10 @@
      *
      * @throws IllegalArgumentException if {@code v} is null or cannot be
      *         parsed as a version string
-     * @throws IllegalStateException if the module version is already set
      *
      * @see Version#parse(String)
      */
     public Builder version(String v) {
-        if (version != null)
-            throw new IllegalStateException("module version already set");
         Version ver = cachedVersion;
         if (ver != null && v.equals(ver.toString())) {
             version = ver;
@@ -246,63 +241,63 @@
 
     /**
      * Sets the module main class.
-     *
-     * @throws IllegalStateException if already set
      */
     public Builder mainClass(String mc) {
-        if (mainClass != null)
-            throw new IllegalStateException("main class already set");
         mainClass = mc;
         return this;
     }
 
     /**
      * Sets the OS name.
-     *
-     * @throws IllegalStateException if already set
      */
     public Builder osName(String name) {
-        if (osName != null)
-            throw new IllegalStateException("OS name already set");
         this.osName = name;
         return this;
     }
 
     /**
      * Sets the OS arch.
-     *
-     * @throws IllegalStateException if already set
      */
     public Builder osArch(String arch) {
-        if (osArch != null)
-            throw new IllegalStateException("OS arch already set");
         this.osArch = arch;
         return this;
     }
 
     /**
      * Sets the OS version.
-     *
-     * @throws IllegalStateException if already set
      */
     public Builder osVersion(String version) {
-        if (osVersion != null)
-            throw new IllegalStateException("OS version already set");
         this.osVersion = version;
         return this;
     }
 
     /**
+     * Returns an immutable set of the module modifiers derived from the flags.
+     */
+    private Set<ModuleDescriptor.Modifier> modifiers() {
+        int n = 0;
+        if (open) n++;
+        if (synthetic) n++;
+        if (mandated) n++;
+        if (n == 0) {
+            return Collections.emptySet();
+        } else {
+            ModuleDescriptor.Modifier[] mods = new ModuleDescriptor.Modifier[n];
+            if (open) mods[--n] = ModuleDescriptor.Modifier.OPEN;
+            if (synthetic) mods[--n] = ModuleDescriptor.Modifier.SYNTHETIC;
+            if (mandated) mods[--n] = ModuleDescriptor.Modifier.MANDATED;
+            return Set.of(mods);
+        }
+    }
+
+    /**
      * Builds a {@code ModuleDescriptor} from the components.
      */
     public ModuleDescriptor build(int hashCode) {
         assert name != null;
-
         return JLMA.newModuleDescriptor(name,
                                         version,
-                                        open,
-                                        automatic,
-                                        synthetic,
+                                        modifiers(),
                                         requires,
                                         exports,
                                         opens,
--- a/jdk/src/java.base/share/classes/jdk/internal/module/Checks.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/Checks.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2017, 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
@@ -26,7 +26,7 @@
 package jdk.internal.module;
 
 /**
- * Utility class for checking module name and binary names.
+ * Utility class for checking module, package, and class names.
  */
 
 public final class Checks {
@@ -58,8 +58,6 @@
             throw new IllegalArgumentException(name + ": Invalid module name"
                     + ": '" + id + "' is not a Java identifier");
         }
-        //if (!Character.isJavaIdentifierStart(last))
-        //    throw new IllegalArgumentException(name + ": Module name ends in digit");
         return name;
     }
 
@@ -77,8 +75,6 @@
         int last = isJavaIdentifier(name, off, name.length() - off);
         if (last == -1)
             return false;
-        //if (!Character.isJavaIdentifierStart(last))
-        //    return false;
         return true;
     }
 
@@ -89,40 +85,62 @@
      *         package name
      */
     public static String requirePackageName(String name) {
-        return requireBinaryName("package name", name);
+        return requireTypeName("package name", name);
     }
 
     /**
-     * Checks a name to ensure that it's a legal type name.
+     * Returns {@code true} if the given name is a legal package name.
+     */
+    public static boolean isPackageName(String name) {
+        return isTypeName(name);
+    }
+
+    /**
+     * Checks a name to ensure that it's a legal qualified class name
      *
      * @throws IllegalArgumentException if name is null or not a legal
-     *         type name
+     *         qualified class name
      */
     public static String requireServiceTypeName(String name) {
-        return requireBinaryName("service type name", name);
+        return requireQualifiedClassName("service type name", name);
     }
 
     /**
-     * Checks a name to ensure that it's a legal type name.
+     * Checks a name to ensure that it's a legal qualified class name.
      *
      * @throws IllegalArgumentException if name is null or not a legal
-     *         type name
+     *         qualified class name
      */
     public static String requireServiceProviderName(String name) {
-        return requireBinaryName("service provider name", name);
+        return requireQualifiedClassName("service provider name", name);
     }
 
     /**
-     * Returns {@code true} if the given name is a legal binary name.
+     * Checks a name to ensure that it's a legal qualified class name in
+     * a named package.
+     *
+     * @throws IllegalArgumentException if name is null or not a legal
+     *         qualified class name in a named package
      */
-    public static boolean isJavaIdentifier(String name) {
-        return isBinaryName(name);
+    public static String requireQualifiedClassName(String what, String name) {
+        requireTypeName(what, name);
+        if (name.indexOf('.') == -1)
+            throw new IllegalArgumentException(name + ": is not a qualified name of"
+                                               + " a Java class in a named package");
+        return name;
     }
 
     /**
-     * Returns {@code true} if the given name is a legal binary name.
+     * Returns {@code true} if the given name is a legal class name.
      */
-    public static boolean isBinaryName(String name) {
+    public static boolean isClassName(String name) {
+        return isTypeName(name);
+    }
+
+    /**
+     * Returns {@code true} if the given name is a legal type name.
+     */
+    private static boolean isTypeName(String name) {
         int next;
         int off = 0;
         while ((next = name.indexOf('.', off)) != -1) {
@@ -135,12 +153,12 @@
     }
 
     /**
-     * Checks if the given name is a legal binary name.
+     * Checks if the given name is a legal type name.
      *
      * @throws IllegalArgumentException if name is null or not a legal
-     *         binary name
+     *         type name
      */
-    public static String requireBinaryName(String what, String name) {
+    private static String requireTypeName(String what, String name) {
         if (name == null)
             throw new IllegalArgumentException("Null " + what);
         int next;
--- a/jdk/src/java.base/share/classes/jdk/internal/module/ClassFileAttributes.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/ClassFileAttributes.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -26,6 +26,7 @@
 package jdk.internal.module;
 
 import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleDescriptor.Builder;
 import java.lang.module.ModuleDescriptor.Requires;
 import java.lang.module.ModuleDescriptor.Exports;
 import java.lang.module.ModuleDescriptor.Opens;
@@ -98,14 +99,17 @@
 
             // module_flags
             int module_flags = cr.readUnsignedShort(off);
-            boolean open = ((module_flags & ACC_OPEN) != 0);
-            boolean synthetic = ((module_flags & ACC_SYNTHETIC) != 0);
             off += 2;
 
-            ModuleDescriptor.Builder builder = JLMA.newModuleBuilder(mn,
-                                                                     false,
-                                                                     open,
-                                                                     synthetic);
+            Set<ModuleDescriptor.Modifier> modifiers = new HashSet<>();
+            if ((module_flags & ACC_OPEN) != 0)
+                modifiers.add(ModuleDescriptor.Modifier.OPEN);
+            if ((module_flags & ACC_SYNTHETIC) != 0)
+                modifiers.add(ModuleDescriptor.Modifier.SYNTHETIC);
+            if ((module_flags & ACC_MANDATED) != 0)
+                modifiers.add(ModuleDescriptor.Modifier.MANDATED);
+
+            Builder builder = JLMA.newModuleBuilder(mn, false, modifiers);
 
             // module_version
             String module_version = cr.readUTF8(off, buf);
@@ -142,19 +146,13 @@
                         mods.add(Requires.Modifier.MANDATED);
                 }
 
-
                 // requires_version
-                Version compiledVersion = null;
                 String requires_version = cr.readUTF8(off, buf);
                 off += 2;
-                if (requires_version != null) {
-                    compiledVersion = Version.parse(requires_version);
-                }
-
-                if (compiledVersion == null) {
+                if (requires_version == null) {
                     builder.requires(mods, dn);
                 } else {
-                    builder.requires(mods, dn, compiledVersion);
+                    JLMA.requires(builder, mods, dn, requires_version);
                 }
             }
 
@@ -283,11 +281,14 @@
             attr.putShort(module_name_index);
 
             // module_flags
+            Set<ModuleDescriptor.Modifier> modifiers = descriptor.modifiers();
             int module_flags = 0;
-            if (descriptor.isOpen())
+            if (modifiers.contains(ModuleDescriptor.Modifier.OPEN))
                 module_flags |= ACC_OPEN;
-            if (descriptor.isSynthetic())
+            if (modifiers.contains(ModuleDescriptor.Modifier.SYNTHETIC))
                 module_flags |= ACC_SYNTHETIC;
+            if (modifiers.contains(ModuleDescriptor.Modifier.MANDATED))
+                module_flags |= ACC_MANDATED;
             attr.putShort(module_flags);
 
             // module_version
--- a/jdk/src/java.base/share/classes/jdk/internal/module/ClassFileConstants.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/ClassFileConstants.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -46,8 +46,8 @@
     // access, requires, exports, and opens flags
     public static final int ACC_MODULE        = 0x8000;
     public static final int ACC_OPEN          = 0x0020;
-    public static final int ACC_TRANSITIVE    = 0x0010;
-    public static final int ACC_STATIC_PHASE  = 0x0020;
+    public static final int ACC_TRANSITIVE    = 0x0020;
+    public static final int ACC_STATIC_PHASE  = 0x0040;
     public static final int ACC_SYNTHETIC     = 0x1000;
     public static final int ACC_MANDATED      = 0x8000;
 
--- a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleBootstrap.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleBootstrap.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -46,6 +46,7 @@
 import java.util.Optional;
 import java.util.Set;
 import java.util.function.Function;
+import java.util.stream.Stream;
 
 import jdk.internal.loader.BootLoader;
 import jdk.internal.loader.BuiltinClassLoader;
@@ -275,10 +276,10 @@
 
         // run the resolver to create the configuration
         Configuration cf = SharedSecrets.getJavaLangModuleAccess()
-                .resolveRequiresAndUses(finder,
-                                        roots,
-                                        needPostResolutionChecks,
-                                        traceOutput);
+                .resolveAndBind(finder,
+                                roots,
+                                needPostResolutionChecks,
+                                traceOutput);
 
         // time to create configuration
         PerfCounters.resolveTime.addElapsedTimeFrom(t3);
@@ -318,20 +319,20 @@
         // if needed check that there are no split packages in the set of
         // resolved modules for the boot layer
         if (SystemModules.hasSplitPackages() || needPostResolutionChecks) {
-                Map<String, String> packageToModule = new HashMap<>();
-                for (ResolvedModule resolvedModule : cf.modules()) {
-                    ModuleDescriptor descriptor =
-                        resolvedModule.reference().descriptor();
-                    String name = descriptor.name();
-                    for (String p : descriptor.packages()) {
-                        String other = packageToModule.putIfAbsent(p, name);
-                        if (other != null) {
-                            fail("Package " + p + " in both module "
-                                 + name + " and module " + other);
-                        }
+            Map<String, String> packageToModule = new HashMap<>();
+            for (ResolvedModule resolvedModule : cf.modules()) {
+                ModuleDescriptor descriptor =
+                    resolvedModule.reference().descriptor();
+                String name = descriptor.name();
+                for (String p : descriptor.packages()) {
+                    String other = packageToModule.putIfAbsent(p, name);
+                    if (other != null) {
+                        fail("Package " + p + " in both module "
+                             + name + " and module " + other);
                     }
                 }
             }
+        }
 
         long t4 = System.nanoTime();
 
@@ -380,10 +381,9 @@
                                             Set<String> otherMods)
     {
         // resolve all root modules
-        Configuration cf = Configuration.empty()
-                .resolveRequires(finder,
-                                 ModuleFinder.of(),
-                                 roots);
+        Configuration cf = Configuration.empty().resolve(finder,
+                                                         ModuleFinder.of(),
+                                                         roots);
 
         // module name -> reference
         Map<String, ModuleReference> map = new HashMap<>();
@@ -416,7 +416,7 @@
 
     /**
      * Creates a finder from the module path that is the value of the given
-     * system property.
+     * system property and optionally patched by --patch-module
      */
     private static ModuleFinder createModulePathFinder(String prop) {
         String s = System.getProperty(prop);
@@ -429,7 +429,7 @@
             for (String dir: dirs) {
                 paths[i++] = Paths.get(dir);
             }
-            return ModuleFinder.of(paths);
+            return ModulePath.of(patcher, paths);
         }
     }
 
@@ -528,6 +528,7 @@
         if (!extraOpens.isEmpty()) {
             addExtraExportsOrOpens(bootLayer, extraOpens, true);
         }
+
     }
 
     private static void addExtraExportsOrOpens(Layer bootLayer,
--- a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfo.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfo.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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,7 +37,6 @@
 import java.lang.module.ModuleDescriptor.Requires;
 import java.lang.module.ModuleDescriptor.Exports;
 import java.lang.module.ModuleDescriptor.Opens;
-import java.lang.module.ModuleDescriptor.Version;
 import java.nio.ByteBuffer;
 import java.nio.BufferUnderflowException;
 import java.util.ArrayList;
@@ -51,7 +50,6 @@
 
 import jdk.internal.misc.JavaLangModuleAccess;
 import jdk.internal.misc.SharedSecrets;
-import jdk.internal.module.ModuleResolution;
 
 import static jdk.internal.module.ClassFileConstants.*;
 
@@ -221,7 +219,7 @@
         Set<String> attributes = new HashSet<>();
 
         Builder builder = null;
-        Set<String> packages = null;
+        Set<String> allPackages = null;
         String mainClass = null;
         String[] osValues = null;
         ModuleHashes hashes = null;
@@ -245,7 +243,7 @@
                     break;
 
                 case MODULE_PACKAGES :
-                    packages = readModulePackagesAttribute(in, cpool);
+                    allPackages = readModulePackagesAttribute(in, cpool);
                     break;
 
                 case MODULE_MAIN_CLASS :
@@ -284,51 +282,44 @@
             throw invalidModuleDescriptor(MODULE + " attribute not found");
         }
 
+        // ModuleMainClass and ModuleTarget attributes
+        if (mainClass != null) {
+            builder.mainClass(mainClass);
+        }
+        if (osValues != null) {
+            if (osValues[0] != null) builder.osName(osValues[0]);
+            if (osValues[1] != null) builder.osArch(osValues[1]);
+            if (osValues[2] != null) builder.osVersion(osValues[2]);
+        }
+
         // If the ModulePackages attribute is not present then the packageFinder
         // is used to find the set of packages
         boolean usedPackageFinder = false;
-        if (packages == null && packageFinder != null) {
+        if (allPackages == null && packageFinder != null) {
             try {
-                packages = new HashSet<>(packageFinder.get());
+                allPackages = packageFinder.get();
             } catch (UncheckedIOException x) {
                 throw x.getCause();
             }
             usedPackageFinder = true;
         }
-        if (packages != null) {
-            Set<String> exportedPackages = JLMA.exportedPackages(builder);
-            Set<String> openPackages = JLMA.openPackages(builder);
-            if (packages.containsAll(exportedPackages)
-                    && packages.containsAll(openPackages)) {
-                packages.removeAll(exportedPackages);
-                packages.removeAll(openPackages);
-            } else {
-                // the set of packages is not complete
-                Set<String> exportedAndOpenPackages = new HashSet<>();
-                exportedAndOpenPackages.addAll(exportedPackages);
-                exportedAndOpenPackages.addAll(openPackages);
-                for (String pn : exportedAndOpenPackages) {
-                    if (!packages.contains(pn)) {
-                        String tail;
-                        if (usedPackageFinder) {
-                            tail = " not found by package finder";
-                        } else {
-                            tail = " missing from ModulePackages attribute";
-                        }
-                        throw invalidModuleDescriptor("Package " + pn + tail);
-                    }
+        if (allPackages != null) {
+            Set<String> knownPackages = JLMA.packages(builder);
+            if (!allPackages.containsAll(knownPackages)) {
+                Set<String> missingPackages = new HashSet<>(knownPackages);
+                missingPackages.removeAll(allPackages);
+                assert !missingPackages.isEmpty();
+                String missingPackage = missingPackages.iterator().next();
+                String tail;
+                if (usedPackageFinder) {
+                    tail = " not found in module";
+                } else {
+                    tail = " missing from ModulePackages class file attribute";
                 }
-                assert false; // should not get here
-            }
-            builder.contains(packages);
-        }
+                throw invalidModuleDescriptor("Package " + missingPackage + tail);
 
-        if (mainClass != null)
-            builder.mainClass(mainClass);
-        if (osValues != null) {
-            if (osValues[0] != null) builder.osName(osValues[0]);
-            if (osValues[1] != null) builder.osArch(osValues[1]);
-            if (osValues[2] != null) builder.osVersion(osValues[2]);
+            }
+            builder.packages(allPackages);
         }
 
         ModuleDescriptor descriptor = builder.build();
@@ -347,10 +338,17 @@
         String mn = cpool.getModuleName(module_name_index);
 
         int module_flags = in.readUnsignedShort();
+
+        Set<ModuleDescriptor.Modifier> modifiers = new HashSet<>();
         boolean open = ((module_flags & ACC_OPEN) != 0);
-        boolean synthetic = ((module_flags & ACC_SYNTHETIC) != 0);
+        if (open)
+            modifiers.add(ModuleDescriptor.Modifier.OPEN);
+        if ((module_flags & ACC_SYNTHETIC) != 0)
+            modifiers.add(ModuleDescriptor.Modifier.SYNTHETIC);
+        if ((module_flags & ACC_MANDATED) != 0)
+            modifiers.add(ModuleDescriptor.Modifier.MANDATED);
 
-        Builder builder = JLMA.newModuleBuilder(mn, false, open, synthetic);
+        Builder builder = JLMA.newModuleBuilder(mn, false, modifiers);
 
         int module_version_index = in.readUnsignedShort();
         if (module_version_index != 0) {
@@ -381,16 +379,11 @@
             }
 
             int requires_version_index = in.readUnsignedShort();
-            Version compiledVersion = null;
-            if (requires_version_index != 0) {
-                String vs = cpool.getUtf8(requires_version_index);
-                compiledVersion = Version.parse(vs);
-            }
-
-            if (compiledVersion == null) {
+            if (requires_version_index == 0) {
                 builder.requires(mods, dn);
             } else {
-                builder.requires(mods, dn, compiledVersion);
+                String vs = cpool.getUtf8(requires_version_index);
+                JLMA.requires(builder, mods, dn, vs);
             }
 
             if (dn.equals("java.base"))
@@ -629,10 +622,7 @@
 
     /**
      * Return true if the given attribute name is the name of a pre-defined
-     * attribute that is not allowed in the class file.
-     *
-     * Except for Module, InnerClasses, SourceFile, SourceDebugExtension, and
-     * Deprecated, none of the pre-defined attributes in JVMS 4.7 may appear.
+     * attribute in JVMS 4.7 that is not allowed in a module-info class.
      */
     private static boolean isAttributeDisallowed(String name) {
         Set<String> notAllowed = predefinedNotAllowed;
@@ -640,6 +630,7 @@
             notAllowed = Set.of(
                     "ConstantValue",
                     "Code",
+                    "Deprecated",
                     "StackMapTable",
                     "Exceptions",
                     "EnclosingMethod",
--- a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfoExtender.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleInfoExtender.java	Thu Mar 16 20:47:03 2017 +0000
@@ -56,7 +56,7 @@
     // the packages in the ModulePackages attribute
     private Set<String> packages;
 
-    // the value of the module_version in Module attribute
+    // the value for the module version in the Module attribute
     private Version version;
 
     // the value of the ModuleMainClass attribute
@@ -78,7 +78,11 @@
     }
 
     /**
-     * Sets the set of packages for the ModulePackages attribute
+     * Sets the packages for the ModulePackages attribute
+     *
+     * @apiNote This method does not check that the package names are legal
+     * package names or that the set of packages is a super set of the
+     * packages in the module.
      */
     public ModuleInfoExtender packages(Set<String> packages) {
         this.packages = Collections.unmodifiableSet(packages);
@@ -86,7 +90,7 @@
     }
 
     /**
-     * Sets the value of the module_version in Module attribute.
+     * Sets the value for the module version in the Module attribute
      */
     public ModuleInfoExtender version(Version version) {
         this.version = version;
@@ -95,6 +99,9 @@
 
     /**
      * Sets the value of the ModuleMainClass attribute.
+     *
+     * @apiNote This method does not check that the main class is a legal
+     * class name in a named package.
      */
     public ModuleInfoExtender mainClass(String mainClass) {
         this.mainClass = mainClass;
@@ -133,7 +140,7 @@
 
     /**
      * A ClassVisitor that supports adding class file attributes. If an
-     * attribute already exists then the first occurence of the attribute
+     * attribute already exists then the first occurrence of the attribute
      * is replaced.
      */
     private static class AttributeAddingClassVisitor extends ClassVisitor {
--- a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleLoaderMap.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleLoaderMap.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,13 +41,6 @@
  * are generated at build time.
  */
 final class ModuleLoaderMap {
-    /*
-     * The list of boot modules and platform modules are generated at build time.
-     */
-    private static final String[] BOOT_MODULES
-        = new String[] { "@@BOOT_MODULE_NAMES@@" };
-    private static final String[] PLATFORM_MODULES
-        = new String[] { "@@PLATFORM_MODULE_NAMES@@" };
 
     /**
      * Returns the function to map modules in the given configuration to the
@@ -55,6 +48,10 @@
      */
     static Function<String, ClassLoader> mappingFunction(Configuration cf) {
 
+        // The list of boot modules and platform modules are generated at build time.
+        final String[] BOOT_MODULES = new String[] { "@@BOOT_MODULE_NAMES@@" };
+        final String[] PLATFORM_MODULES = new String[] { "@@PLATFORM_MODULE_NAMES@@" };
+
         Set<String> bootModules = new HashSet<>(BOOT_MODULES.length);
         for (String mn : BOOT_MODULES) {
             bootModules.add(mn);
--- a/jdk/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModulePatcher.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -31,6 +31,7 @@
 import java.io.InputStream;
 import java.io.UncheckedIOException;
 import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleDescriptor.Builder;
 import java.lang.module.ModuleReader;
 import java.lang.module.ModuleReference;
 import java.net.MalformedURLException;
@@ -54,6 +55,7 @@
 import java.util.stream.Stream;
 
 import jdk.internal.loader.Resource;
+import jdk.internal.loader.ResourceHelper;
 import jdk.internal.misc.JavaLangModuleAccess;
 import jdk.internal.misc.SharedSecrets;
 import sun.net.www.ParseUtil;
@@ -108,8 +110,11 @@
         if (paths == null)
             return mref;
 
-        // scan the JAR file or directory tree to get the set of packages
+        // Scan the JAR file or directory tree to get the set of packages.
+        // For automatic modules then packages that do not contain class files
+        // must be ignored.
         Set<String> packages = new HashSet<>();
+        boolean isAutomatic = descriptor.isAutomatic();
         try {
             for (Path file : paths) {
                 if (Files.isRegularFile(file)) {
@@ -118,8 +123,10 @@
                     // is not supported by the boot class loader
                     try (JarFile jf = new JarFile(file.toFile())) {
                         jf.stream()
+                          .filter(e -> !e.isDirectory()
+                                  && (!isAutomatic || e.getName().endsWith(".class")))
                           .map(e -> toPackageName(file, e))
-                          .filter(Checks::isJavaIdentifier)
+                          .filter(Checks::isPackageName)
                           .forEach(packages::add);
                     }
 
@@ -129,8 +136,10 @@
                     Path top = file;
                     Files.find(top, Integer.MAX_VALUE,
                                ((path, attrs) -> attrs.isRegularFile()))
+                            .filter(path -> !isAutomatic
+                                    || path.toString().endsWith(".class"))
                             .map(path -> toPackageName(top, path))
-                            .filter(Checks::isJavaIdentifier)
+                            .filter(Checks::isPackageName)
                             .forEach(packages::add);
 
                 }
@@ -141,10 +150,30 @@
         }
 
         // if there are new packages then we need a new ModuleDescriptor
-        Set<String> original = descriptor.packages();
-        packages.addAll(original);
-        if (packages.size() > original.size()) {
-            descriptor = JLMA.newModuleDescriptor(descriptor, packages);
+        packages.removeAll(descriptor.packages());
+        if (!packages.isEmpty()) {
+            Builder builder = JLMA.newModuleBuilder(descriptor.name(),
+                                                    /*strict*/ false,
+                                                    descriptor.modifiers());
+            if (!descriptor.isAutomatic()) {
+                descriptor.requires().forEach(builder::requires);
+                descriptor.exports().forEach(builder::exports);
+                descriptor.opens().forEach(builder::opens);
+                descriptor.uses().forEach(builder::uses);
+            }
+            descriptor.provides().forEach(builder::provides);
+
+            descriptor.version().ifPresent(builder::version);
+            descriptor.mainClass().ifPresent(builder::mainClass);
+            descriptor.osName().ifPresent(builder::osName);
+            descriptor.osArch().ifPresent(builder::osArch);
+            descriptor.osVersion().ifPresent(builder::osVersion);
+
+            // original + new packages
+            builder.packages(descriptor.packages());
+            builder.packages(packages);
+
+            descriptor = builder.build();
         }
 
         // return a module reference to the patched module
@@ -471,23 +500,14 @@
 
         @Override
         public Resource find(String name) throws IOException {
-            Path file = Paths.get(name.replace('/', File.separatorChar));
-            if (file.getRoot() == null) {
-                file = dir.resolve(file);
-            } else {
-                // drop the root component so that the resource is
-                // located relative to the module directory
-                int n = file.getNameCount();
-                if (n == 0)
-                    return null;
-                file = dir.resolve(file.subpath(0, n));
+            Path path = ResourceHelper.toFilePath(name);
+            if (path != null) {
+                Path file = dir.resolve(path);
+                if (Files.isRegularFile(file)) {
+                    return newResource(name, dir, file);
+                }
             }
-
-            if (Files.isRegularFile(file)) {
-                return newResource(name, dir, file);
-            } else {
-                return null;
-            }
+            return null;
         }
 
         private Resource newResource(String name, Path top, Path file) {
--- a/jdk/src/java.base/share/classes/jdk/internal/module/ModulePath.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModulePath.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -35,7 +35,6 @@
 import java.lang.module.FindException;
 import java.lang.module.InvalidModuleDescriptorException;
 import java.lang.module.ModuleDescriptor;
-import java.lang.module.ModuleDescriptor.Requires;
 import java.lang.module.ModuleFinder;
 import java.lang.module.ModuleReference;
 import java.net.URI;
@@ -70,12 +69,11 @@
 
 /**
  * A {@code ModuleFinder} that locates modules on the file system by searching
- * a sequence of directories or packaged modules.
- *
- * The {@code ModuleFinder} can be created to work in either the run-time
- * or link-time phases. In both cases it locates modular JAR and exploded
- * modules. When created for link-time then it additionally locates
- * modules in JMOD files.
+ * a sequence of directories or packaged modules. The ModuleFinder can be
+ * created to work in either the run-time or link-time phases. In both cases it
+ * locates modular JAR and exploded modules. When created for link-time then it
+ * additionally locates modules in JMOD files. The ModuleFinder can also
+ * optionally patch any modules that it locates with a ModulePatcher.
  */
 
 public class ModulePath implements ModuleFinder {
@@ -87,6 +85,9 @@
     // true for the link phase (supports modules packaged in JMOD format)
     private final boolean isLinkPhase;
 
+    // for patching modules, can be null
+    private final ModulePatcher patcher;
+
     // the entries on this module path
     private final Path[] entries;
     private int next;
@@ -94,19 +95,51 @@
     // map of module name to module reference map for modules already located
     private final Map<String, ModuleReference> cachedModules = new HashMap<>();
 
-    public ModulePath(Runtime.Version version, boolean isLinkPhase, Path... entries) {
+
+    private ModulePath(Runtime.Version version,
+                       boolean isLinkPhase,
+                       ModulePatcher patcher,
+                       Path... entries) {
         this.releaseVersion = version;
         this.isLinkPhase = isLinkPhase;
+        this.patcher = patcher;
         this.entries = entries.clone();
         for (Path entry : this.entries) {
             Objects.requireNonNull(entry);
         }
     }
 
-    public ModulePath(Path... entries) {
-        this(JarFile.runtimeVersion(), false, entries);
+    /**
+     * Returns a ModuleFinder that that locates modules on the file system by
+     * searching a sequence of directories and/or packaged modules. The modules
+     * may be patched by the given ModulePatcher.
+     */
+    public static ModuleFinder of(ModulePatcher patcher, Path... entries) {
+        return new ModulePath(JarFile.runtimeVersion(), false, patcher, entries);
     }
 
+    /**
+     * Returns a ModuleFinder that that locates modules on the file system by
+     * searching a sequence of directories and/or packaged modules.
+     */
+    public static ModuleFinder of(Path... entries) {
+        return of((ModulePatcher)null, entries);
+    }
+
+    /**
+     * Returns a ModuleFinder that that locates modules on the file system by
+     * searching a sequence of directories and/or packaged modules.
+     *
+     * @param version The release version to use for multi-release JAR files
+     * @param isLinkPhase {@code true} if the link phase to locate JMOD files
+     */
+    public static ModuleFinder of(Runtime.Version version,
+                                  boolean isLinkPhase,
+                                  Path... entries) {
+        return new ModulePath(version, isLinkPhase, null, entries);
+    }
+
+
     @Override
     public Optional<ModuleReference> find(String name) {
         Objects.requireNonNull(name);
@@ -195,8 +228,7 @@
             if (attrs.isDirectory()) {
                 Path mi = entry.resolve(MODULE_INFO);
                 if (!Files.exists(mi)) {
-                    // does not exist or unable to determine so assume a
-                    // directory of modules
+                    // assume a directory of modules
                     return scanDirectory(entry);
                 }
             }
@@ -206,10 +238,16 @@
             if (mref != null) {
                 String name = mref.descriptor().name();
                 return Collections.singletonMap(name, mref);
+            }
+
+            // not recognized
+            String msg;
+            if (!isLinkPhase && entry.toString().endsWith(".jmod")) {
+                msg = "JMOD format not supported at execution time";
             } else {
-                // skipped
-                return Collections.emptyMap();
+                msg = "Module format not recognized";
             }
+            throw new FindException(msg + ": " + entry);
 
         } catch (IOException ioe) {
             throw new FindException(ioe);
@@ -266,14 +304,11 @@
 
 
     /**
-     * Locates a packaged or exploded module, returning a {@code ModuleReference}
-     * to the module. Returns {@code null} if the entry is skipped because it is
-     * to a directory that does not contain a module-info.class or it's a hidden
-     * file.
+     * Reads a packaged or exploded module, returning a {@code ModuleReference}
+     * to the module. Returns {@code null} if the entry is not recognized.
      *
      * @throws IOException if an I/O error occurs
-     * @throws FindException if the file is not recognized as a module or an
-     *         error occurs parsing its module descriptor
+     * @throws FindException if an error occurs parsing its module descriptor
      */
     private ModuleReference readModule(Path entry, BasicFileAttributes attrs)
         throws IOException
@@ -282,24 +317,16 @@
 
             if (attrs.isDirectory()) {
                 return readExplodedModule(entry); // may return null
-            }
-
-            String fn = entry.getFileName().toString();
-            if (attrs.isRegularFile()) {
-                if (fn.endsWith(".jar")) {
-                    return readJar(entry);
-                } else if (fn.endsWith(".jmod")) {
-                    if (isLinkPhase)
+            } else {
+                String fn = entry.getFileName().toString();
+                if (attrs.isRegularFile()) {
+                    if (fn.endsWith(".jar")) {
+                        return readJar(entry);
+                    } else if (isLinkPhase && fn.endsWith(".jmod")) {
                         return readJMod(entry);
-                    throw new FindException("JMOD files not supported: " + entry);
+                    }
                 }
-            }
-
-            // skip hidden files
-            if (fn.startsWith(".") || Files.isHidden(entry)) {
                 return null;
-            } else {
-                throw new FindException("Unrecognized module: " + entry);
             }
 
         } catch (InvalidModuleDescriptorException e) {
@@ -327,7 +354,7 @@
         }
     }
 
-    // -- jmod files --
+    // -- JMOD files --
 
     private Set<String> jmodPackages(JmodFile jf) {
         return jf.stream()
@@ -339,7 +366,7 @@
     }
 
     /**
-     * Returns a {@code ModuleReference} to a module in jmod file on the
+     * Returns a {@code ModuleReference} to a module in JMOD file on the
      * file system.
      *
      * @throws IOException
@@ -362,7 +389,7 @@
 
     /**
      * Returns the service type corresponding to the name of a services
-     * configuration file if it is a valid Java identifier.
+     * configuration file if it is a legal type name.
      *
      * For example, if called with "META-INF/services/p.S" then this method
      * returns a container with the value "p.S".
@@ -374,7 +401,7 @@
             String prefix = cf.substring(0, index);
             if (prefix.equals(SERVICES_PREFIX)) {
                 String sn = cf.substring(index);
-                if (Checks.isJavaIdentifier(sn))
+                if (Checks.isClassName(sn))
                     return Optional.of(sn);
             }
         }
@@ -403,11 +430,10 @@
      *
      * 1. The module name (and optionally the version) is derived from the file
      *    name of the JAR file
-     * 2. All packages are exported and open
-     * 3. It has no non-exported/non-open packages
-     * 4. The contents of any META-INF/services configuration files are mapped
+     * 2. All packages are derived from the .class files in the JAR file
+     * 3. The contents of any META-INF/services configuration files are mapped
      *    to "provides" declarations
-     * 5. The Main-Class attribute in the main attributes of the JAR manifest
+     * 4. The Main-Class attribute in the main attributes of the JAR manifest
      *    is mapped to the module descriptor mainClass
      */
     private ModuleDescriptor deriveModuleDescriptor(JarFile jf)
@@ -443,9 +469,7 @@
         mn = cleanModuleName(mn);
 
         // Builder throws IAE if module name is empty or invalid
-        ModuleDescriptor.Builder builder
-            = ModuleDescriptor.automaticModule(mn)
-                .requires(Set.of(Requires.Modifier.MANDATED), "java.base");
+        ModuleDescriptor.Builder builder = ModuleDescriptor.newAutomaticModule(mn);
         if (vs != null)
             builder.version(vs);
 
@@ -453,17 +477,22 @@
         Map<Boolean, Set<String>> map = VersionedStream.stream(jf)
                 .filter(e -> !e.isDirectory())
                 .map(JarEntry::getName)
+                .filter(e -> (e.endsWith(".class") ^ e.startsWith(SERVICES_PREFIX)))
                 .collect(Collectors.partitioningBy(e -> e.startsWith(SERVICES_PREFIX),
                                                    Collectors.toSet()));
 
-        Set<String> resources = map.get(Boolean.FALSE);
+        Set<String> classFiles = map.get(Boolean.FALSE);
         Set<String> configFiles = map.get(Boolean.TRUE);
-        // all packages are exported and open
-        resources.stream()
+
+        // the packages containing class files
+        Set<String> packages = classFiles.stream()
                 .map(this::toPackageName)
                 .flatMap(Optional::stream)
                 .distinct()
-                .forEach(pn -> builder.exports(pn).opens(pn));
+                .collect(Collectors.toSet());
+
+        // all packages are exported and open
+        builder.packages(packages);
 
         // map names of service configuration files to service names
         Set<String> serviceNames = configFiles.stream()
@@ -481,6 +510,11 @@
                 String cn;
                 while ((cn = nextLine(reader)) != null) {
                     if (cn.length() > 0) {
+                        String pn = packageName(cn);
+                        if (!packages.contains(pn)) {
+                            String msg = "Provider class " + cn + " not in module";
+                            throw new IOException(msg);
+                        }
                         providerClasses.add(cn);
                     }
                 }
@@ -494,8 +528,15 @@
         if (man != null) {
             Attributes attrs = man.getMainAttributes();
             String mainClass = attrs.getValue(Attributes.Name.MAIN_CLASS);
-            if (mainClass != null)
-                builder.mainClass(mainClass.replace("/", "."));
+            if (mainClass != null) {
+                mainClass = mainClass.replace("/", ".");
+                String pn = packageName(mainClass);
+                if (!packages.contains(pn)) {
+                    String msg = "Main-Class " + mainClass + " not in module";
+                    throw new IOException(msg);
+                }
+                builder.mainClass(mainClass);
+            }
         }
 
         return builder.build();
@@ -569,10 +610,10 @@
                 try {
                     ModuleDescriptor md = deriveModuleDescriptor(jf);
                     attrs = new ModuleInfo.Attributes(md, null, null);
-                } catch (IllegalArgumentException iae) {
+                } catch (IllegalArgumentException e) {
                     throw new FindException(
                         "Unable to derive module descriptor for: "
-                        + jf.getName(), iae);
+                        + jf.getName(), e);
                 }
 
             } else {
@@ -580,7 +621,7 @@
                                         () -> jarPackages(jf));
             }
 
-            return ModuleReferences.newJarModule(attrs, file);
+            return ModuleReferences.newJarModule(attrs, patcher, file);
         }
     }
 
@@ -617,7 +658,15 @@
             // for now
             return null;
         }
-        return ModuleReferences.newExplodedModule(attrs, dir);
+        return ModuleReferences.newExplodedModule(attrs, patcher, dir);
+    }
+
+    /**
+     * Maps a type name to its package name.
+     */
+    private static String packageName(String cn) {
+        int index = cn.lastIndexOf('.');
+        return (index == -1) ? "" : cn.substring(0, index);
     }
 
     /**
@@ -629,19 +678,18 @@
      */
     private Optional<String> toPackageName(String name) {
         assert !name.endsWith("/");
-
         int index = name.lastIndexOf("/");
         if (index == -1) {
             if (name.endsWith(".class") && !name.equals(MODULE_INFO)) {
                 throw new IllegalArgumentException(name
-                        + " found in top-level directory:"
+                        + " found in top-level directory"
                         + " (unnamed package not allowed in module)");
             }
             return Optional.empty();
         }
 
         String pn = name.substring(0, index).replace('/', '.');
-        if (Checks.isJavaIdentifier(pn)) {
+        if (Checks.isPackageName(pn)) {
             return Optional.of(pn);
         } else {
             // not a valid package name
@@ -654,7 +702,7 @@
      * name.
      *
      * @throws IllegalArgumentException if the name is a class file in
-     *         the top-level directory (and it's not module-info.class)
+     *          the top-level directory (and it's not module-info.class)
      */
     private Optional<String> toPackageName(Path file) {
         assert file.getRoot() == null;
@@ -664,14 +712,14 @@
             String name = file.toString();
             if (name.endsWith(".class") && !name.equals(MODULE_INFO)) {
                 throw new IllegalArgumentException(name
-                        + " found in in top-level directory"
+                        + " found in top-level directory"
                         + " (unnamed package not allowed in module)");
             }
             return Optional.empty();
         }
 
         String pn = parent.toString().replace(File.separatorChar, '.');
-        if (Checks.isJavaIdentifier(pn)) {
+        if (Checks.isPackageName(pn)) {
             return Optional.of(pn);
         } else {
             // not a valid package name
--- a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleReferenceImpl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleReferenceImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -163,7 +163,14 @@
 
     @Override
     public String toString() {
-        return super.toString();
+        StringBuilder sb = new StringBuilder();
+        sb.append("[module ");
+        sb.append(descriptor().name());
+        sb.append(", location=");
+        sb.append(location().orElseThrow(() -> new InternalError()));
+        if (isPatched()) sb.append(" (patched)");
+        sb.append("]");
+        return sb.toString();
     }
 
 }
--- a/jdk/src/java.base/share/classes/jdk/internal/module/ModuleReferences.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/ModuleReferences.java	Thu Mar 16 20:47:03 2017 +0000
@@ -36,7 +36,6 @@
 import java.nio.ByteBuffer;
 import java.nio.file.Files;
 import java.nio.file.Path;
-import java.nio.file.Paths;
 import java.util.List;
 import java.util.Objects;
 import java.util.Optional;
@@ -51,7 +50,7 @@
 import java.util.zip.ZipFile;
 
 import jdk.internal.jmod.JmodFile;
-import jdk.internal.misc.JavaLangAccess;
+import jdk.internal.loader.ResourceHelper;
 import jdk.internal.misc.SharedSecrets;
 import jdk.internal.module.ModuleHashes.HashSupplier;
 import jdk.internal.util.jar.VersionedStream;
@@ -65,20 +64,16 @@
  */
 
 class ModuleReferences {
-
-    private static final JavaLangAccess JLA = SharedSecrets.getJavaLangAccess();
-
     private ModuleReferences() { }
 
     /**
-     * Creates a ModuleReference to a module or to patched module when
-     * creating modules for the boot Layer and --patch-module is specified.
+     * Creates a ModuleReference to a possibly-patched module
      */
     private static ModuleReference newModule(ModuleInfo.Attributes attrs,
                                              URI uri,
                                              Supplier<ModuleReader> supplier,
+                                             ModulePatcher patcher,
                                              HashSupplier hasher) {
-
         ModuleReference mref = new ModuleReferenceImpl(attrs.descriptor(),
                                                        uri,
                                                        supplier,
@@ -86,38 +81,42 @@
                                                        attrs.recordedHashes(),
                                                        hasher,
                                                        attrs.moduleResolution());
-        if (JLA.getBootLayer() == null)
-            mref = ModuleBootstrap.patcher().patchIfNeeded(mref);
+        if (patcher != null)
+            mref = patcher.patchIfNeeded(mref);
 
         return mref;
     }
 
     /**
-     * Creates a ModuleReference to a module packaged as a modular JAR.
+     * Creates a ModuleReference to a possibly-patched module in a modular JAR.
      */
-    static ModuleReference newJarModule(ModuleInfo.Attributes attrs, Path file) {
+    static ModuleReference newJarModule(ModuleInfo.Attributes attrs,
+                                        ModulePatcher patcher,
+                                        Path file) {
         URI uri = file.toUri();
         Supplier<ModuleReader> supplier = () -> new JarModuleReader(file, uri);
         HashSupplier hasher = (a) -> ModuleHashes.computeHash(file, a);
-        return newModule(attrs, uri, supplier, hasher);
+        return newModule(attrs, uri, supplier, patcher, hasher);
     }
 
     /**
-     * Creates a ModuleReference to a module packaged as a JMOD.
+     * Creates a ModuleReference to a module in a JMOD file.
      */
     static ModuleReference newJModModule(ModuleInfo.Attributes attrs, Path file) {
         URI uri = file.toUri();
         Supplier<ModuleReader> supplier = () -> new JModModuleReader(file, uri);
         HashSupplier hasher = (a) -> ModuleHashes.computeHash(file, a);
-        return newModule(attrs, uri, supplier, hasher);
+        return newModule(attrs, uri, supplier, null, hasher);
     }
 
     /**
-     * Creates a ModuleReference to an exploded module.
+     * Creates a ModuleReference to a possibly-patched exploded module.
      */
-    static ModuleReference newExplodedModule(ModuleInfo.Attributes attrs, Path dir) {
+    static ModuleReference newExplodedModule(ModuleInfo.Attributes attrs,
+                                             ModulePatcher patcher,
+                                             Path dir) {
         Supplier<ModuleReader> supplier = () -> new ExplodedModuleReader(dir);
-        return newModule(attrs, dir.toUri(), supplier, null);
+        return newModule(attrs, dir.toUri(), supplier, patcher, null);
     }
 
 
@@ -243,7 +242,8 @@
         }
 
         private JarEntry getEntry(String name) {
-            return jf.getJarEntry(Objects.requireNonNull(name));
+            JarEntry entry = jf.getJarEntry(Objects.requireNonNull(name));
+            return (entry == null || entry.isDirectory()) ? null : entry;
         }
 
         @Override
@@ -370,32 +370,33 @@
         }
 
         /**
-         * Returns a Path to access to the given resource.
-         */
-        private Path toPath(String name) {
-            Path path = Paths.get(name.replace('/', File.separatorChar));
-            if (path.getRoot() == null) {
-                return dir.resolve(path);
-            } else {
-                // drop the root component so that the resource is
-                // located relative to the module directory
-                int n = path.getNameCount();
-                return (n > 0) ? dir.resolve(path.subpath(0, n)) : null;
-            }
-        }
-
-        /**
          * Throws IOException if the module reader is closed;
          */
         private void ensureOpen() throws IOException {
             if (closed) throw new IOException("ModuleReader is closed");
         }
 
+        /**
+         * Returns a Path to access the given resource. Returns null if the
+         * resource name does not convert to a file path that locates a regular
+         * file in the module.
+         */
+        private Path toFilePath(String name) {
+            Path path = ResourceHelper.toFilePath(name);
+            if (path != null) {
+                Path file = dir.resolve(path);
+                if (Files.isRegularFile(file)) {
+                    return file;
+                }
+            }
+            return null;
+        }
+
         @Override
         public Optional<URI> find(String name) throws IOException {
             ensureOpen();
-            Path path = toPath(name);
-            if (path != null && Files.isRegularFile(path)) {
+            Path path = toFilePath(name);
+            if (path != null) {
                 try {
                     return Optional.of(path.toUri());
                 } catch (IOError e) {
@@ -409,8 +410,8 @@
         @Override
         public Optional<InputStream> open(String name) throws IOException {
             ensureOpen();
-            Path path = toPath(name);
-            if (path != null && Files.isRegularFile(path)) {
+            Path path = toFilePath(name);
+            if (path != null) {
                 return Optional.of(Files.newInputStream(path));
             } else {
                 return Optional.empty();
@@ -420,8 +421,8 @@
         @Override
         public Optional<ByteBuffer> read(String name) throws IOException {
             ensureOpen();
-            Path path = toPath(name);
-            if (path != null && Files.isRegularFile(path)) {
+            Path path = toFilePath(name);
+            if (path != null) {
                 return Optional.of(ByteBuffer.wrap(Files.readAllBytes(path)));
             } else {
                 return Optional.empty();
--- a/jdk/src/java.base/share/classes/jdk/internal/module/Modules.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/Modules.java	Thu Mar 16 20:47:03 2017 +0000
@@ -82,8 +82,8 @@
                                       String name,
                                       Set<String> packages)
     {
-        ModuleDescriptor descriptor = ModuleDescriptor.module(name)
-                .contains(packages)
+        ModuleDescriptor descriptor = ModuleDescriptor.newModule(name)
+                .packages(packages)
                 .build();
 
         return JLRMA.defineModule(loader, descriptor, null);
@@ -185,7 +185,8 @@
     /**
      * Adds a package to a module's content.
      *
-     * This method is a no-op if the module already contains the package.
+     * This method is a no-op if the module already contains the package or the
+     * module is an unnamed module.
      */
     public static void addPackage(Module m, String pn) {
         JLRMA.addPackage(m, pn);
--- a/jdk/src/java.base/share/classes/jdk/internal/module/SystemModuleFinder.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/module/SystemModuleFinder.java	Thu Mar 16 20:47:03 2017 +0000
@@ -80,8 +80,6 @@
         = PerfCounter.newPerfCounter("jdk.module.finder.jimage.packages");
     private static final PerfCounter exportsCount
         = PerfCounter.newPerfCounter("jdk.module.finder.jimage.exports");
-    // ImageReader used to access all modules in the image
-    private static final ImageReader imageReader;
 
     // singleton finder to find modules in the run-time images
     private static final SystemModuleFinder INSTANCE;
@@ -96,13 +94,28 @@
      */
     static {
         long t0 = System.nanoTime();
-        imageReader = ImageReaderFactory.getImageReader();
 
         INSTANCE = new SystemModuleFinder();
 
         initTime.addElapsedTimeFrom(t0);
     }
 
+    /**
+     * Holder class for the ImageReader
+     */
+    private static class SystemImage {
+        static final ImageReader READER;
+        static {
+            long t0 = System.nanoTime();
+            READER = ImageReaderFactory.getImageReader();
+            initTime.addElapsedTimeFrom(t0);
+        }
+
+        static ImageReader reader() {
+            return READER;
+        }
+    }
+
     private static boolean isFastPathSupported() {
        return SystemModules.MODULE_NAMES.length > 0;
     }
@@ -114,7 +127,7 @@
 
         // this happens when java.base is patched with java.base
         // from an exploded image
-        return imageReader.getModuleNames();
+        return SystemImage.reader().getModuleNames();
     }
 
     // the set of modules in the run-time image
@@ -151,6 +164,7 @@
             descriptors = new ModuleDescriptor[n];
             recordedHashes = new ModuleHashes[n];
             moduleResolutions = new ModuleResolution[n];
+            ImageReader imageReader = SystemImage.reader();
             for (int i = 0; i < names.length; i++) {
                 String mn = names[i];
                 ImageLocation loc = imageReader.findLocation(mn, "module-info.class");
@@ -291,6 +305,7 @@
             Objects.requireNonNull(name);
             if (closed)
                 throw new IOException("ModuleReader is closed");
+            ImageReader imageReader = SystemImage.reader();
             if (imageReader != null) {
                 return imageReader.findLocation(module, name);
             } else {
@@ -330,7 +345,7 @@
         public Optional<ByteBuffer> read(String name) throws IOException {
             ImageLocation location = findImageLocation(name);
             if (location != null) {
-                return Optional.of(imageReader.getResourceBuffer(location));
+                return Optional.of(SystemImage.reader().getResourceBuffer(location));
             } else {
                 return Optional.empty();
             }
@@ -372,7 +387,7 @@
             stack = new ArrayDeque<>();
 
             // push the root node to the stack to get started
-            ImageReader.Node dir = imageReader.findNode(moduleRoot);
+            ImageReader.Node dir = SystemImage.reader().findNode(moduleRoot);
             if (dir == null || !dir.isDirectory())
                 throw new IOException(moduleRoot + " not a directory");
             stack.push(dir);
@@ -390,7 +405,7 @@
                     String name = node.getName();
                     if (node.isDirectory()) {
                         // build node
-                        ImageReader.Node dir = imageReader.findNode(name);
+                        ImageReader.Node dir = SystemImage.reader().findNode(name);
                         assert dir.isDirectory();
                         stack.push(dir);
                     } else {
--- a/jdk/src/java.base/share/classes/jdk/internal/reflect/Reflection.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/jdk/internal/reflect/Reflection.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2017, 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
@@ -211,15 +211,7 @@
         if (currentModule == memberModule)
            return true;  // same module (named or unnamed)
 
-        // memberClass may be primitive or array class
-        Class<?> c = memberClass;
-        while (c.isArray()) {
-            c = c.getComponentType();
-        }
-        if (c.isPrimitive())
-            return true;
-
-        String pkg = c.getPackageName();
+        String pkg = memberClass.getPackageName();
         boolean allowed = memberModule.isExported(pkg, currentModule);
         if (allowed && memberModule.isNamed() && printStackTraceWhenAccessSucceeds()) {
             if (!SharedSecrets.getJavaLangReflectModuleAccess()
@@ -237,10 +229,6 @@
     private static boolean isSameClassPackage(Class<?> c1, Class<?> c2) {
         if (c1.getClassLoader() != c2.getClassLoader())
             return false;
-        while (c1.isArray())
-            c1 = c1.getComponentType();
-        while (c2.isArray())
-            c2 = c2.getComponentType();
         return Objects.equals(c1.getPackageName(), c2.getPackageName());
     }
 
@@ -378,12 +366,6 @@
         }
     }
 
-    public static void enableStackTraces() {
-        printStackWhenAccessFails = true;
-        printStackWhenAccessSucceeds = true;
-        printStackPropertiesSet = true;
-    }
-
     public static boolean printStackTraceWhenAccessFails() {
         ensurePrintStackPropertiesSet();
         return printStackWhenAccessFails;
@@ -413,11 +395,7 @@
         if (m2.isNamed())
             memberSuffix = " (in " + m2 + ")";
 
-        Class<?> c = memberClass;
-        while (c.isArray()) {
-            c = c.getComponentType();
-        }
-        String memberPackageName = c.getPackageName();
+        String memberPackageName = memberClass.getPackageName();
 
         String msg = currentClass + currentSuffix + " cannot access ";
         if (m2.isExported(memberPackageName, m1)) {
--- a/jdk/src/java.base/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines the foundational APIs of the Java SE Platform.
+ *
+ * @since 9
  */
 module java.base {
 
@@ -237,8 +239,7 @@
         java.management.rmi,
         java.rmi,
         java.sql.rowset,
-        java.xml,
-        java.xml.ws;
+        java.xml;
     exports sun.security.action to
         java.desktop,
         java.security.jgss;
--- a/jdk/src/java.base/share/classes/sun/invoke/util/VerifyAccess.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/invoke/util/VerifyAccess.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2017, 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
@@ -39,6 +39,7 @@
 
     private VerifyAccess() { }  // cannot instantiate
 
+    private static final int UNCONDITIONAL_ALLOWED = java.lang.invoke.MethodHandles.Lookup.UNCONDITIONAL;
     private static final int MODULE_ALLOWED = java.lang.invoke.MethodHandles.Lookup.MODULE;
     private static final int PACKAGE_ONLY = 0;
     private static final int PACKAGE_ALLOWED = java.lang.invoke.MethodHandles.Lookup.PACKAGE;
@@ -92,7 +93,7 @@
                                              int      allowedModes) {
         if (allowedModes == 0)  return false;
         assert((allowedModes & PUBLIC) != 0 &&
-               (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED|MODULE_ALLOWED)) == 0);
+               (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED|MODULE_ALLOWED|UNCONDITIONAL_ALLOWED)) == 0);
         // The symbolic reference class (refc) must always be fully verified.
         if (!isClassAccessible(refc, lookupClass, allowedModes)) {
             return false;
@@ -173,7 +174,7 @@
                                             int allowedModes) {
         if (allowedModes == 0)  return false;
         assert((allowedModes & PUBLIC) != 0 &&
-               (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED|MODULE_ALLOWED)) == 0);
+               (allowedModes & ~(ALL_ACCESS_MODES|PACKAGE_ALLOWED|MODULE_ALLOWED|UNCONDITIONAL_ALLOWED)) == 0);
         int mods = getClassModifiers(refc);
         if (isPublic(mods)) {
 
@@ -191,22 +192,17 @@
                 (lookupModule == refModule))
                 return true;
 
-            // check readability
-            if (lookupModule.canRead(refModule)) {
+            // check readability when UNCONDITIONAL not allowed
+            if (((allowedModes & UNCONDITIONAL_ALLOWED) != 0)
+                || lookupModule.canRead(refModule)) {
 
                 // check that refc is in an exported package
-                Class<?> c = refc;
-                while (c.isArray()) {
-                    c = c.getComponentType();
-                }
-                if (c.isPrimitive())
-                    return true;
                 if ((allowedModes & MODULE_ALLOWED) != 0) {
-                    if (refModule.isExported(c.getPackageName(), lookupModule))
+                    if (refModule.isExported(refc.getPackageName(), lookupModule))
                         return true;
                 } else {
                     // exported unconditionally
-                    if (refModule.isExported(c.getPackageName()))
+                    if (refModule.isExported(refc.getPackageName()))
                         return true;
                 }
 
--- a/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/launcher/LauncherHelper.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2017, 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
@@ -591,8 +591,8 @@
                 c = Class.forName(m, cn);
             }
         } catch (LinkageError le) {
-            abort(null, "java.launcher.module.error3",
-                    mainClass, m.getName(), le.getLocalizedMessage());
+            abort(null, "java.launcher.module.error3", mainClass, m.getName(),
+                    le.getClass().getName() + ": " + le.getLocalizedMessage());
         }
         if (c == null) {
             abort(null, "java.launcher.module.error2", mainClass, mainModule);
@@ -638,14 +638,17 @@
                         String ncn = Normalizer.normalize(cn, Normalizer.Form.NFC);
                         mainClass = Class.forName(ncn, false, scl);
                     } catch (NoClassDefFoundError | ClassNotFoundException cnfe1) {
-                        abort(cnfe1, "java.launcher.cls.error1", cn);
+                        abort(cnfe1, "java.launcher.cls.error1", cn,
+                                cnfe1.getClass().getCanonicalName(), cnfe1.getMessage());
                     }
                 } else {
-                    abort(cnfe, "java.launcher.cls.error1", cn);
+                    abort(cnfe, "java.launcher.cls.error1", cn,
+                            cnfe.getClass().getCanonicalName(), cnfe.getMessage());
                 }
             }
         } catch (LinkageError le) {
-            abort(le, "java.launcher.cls.error6", cn, le.getLocalizedMessage());
+            abort(le, "java.launcher.cls.error6", cn,
+                    le.getClass().getName() + ": " + le.getLocalizedMessage());
         }
         return mainClass;
     }
@@ -966,6 +969,10 @@
                     ostream.print("open ");
                 if (md.isAutomatic())
                     ostream.print("automatic ");
+                if (md.modifiers().contains(ModuleDescriptor.Modifier.SYNTHETIC))
+                    ostream.print("synthetic ");
+                if (md.modifiers().contains(ModuleDescriptor.Modifier.MANDATED))
+                    ostream.print("mandated ");
                 ostream.println("module " + midAndLocation(md, mref.location()));
 
                 // unqualified exports (sorted by package)
--- a/jdk/src/java.base/share/classes/sun/launcher/resources/launcher.properties	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/launcher/resources/launcher.properties	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2007, 2017, 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
@@ -175,7 +175,8 @@
 \                      override default icon displayed in dock\n\n
 
 java.launcher.cls.error1=\
-    Error: Could not find or load main class {0}
+    Error: Could not find or load main class {0}\n\
+    Caused by: {1}: {2}
 java.launcher.cls.error2=\
     Error: Main method is not {0} in class {1}, please define the main method as:\n\
 \   public static void main(String[] args)
--- a/jdk/src/java.base/share/classes/sun/net/www/protocol/jrt/JavaRuntimeURLConnection.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/net/www/protocol/jrt/JavaRuntimeURLConnection.java	Thu Mar 16 20:47:03 2017 +0000
@@ -32,7 +32,9 @@
 import java.io.InputStream;
 import java.net.MalformedURLException;
 import java.net.URL;
+import java.security.AccessController;
 import java.security.Permission;
+import java.security.PrivilegedAction;
 
 import jdk.internal.jimage.ImageLocation;
 import jdk.internal.jimage.ImageReader;
@@ -51,7 +53,11 @@
 public class JavaRuntimeURLConnection extends URLConnection {
 
     // ImageReader to access resources in jimage
-    private static final ImageReader reader = ImageReaderFactory.getImageReader();
+    private static final ImageReader reader;
+    static {
+        PrivilegedAction<ImageReader> pa = ImageReaderFactory::getImageReader;
+        reader = AccessController.doPrivileged(pa);
+    }
 
     // the module and resource name in the URL
     private final String module;
--- a/jdk/src/java.base/share/classes/sun/nio/cs/StandardCharsets.java.template	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/nio/cs/StandardCharsets.java.template	Thu Mar 16 20:47:03 2017 +0000
@@ -32,7 +32,6 @@
 import java.nio.charset.Charset;
 import java.nio.charset.spi.CharsetProvider;
 import java.util.Iterator;
-import java.util.Locale;
 import java.util.Map;
 import sun.security.action.GetPropertyAction;
 
@@ -44,13 +43,13 @@
     _INCLUDE_CACHE_MAP_
 
     // Maps canonical names to class names
-    private Map<String,String> classMap;
+    private final Map<String,String> classMap;
     // Maps alias names to canonical names
-    private Map<String,String> aliasMap;
+    private final Map<String,String> aliasMap;
     // Maps canonical names to cached instances
-    private Map<String,Charset> cache;
+    private final Map<String,Charset> cache;
 
-    private String packagePrefix = "sun.nio.cs";
+    private static final String packagePrefix = "sun.nio.cs";
 
     public StandardCharsets() {
         this.aliasMap = new Aliases();
@@ -102,10 +101,16 @@
         if (cln == null)
             return null;
 
-        if (cln.equals("US_ASCII")) {
-            cs = new US_ASCII();
-            cache.put(csn, cs);
-            return cs;
+        // As all charset class names added to classMap are string literals we
+        // can check identity here as an optimization
+        if (cln == "US_ASCII") {
+            return cache(csn, new US_ASCII());
+        }
+        if (cln == "ISO_8859_1") {
+            return cache(csn, new ISO_8859_1());
+        }
+        if (cln == "UTF_8") {
+            return cache(csn, new UTF_8());
         }
 
         // Instantiate the charset and cache it
@@ -114,9 +119,7 @@
             Object o = Class.forName(packagePrefix + "." + cln,
                                      true,
                                      this.getClass().getClassLoader()).newInstance();
-            cs = (Charset)o;
-            cache.put(csn, cs);
-            return cs;
+            return cache(csn, (Charset)o);
         } catch (ClassNotFoundException |
                  IllegalAccessException |
                  InstantiationException x) {
@@ -124,6 +127,11 @@
         }
     }
 
+    private Charset cache(String csn, Charset cs) {
+        cache.put(csn, cs);
+        return cs;
+    }
+
     public final Charset charsetForName(String charsetName) {
         synchronized (this) {
             return lookup(canonicalize(charsetName));
--- a/jdk/src/java.base/share/classes/sun/nio/cs/US_ASCII.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/nio/cs/US_ASCII.java	Thu Mar 16 20:47:03 2017 +0000
@@ -31,7 +31,6 @@
 import java.nio.charset.CharsetDecoder;
 import java.nio.charset.CharsetEncoder;
 import java.nio.charset.CoderResult;
-import java.util.Arrays;
 
 public class US_ASCII
     extends Charset
--- a/jdk/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/pkcs/SignerInfo.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 2017, 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.Signature;
 import java.security.SignatureException;
 import java.security.Timestamp;
+import java.security.cert.CertPathValidatorException;
 import java.security.cert.CertificateException;
 import java.security.cert.CertificateFactory;
 import java.security.cert.CertPath;
@@ -48,6 +49,7 @@
 import java.util.Set;
 
 import sun.security.timestamp.TimestampToken;
+import sun.security.util.ConstraintsParameters;
 import sun.security.util.Debug;
 import sun.security.util.DerEncoder;
 import sun.security.util.DerInputStream;
@@ -321,6 +323,8 @@
                 data = content.getContentBytes();
             }
 
+            ConstraintsParameters cparams =
+                    new ConstraintsParameters(timestamp);
             String digestAlgname = getDigestAlgorithmId().getName();
 
             byte[] dataSigned;
@@ -347,11 +351,11 @@
                 if (messageDigest == null) // fail if there is no message digest
                     return null;
 
-                // check that algorithm is not restricted
-                if (!JAR_DISABLED_CHECK.permits(DIGEST_PRIMITIVE_SET,
-                        digestAlgname, null)) {
-                    throw new SignatureException("Digest check failed. " +
-                            "Disabled algorithm used: " + digestAlgname);
+                // check that digest algorithm is not restricted
+                try {
+                    JAR_DISABLED_CHECK.permits(digestAlgname, cparams);
+                } catch (CertPathValidatorException e) {
+                    throw new SignatureException(e.getMessage(), e);
                 }
 
                 MessageDigest md = MessageDigest.getInstance(digestAlgname);
@@ -385,17 +389,18 @@
             String algname = AlgorithmId.makeSigAlg(
                     digestAlgname, encryptionAlgname);
 
-            // check that algorithm is not restricted
-            if (!JAR_DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, algname, null)) {
-                throw new SignatureException("Signature check failed. " +
-                        "Disabled algorithm used: " + algname);
+            // check that jar signature algorithm is not restricted
+            try {
+                JAR_DISABLED_CHECK.permits(algname, cparams);
+            } catch (CertPathValidatorException e) {
+                throw new SignatureException(e.getMessage(), e);
             }
 
             X509Certificate cert = getCertificate(block);
-            PublicKey key = cert.getPublicKey();
             if (cert == null) {
                 return null;
             }
+            PublicKey key = cert.getPublicKey();
 
             // check if the public key is restricted
             if (!JAR_DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) {
--- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/AlgorithmChecker.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2017, 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.security.AlgorithmConstraints;
 import java.security.CryptoPrimitive;
 import java.security.Timestamp;
+import java.security.cert.CertPathValidator;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Date;
@@ -53,9 +54,10 @@
 import java.security.spec.DSAPublicKeySpec;
 
 import sun.security.util.AnchorCertificates;
-import sun.security.util.CertConstraintParameters;
+import sun.security.util.ConstraintsParameters;
 import sun.security.util.Debug;
 import sun.security.util.DisabledAlgorithmConstraints;
+import sun.security.validator.Validator;
 import sun.security.x509.X509CertImpl;
 import sun.security.x509.X509CRLImpl;
 import sun.security.x509.AlgorithmId;
@@ -79,6 +81,7 @@
     private final Date pkixdate;
     private PublicKey prevPubKey;
     private final Timestamp jarTimestamp;
+    private final String variant;
 
     private static final Set<CryptoPrimitive> SIGNATURE_PRIMITIVE_SET =
         Collections.unmodifiableSet(EnumSet.of(CryptoPrimitive.SIGNATURE));
@@ -109,64 +112,36 @@
      *
      * @param anchor the trust anchor selected to validate the target
      *     certificate
-     */
-    public AlgorithmChecker(TrustAnchor anchor) {
-        this(anchor, certPathDefaultConstraints, null);
-    }
-
-    /**
-     * Create a new {@code AlgorithmChecker} with the
-     * given {@code TrustAnchor} and {@code AlgorithmConstraints}.
-     *
-     * @param anchor the trust anchor selected to validate the target
-     *     certificate
-     * @param constraints the algorithm constraints (or null)
-     *
-     * @throws IllegalArgumentException if the {@code anchor} is null
+     * @param variant is the Validator variants of the operation. A null value
+     *                passed will set it to Validator.GENERIC.
      */
-    public AlgorithmChecker(TrustAnchor anchor,
-            AlgorithmConstraints constraints) {
-        this(anchor, constraints, null);
-    }
-
-    /**
-     * Create a new {@code AlgorithmChecker} with the
-     * given {@code AlgorithmConstraints}.
-     * <p>
-     * Note that this constructor will be used to check a certification
-     * path where the trust anchor is unknown, or a certificate list which may
-     * contain the trust anchor. This constructor is used by SunJSSE.
-     *
-     * @param constraints the algorithm constraints (or null)
-     */
-    public AlgorithmChecker(AlgorithmConstraints constraints) {
-        this.prevPubKey = null;
-        this.trustedPubKey = null;
-        this.constraints = constraints;
-        this.pkixdate = null;
-        this.jarTimestamp = null;
+    public AlgorithmChecker(TrustAnchor anchor, String variant) {
+        this(anchor, certPathDefaultConstraints, null, variant);
     }
 
     /**
      * Create a new {@code AlgorithmChecker} with the given
-     * {@code Timestamp}.
+     * {@code AlgorithmConstraints}, {@code Timestamp}, and/or {@code Variant}.
      * <p>
-     * Note that this constructor will be used to check a certification
-     * path for signed JAR files that are timestamped.
+     * Note that this constructor can initialize a variation of situations where
+     * the AlgorithmConstraints, Timestamp, or Variant maybe known.
      *
+     * @param constraints the algorithm constraints (or null)
      * @param jarTimestamp Timestamp passed for JAR timestamp constraint
      *                     checking. Set to null if not applicable.
+     * @param variant is the Validator variants of the operation. A null value
+     *                passed will set it to Validator.GENERIC.
      */
-    public AlgorithmChecker(Timestamp jarTimestamp) {
+    public AlgorithmChecker(AlgorithmConstraints constraints,
+            Timestamp jarTimestamp, String variant) {
         this.prevPubKey = null;
         this.trustedPubKey = null;
-        this.constraints = certPathDefaultConstraints;
-        if (jarTimestamp == null) {
-            throw new IllegalArgumentException(
-                    "Timestamp cannot be null");
-        }
-        this.pkixdate = jarTimestamp.getTimestamp();
+        this.constraints = (constraints == null ? certPathDefaultConstraints :
+                constraints);
+        this.pkixdate = (jarTimestamp != null ? jarTimestamp.getTimestamp() :
+                null);
         this.jarTimestamp = jarTimestamp;
+        this.variant = (variant == null ? Validator.VAR_GENERIC : variant);
     }
 
     /**
@@ -178,12 +153,13 @@
      * @param constraints the algorithm constraints (or null)
      * @param pkixdate Date the constraints are checked against. The value is
      *             either the PKIXParameter date or null for the current date.
+     * @param variant is the Validator variants of the operation. A null value
+     *                passed will set it to Validator.GENERIC.
      *
      * @throws IllegalArgumentException if the {@code anchor} is null
      */
     public AlgorithmChecker(TrustAnchor anchor,
-            AlgorithmConstraints constraints,
-            Date pkixdate) {
+            AlgorithmConstraints constraints, Date pkixdate, String variant) {
 
         if (anchor != null) {
             if (anchor.getTrustedCert() != null) {
@@ -207,6 +183,7 @@
         this.constraints = constraints;
         this.pkixdate = pkixdate;
         this.jarTimestamp = null;
+        this.variant = (variant == null ? Validator.VAR_GENERIC : variant);
     }
 
     /**
@@ -217,11 +194,13 @@
      *     certificate
      * @param pkixdate Date the constraints are checked against. The value is
      *             either the PKIXParameter date or null for the current date.
+     * @param variant is the Validator variants of the operation. A null value
+     *                passed will set it to Validator.GENERIC.
      *
      * @throws IllegalArgumentException if the {@code anchor} is null
      */
-    public AlgorithmChecker(TrustAnchor anchor, Date pkixdate) {
-        this(anchor, certPathDefaultConstraints, pkixdate);
+    public AlgorithmChecker(TrustAnchor anchor, Date pkixdate, String variant) {
+        this(anchor, certPathDefaultConstraints, pkixdate, variant);
     }
 
     // Check this 'cert' for restrictions in the AnchorCertificates
@@ -286,6 +265,28 @@
                 null, null, -1, PKIXReason.INVALID_KEY_USAGE);
         }
 
+        X509CertImpl x509Cert;
+        AlgorithmId algorithmId;
+        try {
+            x509Cert = X509CertImpl.toImpl((X509Certificate)cert);
+            algorithmId = (AlgorithmId)x509Cert.get(X509CertImpl.SIG_ALG);
+        } catch (CertificateException ce) {
+            throw new CertPathValidatorException(ce);
+        }
+
+        AlgorithmParameters currSigAlgParams = algorithmId.getParameters();
+        PublicKey currPubKey = cert.getPublicKey();
+        String currSigAlg = ((X509Certificate)cert).getSigAlgName();
+
+        // Check the signature algorithm and parameters against constraints.
+        if (!constraints.permits(SIGNATURE_PRIMITIVE_SET, currSigAlg,
+                currSigAlgParams)) {
+            throw new CertPathValidatorException(
+                    "Algorithm constraints check failed on signature " +
+                            "algorithm: " + currSigAlg, null, null, -1,
+                    BasicReason.ALGORITHM_CONSTRAINED);
+        }
+
         // Assume all key usage bits are set if key usage is not present
         Set<CryptoPrimitive> primitives = KU_PRIMITIVE_SET;
 
@@ -322,101 +323,74 @@
             }
         }
 
-        PublicKey currPubKey = cert.getPublicKey();
-
-        if (constraints instanceof DisabledAlgorithmConstraints) {
-            // Check against DisabledAlgorithmConstraints certpath constraints.
-            // permits() will throw exception on failure.
-            ((DisabledAlgorithmConstraints)constraints).permits(primitives,
-                new CertConstraintParameters((X509Certificate)cert,
-                        trustedMatch, pkixdate, jarTimestamp));
-            // If there is no previous key, set one and exit
-            if (prevPubKey == null) {
-                prevPubKey = currPubKey;
-                return;
-            }
-        }
+        ConstraintsParameters cp =
+                new ConstraintsParameters((X509Certificate)cert,
+                        trustedMatch, pkixdate, jarTimestamp, variant);
 
-        X509CertImpl x509Cert;
-        AlgorithmId algorithmId;
-        try {
-            x509Cert = X509CertImpl.toImpl((X509Certificate)cert);
-            algorithmId = (AlgorithmId)x509Cert.get(X509CertImpl.SIG_ALG);
-        } catch (CertificateException ce) {
-            throw new CertPathValidatorException(ce);
-        }
-
-        AlgorithmParameters currSigAlgParams = algorithmId.getParameters();
-        String currSigAlg = x509Cert.getSigAlgName();
+        // Check against local constraints if it is DisabledAlgorithmConstraints
+        if (constraints instanceof DisabledAlgorithmConstraints) {
+            ((DisabledAlgorithmConstraints)constraints).permits(currSigAlg, cp);
+            // DisabledAlgorithmsConstraints does not check primitives, so key
+            // additional key check.
 
-        // If 'constraints' is not of DisabledAlgorithmConstraints, check all
-        // everything individually
-        if (!(constraints instanceof DisabledAlgorithmConstraints)) {
-            // Check the current signature algorithm
-            if (!constraints.permits(
-                    SIGNATURE_PRIMITIVE_SET,
-                    currSigAlg, currSigAlgParams)) {
-                throw new CertPathValidatorException(
-                        "Algorithm constraints check failed on signature " +
-                                "algorithm: " + currSigAlg, null, null, -1,
-                        BasicReason.ALGORITHM_CONSTRAINED);
-            }
-
+        } else {
+            // Perform the default constraints checking anyway.
+            certPathDefaultConstraints.permits(currSigAlg, cp);
+            // Call locally set constraints to check key with primitives.
             if (!constraints.permits(primitives, currPubKey)) {
                 throw new CertPathValidatorException(
-                        "Algorithm constraints check failed on keysize: " +
-                                sun.security.util.KeyUtil.getKeySize(currPubKey),
+                        "Algorithm constraints check failed on key " +
+                                currPubKey.getAlgorithm() + " with size of " +
+                                sun.security.util.KeyUtil.getKeySize(currPubKey) +
+                                "bits",
                         null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
             }
         }
 
+        // If there is no previous key, set one and exit
+        if (prevPubKey == null) {
+            prevPubKey = currPubKey;
+            return;
+        }
+
         // Check with previous cert for signature algorithm and public key
-        if (prevPubKey != null) {
-            if (!constraints.permits(
-                    SIGNATURE_PRIMITIVE_SET,
-                    currSigAlg, prevPubKey, currSigAlgParams)) {
-                throw new CertPathValidatorException(
+        if (!constraints.permits(
+                SIGNATURE_PRIMITIVE_SET,
+                currSigAlg, prevPubKey, currSigAlgParams)) {
+            throw new CertPathValidatorException(
                     "Algorithm constraints check failed on " +
                             "signature algorithm: " + currSigAlg,
                     null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
+        }
+
+        // Inherit key parameters from previous key
+        if (PKIX.isDSAPublicKeyWithoutParams(currPubKey)) {
+            // Inherit DSA parameters from previous key
+            if (!(prevPubKey instanceof DSAPublicKey)) {
+                throw new CertPathValidatorException("Input key is not " +
+                        "of a appropriate type for inheriting parameters");
             }
 
-            // Inherit key parameters from previous key
-            if (PKIX.isDSAPublicKeyWithoutParams(currPubKey)) {
-                // Inherit DSA parameters from previous key
-                if (!(prevPubKey instanceof DSAPublicKey)) {
-                    throw new CertPathValidatorException("Input key is not " +
-                        "of a appropriate type for inheriting parameters");
-                }
-
-                DSAParams params = ((DSAPublicKey)prevPubKey).getParams();
-                if (params == null) {
-                    throw new CertPathValidatorException(
+            DSAParams params = ((DSAPublicKey)prevPubKey).getParams();
+            if (params == null) {
+                throw new CertPathValidatorException(
                         "Key parameters missing from public key.");
-                }
+            }
 
-                try {
-                    BigInteger y = ((DSAPublicKey)currPubKey).getY();
-                    KeyFactory kf = KeyFactory.getInstance("DSA");
-                    DSAPublicKeySpec ks = new DSAPublicKeySpec(y,
-                                                       params.getP(),
-                                                       params.getQ(),
-                                                       params.getG());
-                    currPubKey = kf.generatePublic(ks);
-                } catch (GeneralSecurityException e) {
-                    throw new CertPathValidatorException("Unable to generate " +
+            try {
+                BigInteger y = ((DSAPublicKey)currPubKey).getY();
+                KeyFactory kf = KeyFactory.getInstance("DSA");
+                DSAPublicKeySpec ks = new DSAPublicKeySpec(y, params.getP(),
+                        params.getQ(), params.getG());
+                currPubKey = kf.generatePublic(ks);
+            } catch (GeneralSecurityException e) {
+                throw new CertPathValidatorException("Unable to generate " +
                         "key with inherited parameters: " + e.getMessage(), e);
-                }
             }
         }
 
         // reset the previous public key
         prevPubKey = currPubKey;
-
-        // check the extended key usage, ignore the check now
-        // List<String> extendedKeyUsages = x509Cert.getExtendedKeyUsage();
-
-        // DO NOT remove any unresolved critical extensions
     }
 
     /**
@@ -456,8 +430,10 @@
      *
      * @param key the public key to verify the CRL signature
      * @param crl the target CRL
+     * @param variant is the Validator variants of the operation. A null value
+     *                passed will set it to Validator.GENERIC.
      */
-    static void check(PublicKey key, X509CRL crl)
+    static void check(PublicKey key, X509CRL crl, String variant)
                         throws CertPathValidatorException {
 
         X509CRLImpl x509CRLImpl = null;
@@ -468,7 +444,7 @@
         }
 
         AlgorithmId algorithmId = x509CRLImpl.getSigAlgId();
-        check(key, algorithmId);
+        check(key, algorithmId, variant);
     }
 
     /**
@@ -476,20 +452,16 @@
      *
      * @param key the public key to verify the CRL signature
      * @param algorithmId signature algorithm Algorithm ID
+     * @param variant is the Validator variants of the operation. A null value
+     *                passed will set it to Validator.GENERIC.
      */
-    static void check(PublicKey key, AlgorithmId algorithmId)
+    static void check(PublicKey key, AlgorithmId algorithmId, String variant)
                         throws CertPathValidatorException {
         String sigAlgName = algorithmId.getName();
         AlgorithmParameters sigAlgParams = algorithmId.getParameters();
 
-        if (!certPathDefaultConstraints.permits(
-                SIGNATURE_PRIMITIVE_SET, sigAlgName, key, sigAlgParams)) {
-            throw new CertPathValidatorException(
-                "Algorithm constraints check failed on signature algorithm: " +
-                sigAlgName + " is disabled",
-                null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
-        }
+        certPathDefaultConstraints.permits(new ConstraintsParameters(
+                sigAlgName, sigAlgParams, key, variant));
     }
-
 }
 
--- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/DistributionPointFetcher.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, 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.util.*;
 
 import sun.security.util.Debug;
+import sun.security.validator.Validator;
 import static sun.security.x509.PKIXExtensions.*;
 import sun.security.x509.*;
 
@@ -66,6 +67,20 @@
      * an X509CRLSelector with certificateChecking set.
      */
     public static Collection<X509CRL> getCRLs(X509CRLSelector selector,
+            boolean signFlag, PublicKey prevKey, String provider,
+            List<CertStore> certStores, boolean[] reasonsMask,
+            Set<TrustAnchor> trustAnchors, Date validity, String variant)
+            throws CertStoreException
+    {
+        return getCRLs(selector, signFlag, prevKey, null, provider, certStores,
+                reasonsMask, trustAnchors, validity, variant);
+    }
+    /**
+     * Return the X509CRLs matching this selector. The selector must be
+     * an X509CRLSelector with certificateChecking set.
+     */
+    // Called by com.sun.deploy.security.RevocationChecker
+    public static Collection<X509CRL> getCRLs(X509CRLSelector selector,
                                               boolean signFlag,
                                               PublicKey prevKey,
                                               String provider,
@@ -76,7 +91,7 @@
         throws CertStoreException
     {
         return getCRLs(selector, signFlag, prevKey, null, provider, certStores,
-                       reasonsMask, trustAnchors, validity);
+                reasonsMask, trustAnchors, validity, Validator.VAR_GENERIC);
     }
 
     /**
@@ -91,7 +106,8 @@
                                               List<CertStore> certStores,
                                               boolean[] reasonsMask,
                                               Set<TrustAnchor> trustAnchors,
-                                              Date validity)
+                                              Date validity,
+                                              String variant)
         throws CertStoreException
     {
         X509Certificate cert = selector.getCertificateChecking();
@@ -120,7 +136,7 @@
                 DistributionPoint point = t.next();
                 Collection<X509CRL> crls = getCRLs(selector, certImpl,
                     point, reasonsMask, signFlag, prevKey, prevCert, provider,
-                    certStores, trustAnchors, validity);
+                    certStores, trustAnchors, validity, variant);
                 results.addAll(crls);
             }
             if (debug != null) {
@@ -145,7 +161,7 @@
         X509CertImpl certImpl, DistributionPoint point, boolean[] reasonsMask,
         boolean signFlag, PublicKey prevKey, X509Certificate prevCert,
         String provider, List<CertStore> certStores,
-        Set<TrustAnchor> trustAnchors, Date validity)
+        Set<TrustAnchor> trustAnchors, Date validity, String variant)
             throws CertStoreException {
 
         // check for full name
@@ -208,7 +224,7 @@
                 selector.setIssuerNames(null);
                 if (selector.match(crl) && verifyCRL(certImpl, point, crl,
                         reasonsMask, signFlag, prevKey, prevCert, provider,
-                        trustAnchors, certStores, validity)) {
+                        trustAnchors, certStores, validity, variant)) {
                     crls.add(crl);
                 }
             } catch (IOException | CRLException e) {
@@ -316,7 +332,7 @@
         X509CRL crl, boolean[] reasonsMask, boolean signFlag,
         PublicKey prevKey, X509Certificate prevCert, String provider,
         Set<TrustAnchor> trustAnchors, List<CertStore> certStores,
-        Date validity) throws CRLException, IOException {
+        Date validity, String variant) throws CRLException, IOException {
 
         if (debug != null) {
             debug.println("DistributionPointFetcher.verifyCRL: " +
@@ -663,7 +679,7 @@
 
         // check the crl signature algorithm
         try {
-            AlgorithmChecker.check(prevKey, crl);
+            AlgorithmChecker.check(prevKey, crl, variant);
         } catch (CertPathValidatorException cpve) {
             if (debug != null) {
                 debug.println("CRL signature algorithm check failed: " + cpve);
--- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/OCSP.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/OCSP.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 2017, 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
@@ -45,6 +45,7 @@
 
 import sun.security.action.GetIntegerAction;
 import sun.security.util.Debug;
+import sun.security.validator.Validator;
 import sun.security.x509.AccessDescription;
 import sun.security.x509.AuthorityInfoAccessExtension;
 import sun.security.x509.GeneralName;
@@ -94,42 +95,6 @@
 
     private OCSP() {}
 
-    /**
-     * Obtains the revocation status of a certificate using OCSP using the most
-     * common defaults. The OCSP responder URI is retrieved from the
-     * certificate's AIA extension. The OCSP responder certificate is assumed
-     * to be the issuer's certificate (or issued by the issuer CA).
-     *
-     * @param cert the certificate to be checked
-     * @param issuerCert the issuer certificate
-     * @return the RevocationStatus
-     * @throws IOException if there is an exception connecting to or
-     *    communicating with the OCSP responder
-     * @throws CertPathValidatorException if an exception occurs while
-     *    encoding the OCSP Request or validating the OCSP Response
-     */
-    public static RevocationStatus check(X509Certificate cert,
-                                         X509Certificate issuerCert)
-        throws IOException, CertPathValidatorException {
-        CertId certId = null;
-        URI responderURI = null;
-        try {
-            X509CertImpl certImpl = X509CertImpl.toImpl(cert);
-            responderURI = getResponderURI(certImpl);
-            if (responderURI == null) {
-                throw new CertPathValidatorException
-                    ("No OCSP Responder URI in certificate");
-            }
-            certId = new CertId(issuerCert, certImpl.getSerialNumberObject());
-        } catch (CertificateException | IOException e) {
-            throw new CertPathValidatorException
-                ("Exception while encoding OCSPRequest", e);
-        }
-        OCSPResponse ocspResponse = check(Collections.singletonList(certId),
-            responderURI, new OCSPResponse.IssuerInfo(issuerCert), null, null,
-            Collections.<Extension>emptyList());
-        return (RevocationStatus)ocspResponse.getSingleResponse(certId);
-    }
 
     /**
      * Obtains the revocation status of a certificate using OCSP.
@@ -146,6 +111,8 @@
      * @throws CertPathValidatorException if an exception occurs while
      *    encoding the OCSP Request or validating the OCSP Response
      */
+
+    // Called by com.sun.deploy.security.TrustDecider
     public static RevocationStatus check(X509Certificate cert,
                                          X509Certificate issuerCert,
                                          URI responderURI,
@@ -154,27 +121,27 @@
         throws IOException, CertPathValidatorException
     {
         return check(cert, issuerCert, responderURI, responderCert, date,
-                     Collections.<Extension>emptyList());
+                     Collections.<Extension>emptyList(), Validator.VAR_GENERIC);
     }
 
-    // Called by com.sun.deploy.security.TrustDecider
+
     public static RevocationStatus check(X509Certificate cert,
-                                         X509Certificate issuerCert,
-                                         URI responderURI,
-                                         X509Certificate responderCert,
-                                         Date date, List<Extension> extensions)
+            X509Certificate issuerCert, URI responderURI,
+            X509Certificate responderCert, Date date, List<Extension> extensions,
+            String variant)
         throws IOException, CertPathValidatorException
     {
-        return check(cert, responderURI, null, issuerCert, responderCert, date, extensions);
+        return check(cert, responderURI, null, issuerCert, responderCert, date,
+                extensions, variant);
     }
 
     public static RevocationStatus check(X509Certificate cert,
             URI responderURI, TrustAnchor anchor, X509Certificate issuerCert,
             X509Certificate responderCert, Date date,
-            List<Extension> extensions)
+            List<Extension> extensions, String variant)
             throws IOException, CertPathValidatorException
     {
-        CertId certId = null;
+        CertId certId;
         try {
             X509CertImpl certImpl = X509CertImpl.toImpl(cert);
             certId = new CertId(issuerCert, certImpl.getSerialNumberObject());
@@ -184,7 +151,7 @@
         }
         OCSPResponse ocspResponse = check(Collections.singletonList(certId),
                 responderURI, new OCSPResponse.IssuerInfo(anchor, issuerCert),
-                responderCert, date, extensions);
+                responderCert, date, extensions, variant);
         return (RevocationStatus) ocspResponse.getSingleResponse(certId);
     }
 
@@ -206,10 +173,10 @@
      * @throws CertPathValidatorException if an exception occurs while
      *    encoding the OCSP Request or validating the OCSP Response
      */
-        static OCSPResponse check(List<CertId> certIds, URI responderURI,
+    static OCSPResponse check(List<CertId> certIds, URI responderURI,
                               OCSPResponse.IssuerInfo issuerInfo,
                               X509Certificate responderCert, Date date,
-                              List<Extension> extensions)
+                              List<Extension> extensions, String variant)
         throws IOException, CertPathValidatorException
     {
         byte[] nonce = null;
@@ -226,7 +193,7 @@
 
             // verify the response
             ocspResponse.verify(certIds, issuerInfo, responderCert, date,
-                    nonce);
+                    nonce, variant);
         } catch (IOException ioe) {
             throw new CertPathValidatorException(
                 "Unable to determine revocation status due to network error",
--- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/OCSPResponse.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/OCSPResponse.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -41,7 +41,6 @@
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
-import java.util.Objects;
 import java.util.Set;
 import javax.security.auth.x500.X500Principal;
 
@@ -375,7 +374,8 @@
     }
 
     void verify(List<CertId> certIds, IssuerInfo issuerInfo,
-            X509Certificate responderCert, Date date, byte[] nonce)
+            X509Certificate responderCert, Date date, byte[] nonce,
+            String variant)
         throws CertPathValidatorException
     {
         switch (responseStatus) {
@@ -508,7 +508,8 @@
                 // Check algorithm constraints specified in security property
                 // "jdk.certpath.disabledAlgorithms".
                 AlgorithmChecker algChecker =
-                        new AlgorithmChecker(issuerInfo.getAnchor(), date);
+                        new AlgorithmChecker(issuerInfo.getAnchor(), date,
+                                variant);
                 algChecker.init(false);
                 algChecker.check(signerCert, Collections.<String>emptySet());
 
@@ -568,7 +569,7 @@
         if (signerCert != null) {
             // Check algorithm constraints specified in security property
             // "jdk.certpath.disabledAlgorithms".
-            AlgorithmChecker.check(signerCert.getPublicKey(), sigAlgId);
+            AlgorithmChecker.check(signerCert.getPublicKey(), sigAlgId, variant);
 
             if (!verifySignature(signerCert)) {
                 throw new CertPathValidatorException(
--- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/PKIX.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/PKIX.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -87,6 +87,7 @@
         private Set<TrustAnchor> anchors;
         private List<X509Certificate> certs;
         private Timestamp timestamp;
+        private String variant;
 
         ValidatorParams(CertPath cp, PKIXParameters params)
             throws InvalidAlgorithmParameterException
@@ -102,8 +103,9 @@
         ValidatorParams(PKIXParameters params)
             throws InvalidAlgorithmParameterException
         {
-            if (params instanceof PKIXTimestampParameters) {
-                timestamp = ((PKIXTimestampParameters) params).getTimestamp();
+            if (params instanceof PKIXExtendedParameters) {
+                timestamp = ((PKIXExtendedParameters) params).getTimestamp();
+                variant = ((PKIXExtendedParameters) params).getVariant();
             }
 
             this.anchors = params.getTrustAnchors();
@@ -199,6 +201,10 @@
         Timestamp timestamp() {
             return timestamp;
         }
+
+        String variant() {
+            return variant;
+        }
     }
 
     static class BuilderParams extends ValidatorParams {
--- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/PKIXCertPathValidator.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/PKIXCertPathValidator.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -173,9 +173,10 @@
         // add standard checkers that we will be using
         certPathCheckers.add(untrustedChecker);
         if (params.timestamp() == null) {
-            certPathCheckers.add(new AlgorithmChecker(anchor, params.date()));
+            certPathCheckers.add(new AlgorithmChecker(anchor, params.date(), null));
         } else {
-            certPathCheckers.add(new AlgorithmChecker(params.timestamp()));
+            certPathCheckers.add(new AlgorithmChecker(null,
+                    params.timestamp(), params.variant()));
         }
         certPathCheckers.add(new KeyChecker(certPathLen,
                                             params.targetCertConstraints()));
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/PKIXExtendedParameters.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,226 @@
+/*
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+
+package sun.security.provider.certpath;
+
+import java.security.InvalidAlgorithmParameterException;
+import java.security.Timestamp;
+import java.security.cert.CertSelector;
+import java.security.cert.CertStore;
+import java.security.cert.PKIXBuilderParameters;
+import java.security.cert.PKIXCertPathChecker;
+import java.security.cert.TrustAnchor;
+import java.util.Date;
+import java.util.List;
+import java.util.Set;
+
+/**
+ * This class is a wrapper for PKIXBuilderParameters so that a Timestamp object
+ * and a string for the variant type, can be passed when doing certpath
+ * checking.
+ */
+
+public class PKIXExtendedParameters extends PKIXBuilderParameters {
+
+    private final PKIXBuilderParameters p;
+    private Timestamp jarTimestamp;
+    private final String variant;
+
+    public PKIXExtendedParameters(PKIXBuilderParameters params,
+            Timestamp timestamp, String variant)
+            throws InvalidAlgorithmParameterException {
+        super(params.getTrustAnchors(), null);
+        p = params;
+        jarTimestamp = timestamp;
+        this.variant = variant;
+    }
+
+    public Timestamp getTimestamp() {
+        return jarTimestamp;
+    }
+    public void setTimestamp(Timestamp t) {
+        jarTimestamp = t;
+    }
+
+    public String getVariant() {
+        return variant;
+    }
+
+    @Override
+    public void setDate(Date d) {
+        p.setDate(d);
+    }
+
+    @Override
+    public void addCertPathChecker(PKIXCertPathChecker c) {
+        p.addCertPathChecker(c);
+    }
+
+    @Override
+    public void setMaxPathLength(int maxPathLength) {
+        p.setMaxPathLength(maxPathLength);
+    }
+
+    @Override
+    public int getMaxPathLength() {
+        return p.getMaxPathLength();
+    }
+
+    @Override
+    public String toString() {
+        return p.toString();
+    }
+
+    @Override
+    public Set<TrustAnchor> getTrustAnchors() {
+        return p.getTrustAnchors();
+    }
+
+    @Override
+    public void setTrustAnchors(Set<TrustAnchor> trustAnchors)
+            throws InvalidAlgorithmParameterException {
+        // To avoid problems with PKIXBuilderParameter's constructors
+        if (p == null) {
+            return;
+        }
+        p.setTrustAnchors(trustAnchors);
+    }
+
+    @Override
+    public Set<String> getInitialPolicies() {
+        return p.getInitialPolicies();
+    }
+
+    @Override
+    public void setInitialPolicies(Set<String> initialPolicies) {
+        p.setInitialPolicies(initialPolicies);
+    }
+
+    @Override
+    public void setCertStores(List<CertStore> stores) {
+        p.setCertStores(stores);
+    }
+
+    @Override
+    public void addCertStore(CertStore store) {
+        p.addCertStore(store);
+    }
+
+    @Override
+    public List<CertStore> getCertStores() {
+        return p.getCertStores();
+    }
+
+    @Override
+    public void setRevocationEnabled(boolean val) {
+        p.setRevocationEnabled(val);
+    }
+
+    @Override
+    public boolean isRevocationEnabled() {
+        return p.isRevocationEnabled();
+    }
+
+    @Override
+    public void setExplicitPolicyRequired(boolean val) {
+        p.setExplicitPolicyRequired(val);
+    }
+
+    @Override
+    public boolean isExplicitPolicyRequired() {
+        return p.isExplicitPolicyRequired();
+    }
+
+    @Override
+    public void setPolicyMappingInhibited(boolean val) {
+        p.setPolicyMappingInhibited(val);
+    }
+
+    @Override
+    public boolean isPolicyMappingInhibited() {
+        return p.isPolicyMappingInhibited();
+    }
+
+    @Override
+    public void setAnyPolicyInhibited(boolean val) {
+        p.setAnyPolicyInhibited(val);
+    }
+
+    @Override
+    public boolean isAnyPolicyInhibited() {
+        return p.isAnyPolicyInhibited();
+    }
+
+    @Override
+    public void setPolicyQualifiersRejected(boolean qualifiersRejected) {
+        p.setPolicyQualifiersRejected(qualifiersRejected);
+    }
+
+    @Override
+    public boolean getPolicyQualifiersRejected() {
+        return p.getPolicyQualifiersRejected();
+    }
+
+    @Override
+    public Date getDate() {
+        return p.getDate();
+    }
+
+    @Override
+    public void setCertPathCheckers(List<PKIXCertPathChecker> checkers) {
+        p.setCertPathCheckers(checkers);
+    }
+
+    @Override
+    public List<PKIXCertPathChecker> getCertPathCheckers() {
+        return p.getCertPathCheckers();
+    }
+
+    @Override
+    public String getSigProvider() {
+        return p.getSigProvider();
+    }
+
+    @Override
+    public void setSigProvider(String sigProvider) {
+        p.setSigProvider(sigProvider);
+    }
+
+    @Override
+    public CertSelector getTargetCertConstraints() {
+        return p.getTargetCertConstraints();
+    }
+
+    @Override
+    public void setTargetCertConstraints(CertSelector selector) {
+        // To avoid problems with PKIXBuilderParameter's constructors
+        if (p == null) {
+            return;
+        }
+        p.setTargetCertConstraints(selector);
+    }
+
+}
--- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/PKIXTimestampParameters.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,218 +0,0 @@
-/*
- * 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.
- */
-
-
-package sun.security.provider.certpath;
-
-import java.security.InvalidAlgorithmParameterException;
-import java.security.Timestamp;
-import java.security.cert.CertSelector;
-import java.security.cert.CertStore;
-import java.security.cert.PKIXBuilderParameters;
-import java.security.cert.PKIXCertPathChecker;
-import java.security.cert.TrustAnchor;
-import java.util.Date;
-import java.util.List;
-import java.util.Set;
-
-/**
- * This class is a wrapper for PKIXBuilderParameters so that a Timestamp object
- * can be passed alone when PKIXCertPath is checking signed jar files.
- */
-
-public class PKIXTimestampParameters extends PKIXBuilderParameters {
-
-    private final PKIXBuilderParameters p;
-    private Timestamp jarTimestamp;
-
-    public PKIXTimestampParameters(PKIXBuilderParameters params,
-            Timestamp timestamp) throws InvalidAlgorithmParameterException {
-        super(params.getTrustAnchors(), null);
-        p = params;
-        jarTimestamp = timestamp;
-    }
-
-    public Timestamp getTimestamp() {
-        return jarTimestamp;
-    }
-    public void setTimestamp(Timestamp t) {
-        jarTimestamp = t;
-    }
-
-    @Override
-    public void setDate(Date d) {
-        p.setDate(d);
-    }
-
-    @Override
-    public void addCertPathChecker(PKIXCertPathChecker c) {
-        p.addCertPathChecker(c);
-    }
-
-    @Override
-    public void setMaxPathLength(int maxPathLength) {
-        p.setMaxPathLength(maxPathLength);
-    }
-
-    @Override
-    public int getMaxPathLength() {
-        return p.getMaxPathLength();
-    }
-
-    @Override
-    public String toString() {
-        return p.toString();
-    }
-
-    @Override
-    public Set<TrustAnchor> getTrustAnchors() {
-        return p.getTrustAnchors();
-    }
-
-    @Override
-    public void setTrustAnchors(Set<TrustAnchor> trustAnchors)
-            throws InvalidAlgorithmParameterException {
-        // To avoid problems with PKIXBuilderParameter's constructors
-        if (p == null) {
-            return;
-        }
-        p.setTrustAnchors(trustAnchors);
-    }
-
-    @Override
-    public Set<String> getInitialPolicies() {
-        return p.getInitialPolicies();
-    }
-
-    @Override
-    public void setInitialPolicies(Set<String> initialPolicies) {
-        p.setInitialPolicies(initialPolicies);
-    }
-
-    @Override
-    public void setCertStores(List<CertStore> stores) {
-        p.setCertStores(stores);
-    }
-
-    @Override
-    public void addCertStore(CertStore store) {
-        p.addCertStore(store);
-    }
-
-    @Override
-    public List<CertStore> getCertStores() {
-        return p.getCertStores();
-    }
-
-    @Override
-    public void setRevocationEnabled(boolean val) {
-        p.setRevocationEnabled(val);
-    }
-
-    @Override
-    public boolean isRevocationEnabled() {
-        return p.isRevocationEnabled();
-    }
-
-    @Override
-    public void setExplicitPolicyRequired(boolean val) {
-        p.setExplicitPolicyRequired(val);
-    }
-
-    @Override
-    public boolean isExplicitPolicyRequired() {
-        return p.isExplicitPolicyRequired();
-    }
-
-    @Override
-    public void setPolicyMappingInhibited(boolean val) {
-        p.setPolicyMappingInhibited(val);
-    }
-
-    @Override
-    public boolean isPolicyMappingInhibited() {
-        return p.isPolicyMappingInhibited();
-    }
-
-    @Override
-    public void setAnyPolicyInhibited(boolean val) {
-        p.setAnyPolicyInhibited(val);
-    }
-
-    @Override
-    public boolean isAnyPolicyInhibited() {
-        return p.isAnyPolicyInhibited();
-    }
-
-    @Override
-    public void setPolicyQualifiersRejected(boolean qualifiersRejected) {
-        p.setPolicyQualifiersRejected(qualifiersRejected);
-    }
-
-    @Override
-    public boolean getPolicyQualifiersRejected() {
-        return p.getPolicyQualifiersRejected();
-    }
-
-    @Override
-    public Date getDate() {
-        return p.getDate();
-    }
-
-    @Override
-    public void setCertPathCheckers(List<PKIXCertPathChecker> checkers) {
-        p.setCertPathCheckers(checkers);
-    }
-
-    @Override
-    public List<PKIXCertPathChecker> getCertPathCheckers() {
-        return p.getCertPathCheckers();
-    }
-
-    @Override
-    public String getSigProvider() {
-        return p.getSigProvider();
-    }
-
-    @Override
-    public void setSigProvider(String sigProvider) {
-        p.setSigProvider(sigProvider);
-    }
-
-    @Override
-    public CertSelector getTargetCertConstraints() {
-        return p.getTargetCertConstraints();
-    }
-
-    @Override
-    public void setTargetCertConstraints(CertSelector selector) {
-        // To avoid problems with PKIXBuilderParameter's constructors
-        if (p == null) {
-            return;
-        }
-        p.setTargetCertConstraints(selector);
-    }
-
-}
--- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/RevocationChecker.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -579,7 +579,7 @@
                     approvedCRLs.addAll(DistributionPointFetcher.getCRLs(
                                         sel, signFlag, prevKey, prevCert,
                                         params.sigProvider(), certStores,
-                                        reasonsMask, anchors, null));
+                                        reasonsMask, anchors, null, params.variant()));
                 }
             } catch (CertStoreException e) {
                 if (e instanceof CertStoreTypeException) {
@@ -727,7 +727,7 @@
                     }
                 }
                 response.verify(Collections.singletonList(certId), issuerInfo,
-                        responderCert, params.date(), nonce);
+                        responderCert, params.date(), nonce, params.variant());
 
             } else {
                 URI responderURI = (this.responderURI != null)
@@ -741,7 +741,7 @@
 
                 response = OCSP.check(Collections.singletonList(certId),
                         responderURI, issuerInfo, responderCert, null,
-                        ocspExtensions);
+                        ocspExtensions, params.variant());
             }
         } catch (IOException e) {
             throw new CertPathValidatorException(
@@ -853,7 +853,7 @@
                     if (DistributionPointFetcher.verifyCRL(
                             certImpl, point, crl, reasonsMask, signFlag,
                             prevKey, null, params.sigProvider(), anchors,
-                            certStores, params.date()))
+                            certStores, params.date(), params.variant()))
                     {
                         results.add(crl);
                     }
--- a/jdk/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/provider/certpath/SunCertPathBuilder.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 2017, 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
@@ -344,7 +344,7 @@
 
                 // add the algorithm checker
                 checkers.add(new AlgorithmChecker(builder.trustAnchor,
-                        buildParams.date()));
+                        buildParams.date(), null));
 
                 BasicChecker basicChecker = null;
                 if (nextState.keyParamsNeeded()) {
--- a/jdk/src/java.base/share/classes/sun/security/ssl/EllipticCurvesExtension.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/ssl/EllipticCurvesExtension.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2017, 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
@@ -43,6 +43,9 @@
 
 final class EllipticCurvesExtension extends HelloExtension {
 
+    /* Class and subclass dynamic debugging support */
+    private static final Debug debug = Debug.getInstance("ssl");
+
     private static final int ARBITRARY_PRIME = 0xff01;
     private static final int ARBITRARY_CHAR2 = 0xff02;
 
@@ -159,6 +162,11 @@
                     }   // ignore unknown curves
                 }
             }
+            if (idList.isEmpty() && JsseJce.isEcAvailable()) {
+                throw new IllegalArgumentException(
+                    "System property jdk.tls.namedGroups(" + property + ") " +
+                    "contains no supported elliptic curves");
+            }
         } else {        // default curves
             int[] ids;
             if (requireFips) {
@@ -183,16 +191,17 @@
             }
         }
 
-        if (idList.isEmpty()) {
-            throw new IllegalArgumentException(
-                "System property jdk.tls.namedGroups(" + property + ") " +
-                "contains no supported elliptic curves");
-        } else {
-            supportedCurveIds = new int[idList.size()];
-            int i = 0;
-            for (Integer id : idList) {
-                supportedCurveIds[i++] = id;
-            }
+        if (debug != null && idList.isEmpty()) {
+            Debug.log(
+                "Initialized [jdk.tls.namedGroups|default] list contains " +
+                "no available elliptic curves. " +
+                (property != null ? "(" + property + ")" : "[Default]"));
+        }
+
+        supportedCurveIds = new int[idList.size()];
+        int i = 0;
+        for (Integer id : idList) {
+            supportedCurveIds[i++] = id;
         }
     }
 
--- a/jdk/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/ssl/SSLContextImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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 sun.security.provider.certpath.AlgorithmChecker;
 import sun.security.action.GetPropertyAction;
+import sun.security.validator.Validator;
 
 public abstract class SSLContextImpl extends SSLContextSpi {
 
@@ -1436,7 +1437,7 @@
                 constraints = new SSLAlgorithmConstraints(sslSocket, true);
             }
 
-            checkAlgorithmConstraints(chain, constraints);
+            checkAlgorithmConstraints(chain, constraints, isClient);
         }
     }
 
@@ -1478,12 +1479,12 @@
                 constraints = new SSLAlgorithmConstraints(engine, true);
             }
 
-            checkAlgorithmConstraints(chain, constraints);
+            checkAlgorithmConstraints(chain, constraints, isClient);
         }
     }
 
     private void checkAlgorithmConstraints(X509Certificate[] chain,
-            AlgorithmConstraints constraints) throws CertificateException {
+            AlgorithmConstraints constraints, boolean isClient) throws CertificateException {
 
         try {
             // Does the certificate chain end with a trusted certificate?
@@ -1501,7 +1502,9 @@
 
             // A forward checker, need to check from trust to target
             if (checkedLength >= 0) {
-                AlgorithmChecker checker = new AlgorithmChecker(constraints);
+                AlgorithmChecker checker =
+                        new AlgorithmChecker(constraints, null,
+                                (isClient ? Validator.VAR_TLS_CLIENT : Validator.VAR_TLS_SERVER));
                 checker.init(false);
                 for (int i = checkedLength; i >= 0; i--) {
                     Certificate cert = chain[i];
--- a/jdk/src/java.base/share/classes/sun/security/ssl/X509KeyManagerImpl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/ssl/X509KeyManagerImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -39,6 +39,7 @@
 import javax.net.ssl.*;
 
 import sun.security.provider.certpath.AlgorithmChecker;
+import sun.security.validator.Validator;
 
 /**
  * The new X509 key manager implementation. The main differences to the
@@ -661,6 +662,15 @@
 
             return CheckResult.OK;
         }
+
+        public String getValidator() {
+            if (this == CLIENT) {
+                return Validator.VAR_TLS_CLIENT;
+            } else if (this == SERVER) {
+                return Validator.VAR_TLS_SERVER;
+            }
+            return Validator.VAR_GENERIC;
+        }
     }
 
     // enum for the result of the extension check
@@ -774,7 +784,8 @@
 
             // check the algorithm constraints
             if (constraints != null &&
-                    !conformsToAlgorithmConstraints(constraints, chain)) {
+                    !conformsToAlgorithmConstraints(constraints, chain,
+                            checkType.getValidator())) {
 
                 if (useDebug) {
                     debug.println("Ignoring alias " + alias +
@@ -811,9 +822,10 @@
     }
 
     private static boolean conformsToAlgorithmConstraints(
-            AlgorithmConstraints constraints, Certificate[] chain) {
+            AlgorithmConstraints constraints, Certificate[] chain,
+            String variant) {
 
-        AlgorithmChecker checker = new AlgorithmChecker(constraints);
+        AlgorithmChecker checker = new AlgorithmChecker(constraints, null, variant);
         try {
             checker.init(false);
         } catch (CertPathValidatorException cpve) {
--- a/jdk/src/java.base/share/classes/sun/security/util/CertConstraintParameters.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,76 +0,0 @@
-/*
- * 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.
- */
-
-package sun.security.util;
-
-import java.security.Timestamp;
-import java.security.cert.X509Certificate;
-import java.util.Date;
-
-/**
- * This class is a wrapper for keeping state and passing objects between PKIX,
- * AlgorithmChecker, and DisabledAlgorithmConstraints.
- */
-public class CertConstraintParameters {
-    // A certificate being passed to check against constraints.
-    private final X509Certificate cert;
-    // This is true if the trust anchor in the certificate chain matches a cert
-    // in AnchorCertificates
-    private final boolean trustedMatch;
-    // PKIXParameter date
-    private final Date pkixDate;
-    // Timestamp of the signed JAR file
-    private final Timestamp jarTimestamp;
-
-    public CertConstraintParameters(X509Certificate c, boolean match,
-            Date pkixdate, Timestamp jarTime) {
-        cert = c;
-        trustedMatch = match;
-        pkixDate = pkixdate;
-        jarTimestamp = jarTime;
-    }
-
-    public CertConstraintParameters(X509Certificate c) {
-        this(c, false, null, null);
-    }
-
-    // Returns if the trust anchor has a match if anchor checking is enabled.
-    public boolean isTrustedMatch() {
-        return trustedMatch;
-    }
-
-    public X509Certificate getCertificate() {
-        return cert;
-    }
-
-    public Date getPKIXParamDate() {
-        return pkixDate;
-    }
-
-    public Timestamp getJARTimestamp() {
-        return jarTimestamp;
-    }
-
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/util/ConstraintsParameters.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,135 @@
+/*
+ * Copyright (c) 2016, 2017 Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.security.util;
+
+import sun.security.validator.Validator;
+
+import java.security.AlgorithmParameters;
+import java.security.Key;
+import java.security.Timestamp;
+import java.security.cert.X509Certificate;
+import java.util.Date;
+
+/**
+ * This class contains parameters for checking against constraints that extend
+ * past the publicly available parameters in java.security.AlgorithmConstraints.
+
+ * This is currently on passed between  between PKIX, AlgorithmChecker,
+ * and DisabledAlgorithmConstraints.
+ */
+public class ConstraintsParameters {
+    /*
+     * The below 3 values are used the same as the permit() methods
+     * published in java.security.AlgorithmConstraints.
+     */
+    // Algorithm string to be checked against constraints
+    private final String algorithm;
+    // AlgorithmParameters to the algorithm being checked
+    private final AlgorithmParameters algParams;
+    // Public Key being checked against constraints
+    private final Key publicKey;
+
+    /*
+     * New values that are checked against constraints that the current public
+     * API does not support.
+     */
+    // A certificate being passed to check against constraints.
+    private final X509Certificate cert;
+    // This is true if the trust anchor in the certificate chain matches a cert
+    // in AnchorCertificates
+    private final boolean trustedMatch;
+    // PKIXParameter date
+    private final Date pkixDate;
+    // Timestamp of the signed JAR file
+    private final Timestamp jarTimestamp;
+    private final String variant;
+
+    public ConstraintsParameters(X509Certificate c, boolean match,
+            Date pkixdate, Timestamp jarTime, String variant) {
+        cert = c;
+        trustedMatch = match;
+        pkixDate = pkixdate;
+        jarTimestamp = jarTime;
+        this.variant = (variant == null ? Validator.VAR_GENERIC : variant);
+        algorithm = null;
+        algParams = null;
+        publicKey = null;
+    }
+
+    public ConstraintsParameters(String algorithm, AlgorithmParameters params,
+            Key key, String variant) {
+        this.algorithm = algorithm;
+        algParams = params;
+        this.publicKey = key;
+        cert = null;
+        trustedMatch = false;
+        pkixDate = null;
+        jarTimestamp = null;
+        this.variant = (variant == null ? Validator.VAR_GENERIC : variant);
+    }
+
+
+    public ConstraintsParameters(X509Certificate c) {
+        this(c, false, null, null,
+                Validator.VAR_GENERIC);
+    }
+
+    public ConstraintsParameters(Timestamp jarTime) {
+        this(null, false, null, jarTime, Validator.VAR_GENERIC);
+    }
+
+    public String getAlgorithm() {
+        return algorithm;
+    }
+
+    public AlgorithmParameters getAlgParams() {
+        return algParams;
+    }
+
+    public Key getPublicKey() {
+        return publicKey;
+    }
+    // Returns if the trust anchor has a match if anchor checking is enabled.
+    public boolean isTrustedMatch() {
+        return trustedMatch;
+    }
+
+    public X509Certificate getCertificate() {
+        return cert;
+    }
+
+    public Date getPKIXParamDate() {
+        return pkixDate;
+    }
+
+    public Timestamp getJARTimestamp() {
+        return jarTimestamp;
+    }
+
+    public String getVariant() {
+        return variant;
+    }
+}
--- a/jdk/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/util/DisabledAlgorithmConstraints.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 2017, 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,8 @@
 
 package sun.security.util;
 
+import sun.security.validator.Validator;
+
 import java.security.CryptoPrimitive;
 import java.security.AlgorithmParameters;
 import java.security.Key;
@@ -32,10 +34,12 @@
 import java.security.cert.CertPathValidatorException.BasicReason;
 import java.security.cert.X509Certificate;
 import java.text.SimpleDateFormat;
+import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Date;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Locale;
 import java.util.Map;
 import java.util.Set;
@@ -100,12 +104,6 @@
     @Override
     public final boolean permits(Set<CryptoPrimitive> primitives,
             String algorithm, AlgorithmParameters parameters) {
-
-        if (primitives == null || primitives.isEmpty()) {
-            throw new IllegalArgumentException(
-                        "No cryptographic primitive specified");
-        }
-
         return checkAlgorithm(disabledAlgorithms, algorithm, decomposer);
     }
 
@@ -133,6 +131,18 @@
         return checkConstraints(primitives, algorithm, key, parameters);
     }
 
+    public final void permits(ConstraintsParameters cp)
+            throws CertPathValidatorException {
+        permits(cp.getAlgorithm(), cp);
+    }
+
+    public final void permits(String algorithm, Key key,
+            AlgorithmParameters params, String variant)
+            throws CertPathValidatorException {
+        permits(algorithm, new ConstraintsParameters(algorithm, params, key,
+                (variant == null) ? Validator.VAR_GENERIC : variant));
+    }
+
     /*
      * Check if a x509Certificate object is permitted.  Check if all
      * algorithms are allowed, certificate constraints, and the
@@ -140,18 +150,10 @@
      *
      * Uses new style permit() which throws exceptions.
      */
-    public final void permits(Set<CryptoPrimitive> primitives,
-            CertConstraintParameters cp) throws CertPathValidatorException {
-        checkConstraints(primitives, cp);
-    }
 
-    /*
-     * Check if Certificate object is within the constraints.
-     * Uses new style permit() which throws exceptions.
-     */
-    public final void permits(Set<CryptoPrimitive> primitives,
-            X509Certificate cert) throws CertPathValidatorException {
-        checkConstraints(primitives, new CertConstraintParameters(cert));
+    public final void permits(String algorithm, ConstraintsParameters cp)
+            throws CertPathValidatorException {
+        algorithmConstraints.permits(algorithm, cp);
     }
 
     // Check if a string is contained inside the property
@@ -174,7 +176,7 @@
             throw new IllegalArgumentException("The key cannot be null");
         }
 
-        // check the signature algorithm
+        // check the signature algorithm with parameters
         if (algorithm != null && algorithm.length() != 0) {
             if (!permits(primitives, algorithm, parameters)) {
                 return false;
@@ -190,36 +192,6 @@
         return algorithmConstraints.permits(key);
     }
 
-    /*
-     * Check algorithm constraints with Certificate
-     * Uses new style permit() which throws exceptions.
-     */
-    private void checkConstraints(Set<CryptoPrimitive> primitives,
-            CertConstraintParameters cp) throws CertPathValidatorException {
-
-        X509Certificate cert = cp.getCertificate();
-        String algorithm = cert.getSigAlgName();
-
-        // Check signature algorithm is not disabled
-        if (!permits(primitives, algorithm, null)) {
-            throw new CertPathValidatorException(
-                    "Algorithm constraints check failed on disabled "+
-                            "signature algorithm: " + algorithm,
-                    null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
-        }
-
-        // Check key algorithm is not disabled
-        if (!permits(primitives, cert.getPublicKey().getAlgorithm(), null)) {
-            throw new CertPathValidatorException(
-                    "Algorithm constraints check failed on disabled "+
-                            "public key algorithm: " + algorithm,
-                    null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
-        }
-
-        // Check the certificate and key constraints
-        algorithmConstraints.permits(cp);
-
-    }
 
     /**
      * Key and Certificate Constraints
@@ -234,13 +206,13 @@
      * 'true' means the operation is allowed.
      * 'false' means it failed the constraints and is disallowed.
      *
-     * When passing CertConstraintParameters through permit(), an exception
+     * When passing ConstraintsParameters through permit(), an exception
      * will be thrown on a failure to better identify why the operation was
      * disallowed.
      */
 
     private static class Constraints {
-        private Map<String, Set<Constraint>> constraintsMap = new HashMap<>();
+        private Map<String, List<Constraint>> constraintsMap = new HashMap<>();
 
         private static class Holder {
             private static final Pattern DENY_AFTER_PATTERN = Pattern.compile(
@@ -260,23 +232,22 @@
 
                 // Check if constraint is a complete disabling of an
                 // algorithm or has conditions.
-                String algorithm;
-                String policy;
                 int space = constraintEntry.indexOf(' ');
-                if (space > 0) {
-                    algorithm = AlgorithmDecomposer.hashName(
-                            constraintEntry.substring(0, space).
-                                    toUpperCase(Locale.ENGLISH));
-                    policy = constraintEntry.substring(space + 1);
-                } else {
-                    algorithm = constraintEntry.toUpperCase(Locale.ENGLISH);
-                    if (!constraintsMap.containsKey(algorithm)) {
-                        constraintsMap.putIfAbsent(algorithm,
-                                new HashSet<>());
-                    }
+                String algorithm = AlgorithmDecomposer.hashName(
+                        ((space > 0 ? constraintEntry.substring(0, space) :
+                                constraintEntry).
+                                toUpperCase(Locale.ENGLISH)));
+                List<Constraint> constraintList =
+                        constraintsMap.getOrDefault(algorithm,
+                                new ArrayList<>(1));
+                constraintsMap.putIfAbsent(algorithm, constraintList);
+                if (space <= 0) {
+                    constraintList.add(new DisabledConstraint(algorithm));
                     continue;
                 }
 
+                String policy = constraintEntry.substring(space + 1);
+
                 // Convert constraint conditions into Constraint classes
                 Constraint c, lastConstraint = null;
                 // Allow only one jdkCA entry per constraint entry
@@ -315,7 +286,7 @@
                         c = new jdkCAConstraint(algorithm);
                         jdkCALimit = true;
 
-                    } else if(entry.startsWith("denyAfter") &&
+                    } else if (entry.startsWith("denyAfter") &&
                             (matcher = Holder.DENY_AFTER_PATTERN.matcher(entry))
                                     .matches()) {
                         if (debug != null) {
@@ -332,6 +303,12 @@
                         c = new DenyAfterConstraint(algorithm, year, month,
                                 day);
                         denyAfterLimit = true;
+                    } else if (entry.startsWith("usage")) {
+                        String s[] = (entry.substring(5)).trim().split(" ");
+                        c = new UsageConstraint(algorithm, s);
+                        if (debug != null) {
+                            debug.println("Constraints usage length is " + s.length);
+                        }
                     } else {
                         throw new IllegalArgumentException("Error in security" +
                                 " property. Constraint unknown: " + entry);
@@ -340,11 +317,7 @@
                     // Link multiple conditions for a single constraint
                     // into a linked list.
                     if (lastConstraint == null) {
-                        if (!constraintsMap.containsKey(algorithm)) {
-                            constraintsMap.putIfAbsent(algorithm,
-                                    new HashSet<>());
-                        }
-                        constraintsMap.get(algorithm).add(c);
+                        constraintList.add(c);
                     } else {
                         lastConstraint.nextConstraint = c;
                     }
@@ -354,17 +327,17 @@
         }
 
         // Get applicable constraints based off the signature algorithm
-        private Set<Constraint> getConstraints(String algorithm) {
+        private List<Constraint> getConstraints(String algorithm) {
             return constraintsMap.get(algorithm);
         }
 
         // Check if KeySizeConstraints permit the specified key
         public boolean permits(Key key) {
-            Set<Constraint> set = getConstraints(key.getAlgorithm());
-            if (set == null) {
+            List<Constraint> list = getConstraints(key.getAlgorithm());
+            if (list == null) {
                 return true;
             }
-            for (Constraint constraint : set) {
+            for (Constraint constraint : list) {
                 if (!constraint.permits(key)) {
                     if (debug != null) {
                         debug.println("keySizeConstraint: failed key " +
@@ -377,31 +350,35 @@
         }
 
         // Check if constraints permit this cert.
-        public void permits(CertConstraintParameters cp)
+        public void permits(String algorithm, ConstraintsParameters cp)
                 throws CertPathValidatorException {
             X509Certificate cert = cp.getCertificate();
 
             if (debug != null) {
-                debug.println("Constraints.permits(): " + cert.getSigAlgName());
+                debug.println("Constraints.permits(): " + algorithm +
+                        " Variant: " + cp.getVariant());
             }
 
             // Get all signature algorithms to check for constraints
-            Set<String> algorithms =
-                    AlgorithmDecomposer.decomposeOneHash(cert.getSigAlgName());
-            if (algorithms == null || algorithms.isEmpty()) {
-                return;
+            Set<String> algorithms = new HashSet<>();
+            if (algorithm != null) {
+                algorithms.addAll(AlgorithmDecomposer.decomposeOneHash(algorithm));
             }
 
-            // Attempt to add the public key algorithm to the set
-            algorithms.add(cert.getPublicKey().getAlgorithm());
-
+            // Attempt to add the public key algorithm if cert provided
+            if (cert != null) {
+                algorithms.add(cert.getPublicKey().getAlgorithm());
+            }
+            if (cp.getPublicKey() != null) {
+                algorithms.add(cp.getPublicKey().getAlgorithm());
+            }
             // Check all applicable constraints
-            for (String algorithm : algorithms) {
-                Set<Constraint> set = getConstraints(algorithm);
-                if (set == null) {
+            for (String alg : algorithms) {
+                List<Constraint> list = getConstraints(alg);
+                if (list == null) {
                     continue;
                 }
-                for (Constraint constraint : set) {
+                for (Constraint constraint : list) {
                     constraint.permits(cp);
                 }
             }
@@ -467,17 +444,17 @@
 
         /**
          * Check if an algorithm constraint is permitted with a given
-         * CertConstraintParameters.
+         * ConstraintsParameters.
          *
          * If the check inside of {@code permits()} fails, it must call
-         * {@code next()} with the same {@code CertConstraintParameters}
+         * {@code next()} with the same {@code ConstraintsParameters}
          * parameter passed if multiple constraints need to be checked.
          *
          * @param cp CertConstraintParameter containing certificate info
          * @throws CertPathValidatorException if constraint disallows.
          *
          */
-        public abstract void permits(CertConstraintParameters cp)
+        public abstract void permits(ConstraintsParameters cp)
                 throws CertPathValidatorException;
 
         /**
@@ -491,12 +468,12 @@
          * were disallowed, the last constraint will throw
          * {@code CertPathValidatorException}.
          *
-         * @param cp CertConstraintParameters
+         * @param cp ConstraintsParameters
          * @return 'true' if constraint allows the operation, 'false' if
          * we are at the end of the constraint list or,
          * {@code nextConstraint} is null.
          */
-        boolean next(CertConstraintParameters cp)
+        boolean next(ConstraintsParameters cp)
                 throws CertPathValidatorException {
             if (nextConstraint != null) {
                 nextConstraint.permits(cp);
@@ -525,6 +502,14 @@
             }
             return false;
         }
+
+        String extendedMsg(ConstraintsParameters cp) {
+            return (cp.getCertificate() == null ? "." :
+                    " used with certificate: " +
+                            cp.getCertificate().getSubjectX500Principal() +
+                    (cp.getVariant() != Validator.VAR_GENERIC ?
+                            ".  Usage was " + cp.getVariant() : "."));
+        }
     }
 
     /*
@@ -537,11 +522,11 @@
         }
 
         /*
-         * Check if CertConstraintParameters has a trusted match, if it does
+         * Check if ConstraintsParameters has a trusted match, if it does
          * call next() for any following constraints. If it does not, exit
          * as this constraint(s) does not restrict the operation.
          */
-        public void permits(CertConstraintParameters cp)
+        public void permits(ConstraintsParameters cp)
                 throws CertPathValidatorException {
             if (debug != null) {
                 debug.println("jdkCAConstraints.permits(): " + algorithm);
@@ -554,8 +539,7 @@
                 }
                 throw new CertPathValidatorException(
                         "Algorithm constraints check failed on certificate " +
-                                "anchor limits. " + algorithm + " used with " +
-                                cp.getCertificate().getSubjectX500Principal(),
+                        "anchor limits. " + algorithm + extendedMsg(cp),
                         null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
             }
         }
@@ -615,7 +599,7 @@
           * constraints. Throw an exception if this is the last constraint.
           */
          @Override
-         public void permits(CertConstraintParameters cp)
+         public void permits(ConstraintsParameters cp)
                  throws CertPathValidatorException {
              Date currentDate;
              String errmsg;
@@ -628,7 +612,7 @@
                  errmsg = "PKIXParameter date: ";
              } else {
                  currentDate = new Date();
-                 errmsg = "Certificate date: ";
+                 errmsg = "Current date: ";
              }
 
              if (!denyAfterDate.after(currentDate)) {
@@ -637,9 +621,9 @@
                  }
                  throw new CertPathValidatorException(
                          "denyAfter constraint check failed: " + algorithm +
-                                 " used with Constraint date: " +
-                                 dateFormat.format(denyAfterDate) + "; "
-                                 + errmsg + dateFormat.format(currentDate),
+                         " used with Constraint date: " +
+                         dateFormat.format(denyAfterDate) + "; " + errmsg +
+                         dateFormat.format(currentDate) + extendedMsg(cp),
                          null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
              }
          }
@@ -661,6 +645,48 @@
      }
 
     /*
+     * The usage constraint is for the "usage" keyword.  It checks against the
+     * variant value in ConstraintsParameters.
+     */
+    private static class UsageConstraint extends Constraint {
+        String[] usages;
+
+        UsageConstraint(String algorithm, String[] usages) {
+            this.algorithm = algorithm;
+            this.usages = usages;
+        }
+
+        public void permits(ConstraintsParameters cp)
+                throws CertPathValidatorException {
+            for (String usage : usages) {
+
+                String v = null;
+                if (usage.compareToIgnoreCase("TLSServer") == 0) {
+                    v = Validator.VAR_TLS_SERVER;
+                } else if (usage.compareToIgnoreCase("TLSClient") == 0) {
+                    v = Validator.VAR_TLS_CLIENT;
+                } else if (usage.compareToIgnoreCase("SignedJAR") == 0) {
+                    v = Validator.VAR_PLUGIN_CODE_SIGNING;
+                }
+
+                if (debug != null) {
+                    debug.println("Checking if usage constraint " + v +
+                            " matches " + cp.getVariant());
+                }
+                if (cp.getVariant().compareTo(v) == 0) {
+                    if (next(cp)) {
+                        return;
+                    }
+                    throw new CertPathValidatorException("Usage constraint " +
+                            usage + " check failed: " + algorithm +
+                            extendedMsg(cp),
+                            null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
+                }
+            }
+        }
+    }
+
+    /*
      * This class contains constraints dealing with the key size
      * support limits per algorithm.   e.g.  "keySize <= 1024"
      */
@@ -713,17 +739,22 @@
          * constraint  Any permitted constraint will exit the linked list
          * to allow the operation.
          */
-        public void permits(CertConstraintParameters cp)
+        public void permits(ConstraintsParameters cp)
                 throws CertPathValidatorException {
-            if (!permitsImpl(cp.getCertificate().getPublicKey())) {
+            Key key = null;
+            if (cp.getPublicKey() != null) {
+                key = cp.getPublicKey();
+            } else if (cp.getCertificate() != null) {
+                key = cp.getCertificate().getPublicKey();
+            }
+            if (key != null && !permitsImpl(key)) {
                 if (nextConstraint != null) {
                     nextConstraint.permits(cp);
                     return;
                 }
                 throw new CertPathValidatorException(
                         "Algorithm constraints check failed on keysize limits. "
-                                + algorithm + " " + size + "bit key used with "
-                                + cp.getCertificate().getSubjectX500Principal(),
+                        + algorithm + " " + size + "bit key" + extendedMsg(cp),
                         null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
             }
         }
@@ -762,5 +793,26 @@
             return true;
         }
     }
+
+    /*
+     * This constraint is used for the complete disabling of the algorithm.
+     */
+    private static class DisabledConstraint extends Constraint {
+        DisabledConstraint(String algo) {
+            algorithm = algo;
+        }
+
+        public void permits(ConstraintsParameters cp)
+                throws CertPathValidatorException {
+            throw new CertPathValidatorException(
+                    "Algorithm constraints check failed on disabled " +
+                            "algorithm: " + algorithm + extendedMsg(cp),
+                    null, null, -1, BasicReason.ALGORITHM_CONSTRAINED);
+        }
+
+        public boolean permits(Key key) {
+            return false;
+        }
+    }
 }
 
--- a/jdk/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/util/SignatureFileVerifier.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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,25 +28,23 @@
 import java.io.ByteArrayInputStream;
 import java.io.IOException;
 import java.security.CodeSigner;
-import java.security.CryptoPrimitive;
+import java.security.GeneralSecurityException;
 import java.security.MessageDigest;
 import java.security.NoSuchAlgorithmException;
 import java.security.SignatureException;
+import java.security.Timestamp;
 import java.security.cert.CertPath;
 import java.security.cert.X509Certificate;
 import java.security.cert.CertificateException;
 import java.security.cert.CertificateFactory;
 import java.util.ArrayList;
 import java.util.Base64;
-import java.util.Collections;
-import java.util.EnumSet;
 import java.util.HashMap;
 import java.util.Hashtable;
 import java.util.Iterator;
 import java.util.List;
 import java.util.Locale;
 import java.util.Map;
-import java.util.Set;
 import java.util.jar.Attributes;
 import java.util.jar.JarException;
 import java.util.jar.JarFile;
@@ -61,9 +59,6 @@
     /* Are we debugging ? */
     private static final Debug debug = Debug.getInstance("jar");
 
-    private static final Set<CryptoPrimitive> DIGEST_PRIMITIVE_SET =
-            Collections.unmodifiableSet(EnumSet.of(CryptoPrimitive.MESSAGE_DIGEST));
-
     private static final DisabledAlgorithmConstraints JAR_DISABLED_CHECK =
             new DisabledAlgorithmConstraints(
                     DisabledAlgorithmConstraints.PROPERTY_JAR_DISABLED_ALGS);
@@ -97,6 +92,14 @@
     /* for generating certpath objects */
     private CertificateFactory certificateFactory = null;
 
+    /** Algorithms that have been checked if they are weak. */
+    private Map<String, Boolean> permittedAlgs= new HashMap<>();
+
+    /** TSA timestamp of signed jar.  The newest timestamp is used.  If there
+     *  was no TSA timestamp used when signed, current time is used ("null").
+     */
+    private Timestamp timestamp = null;
+
     /**
      * Create the named SignatureFileVerifier.
      *
@@ -222,15 +225,8 @@
 
     /** get digest from cache */
 
-    private MessageDigest getDigest(String algorithm) throws SignatureException {
-        // check that algorithm is not restricted
-        if (!JAR_DISABLED_CHECK.permits(DIGEST_PRIMITIVE_SET, algorithm, null)) {
-            SignatureException e =
-                    new SignatureException("SignatureFile check failed. " +
-                            "Disabled algorithm used: " + algorithm);
-            throw e;
-        }
-
+    private MessageDigest getDigest(String algorithm)
+            throws SignatureException {
         if (createdDigests == null)
             createdDigests = new HashMap<>();
 
@@ -302,6 +298,27 @@
         if (newSigners == null)
             return;
 
+        /*
+         * Look for the latest timestamp in the signature block.  If an entry
+         * has no timestamp, use current time (aka null).
+         */
+        for (CodeSigner s: newSigners) {
+            if (debug != null) {
+                debug.println("Gathering timestamp for:  " + s.toString());
+            }
+            if (s.getTimestamp() == null) {
+                timestamp = null;
+                break;
+            } else if (timestamp == null) {
+                timestamp = s.getTimestamp();
+            } else {
+                if (timestamp.getTimestamp().before(
+                        s.getTimestamp().getTimestamp())) {
+                    timestamp = s.getTimestamp();
+                }
+            }
+        }
+
         Iterator<Map.Entry<String,Attributes>> entries =
                                 sf.getEntries().entrySet().iterator();
 
@@ -345,6 +362,68 @@
     }
 
     /**
+     * Check if algorithm is permitted using the permittedAlgs Map.
+     * If the algorithm is not in the map, check against disabled algorithms and
+     * store the result. If the algorithm is in the map use that result.
+     * False is returned for weak algorithm, true for good algorithms.
+     */
+    boolean permittedCheck(String key, String algorithm) {
+        Boolean permitted = permittedAlgs.get(algorithm);
+        if (permitted == null) {
+            try {
+                JAR_DISABLED_CHECK.permits(algorithm,
+                        new ConstraintsParameters(timestamp));
+            } catch(GeneralSecurityException e) {
+                permittedAlgs.put(algorithm, Boolean.FALSE);
+                permittedAlgs.put(key.toUpperCase(), Boolean.FALSE);
+                if (debug != null) {
+                    if (e.getMessage() != null) {
+                        debug.println(key + ":  " + e.getMessage());
+                    } else {
+                        debug.println(key + ":  " + algorithm +
+                                " was disabled, no exception msg given.");
+                        e.printStackTrace();
+                    }
+                }
+                return false;
+            }
+
+            permittedAlgs.put(algorithm, Boolean.TRUE);
+            return true;
+        }
+
+        // Algorithm has already been checked, return the value from map.
+        return permitted.booleanValue();
+    }
+
+    /**
+     * With a given header (*-DIGEST*), return a string that lists all the
+     * algorithms associated with the header.
+     * If there are none, return "Unknown Algorithm".
+     */
+    String getWeakAlgorithms(String header) {
+        String w = "";
+        try {
+            for (String key : permittedAlgs.keySet()) {
+                if (key.endsWith(header)) {
+                    w += key.substring(0, key.length() - header.length()) + " ";
+                }
+            }
+        } catch (RuntimeException e) {
+            w = "Unknown Algorithm(s).  Error processing " + header + ".  " +
+                    e.getMessage();
+        }
+
+        // This means we have an error in finding weak algorithms, run in
+        // debug mode to see permittedAlgs map's values.
+        if (w.length() == 0) {
+            return "Unknown Algorithm(s)";
+        }
+
+        return w;
+    }
+
+    /**
      * See if the whole manifest was signed.
      */
     private boolean verifyManifestHash(Manifest sf,
@@ -354,6 +433,7 @@
     {
         Attributes mattr = sf.getMainAttributes();
         boolean manifestSigned = false;
+        boolean weakAlgs = true;
 
         // go through all the attributes and process *-Digest-Manifest entries
         for (Map.Entry<Object,Object> se : mattr.entrySet()) {
@@ -364,6 +444,15 @@
                 // 16 is length of "-Digest-Manifest"
                 String algorithm = key.substring(0, key.length()-16);
 
+                // Check if this algorithm is permitted, skip if false.
+                if (!permittedCheck(key, algorithm)) {
+                    continue;
+                }
+
+                // A non-weak algorithm was used, any weak algorithms found do
+                // not need to be reported.
+                weakAlgs = false;
+
                 manifestDigests.add(key);
                 manifestDigests.add(se.getValue());
                 MessageDigest digest = getDigest(algorithm);
@@ -373,15 +462,14 @@
                         Base64.getMimeDecoder().decode((String)se.getValue());
 
                     if (debug != null) {
-                     debug.println("Signature File: Manifest digest " +
-                                          digest.getAlgorithm());
-                     debug.println( "  sigfile  " + toHex(expectedHash));
-                     debug.println( "  computed " + toHex(computedHash));
-                     debug.println();
+                        debug.println("Signature File: Manifest digest " +
+                                algorithm);
+                        debug.println( "  sigfile  " + toHex(expectedHash));
+                        debug.println( "  computed " + toHex(computedHash));
+                        debug.println();
                     }
 
-                    if (MessageDigest.isEqual(computedHash,
-                                              expectedHash)) {
+                    if (MessageDigest.isEqual(computedHash, expectedHash)) {
                         manifestSigned = true;
                     } else {
                         //XXX: we will continue and verify each section
@@ -389,15 +477,31 @@
                 }
             }
         }
+
+        if (debug != null) {
+            debug.println("PermittedAlgs mapping: ");
+            for (String key : permittedAlgs.keySet()) {
+                debug.println(key + " : " +
+                        permittedAlgs.get(key).toString());
+            }
+        }
+
+        // If there were only weak algorithms used, throw an exception.
+        if (weakAlgs) {
+            String weakAlgorithms = getWeakAlgorithms("-DIGEST-MANIFEST");
+            throw new SignatureException("Manifest hash check failed " +
+                    "(DIGEST-MANIFEST). Disabled algorithm(s) used: " +
+                    weakAlgorithms);
+        }
         return manifestSigned;
     }
 
-    private boolean verifyManifestMainAttrs(Manifest sf,
-                                        ManifestDigester md)
+    private boolean verifyManifestMainAttrs(Manifest sf, ManifestDigester md)
          throws IOException, SignatureException
     {
         Attributes mattr = sf.getMainAttributes();
         boolean attrsVerified = true;
+        boolean weakAlgs = true;
 
         // go through all the attributes and process
         // digest entries for the manifest main attributes
@@ -408,6 +512,15 @@
                 String algorithm =
                         key.substring(0, key.length() - ATTR_DIGEST.length());
 
+                // Check if this algorithm is permitted, skip if false.
+                if (!permittedCheck(key, algorithm)) {
+                    continue;
+                }
+
+                // A non-weak algorithm was used, any weak algorithms found do
+                // not need to be reported.
+                weakAlgs = false;
+
                 MessageDigest digest = getDigest(algorithm);
                 if (digest != null) {
                     ManifestDigester.Entry mde =
@@ -425,8 +538,7 @@
                      debug.println();
                     }
 
-                    if (MessageDigest.isEqual(computedHash,
-                                              expectedHash)) {
+                    if (MessageDigest.isEqual(computedHash, expectedHash)) {
                         // good
                     } else {
                         // we will *not* continue and verify each section
@@ -442,6 +554,23 @@
             }
         }
 
+        if (debug != null) {
+            debug.println("PermittedAlgs mapping: ");
+            for (String key : permittedAlgs.keySet()) {
+                debug.println(key + " : " +
+                        permittedAlgs.get(key).toString());
+            }
+        }
+
+        // If there were only weak algorithms used, throw an exception.
+        if (weakAlgs) {
+            String weakAlgorithms = getWeakAlgorithms("-DIGEST-" +
+                    ManifestDigester.MF_MAIN_ATTRS);
+            throw new SignatureException("Manifest Main Attribute check " +
+                    "failed (DIGEST-" + ManifestDigester.MF_MAIN_ATTRS +
+                    "). " + "Disabled algorithm(s) used: " + weakAlgorithms);
+        }
+
         // this method returns 'true' if either:
         //      . manifest main attributes were not signed, or
         //      . manifest main attributes were signed and verified
@@ -464,6 +593,7 @@
     {
         boolean oneDigestVerified = false;
         ManifestDigester.Entry mde = md.get(name,block.isOldStyle());
+        boolean weakAlgs = true;
 
         if (mde == null) {
             throw new SecurityException(
@@ -471,7 +601,6 @@
         }
 
         if (sfAttr != null) {
-
             //sun.security.util.HexDumpEncoder hex = new sun.security.util.HexDumpEncoder();
             //hex.encodeBuffer(data, System.out);
 
@@ -483,6 +612,15 @@
                     // 7 is length of "-Digest"
                     String algorithm = key.substring(0, key.length()-7);
 
+                    // Check if this algorithm is permitted, skip if false.
+                    if (!permittedCheck(key, algorithm)) {
+                        continue;
+                    }
+
+                    // A non-weak algorithm was used, any weak algorithms found do
+                    // not need to be reported.
+                    weakAlgs = false;
+
                     MessageDigest digest = getDigest(algorithm);
 
                     if (digest != null) {
@@ -532,6 +670,23 @@
                 }
             }
         }
+
+        if (debug != null) {
+            debug.println("PermittedAlgs mapping: ");
+            for (String key : permittedAlgs.keySet()) {
+                debug.println(key + " : " +
+                        permittedAlgs.get(key).toString());
+            }
+        }
+
+        // If there were only weak algorithms used, throw an exception.
+        if (weakAlgs) {
+            String weakAlgorithms = getWeakAlgorithms("DIGEST");
+            throw new SignatureException("Manifest Main Attribute check " +
+                    "failed (DIGEST). " + "Disabled algorithm(s) used: " +
+                    weakAlgorithms);
+        }
+
         return oneDigestVerified;
     }
 
--- a/jdk/src/java.base/share/classes/sun/security/validator/PKIXValidator.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/validator/PKIXValidator.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, 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,7 +33,7 @@
 import javax.security.auth.x500.X500Principal;
 import sun.security.action.GetBooleanAction;
 import sun.security.provider.certpath.AlgorithmChecker;
-import sun.security.provider.certpath.PKIXTimestampParameters;
+import sun.security.provider.certpath.PKIXExtendedParameters;
 
 /**
  * Validator implementation built on the PKIX CertPath API. This
@@ -199,9 +199,9 @@
         PKIXBuilderParameters pkixParameters = null;
         if (parameter instanceof Timestamp && plugin) {
             try {
-                pkixParameters = new PKIXTimestampParameters(
+                pkixParameters = new PKIXExtendedParameters(
                         (PKIXBuilderParameters) parameterTemplate.clone(),
-                        (Timestamp) parameter);
+                        (Timestamp) parameter, variant);
             } catch (InvalidAlgorithmParameterException e) {
                 // ignore exception
             }
@@ -211,7 +211,8 @@
 
         // add new algorithm constraints checker
         if (constraints != null) {
-            pkixParameters.addCertPathChecker(new AlgorithmChecker(constraints));
+            pkixParameters.addCertPathChecker(
+                    new AlgorithmChecker(constraints, null, variant));
         }
 
         // attach it to the PKIXBuilderParameters.
--- a/jdk/src/java.base/share/classes/sun/security/validator/SimpleValidator.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/classes/sun/security/validator/SimpleValidator.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, 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
@@ -155,12 +155,14 @@
 
         // create default algorithm constraints checker
         TrustAnchor anchor = new TrustAnchor(anchorCert, null);
-        AlgorithmChecker defaultAlgChecker = new AlgorithmChecker(anchor);
+        AlgorithmChecker defaultAlgChecker =
+                new AlgorithmChecker(anchor, variant);
 
         // create application level algorithm constraints checker
         AlgorithmChecker appAlgChecker = null;
         if (constraints != null) {
-            appAlgChecker = new AlgorithmChecker(anchor, constraints);
+            appAlgChecker = new AlgorithmChecker(anchor, constraints, null,
+                    variant);
         }
 
         // verify top down, starting at the certificate issued by
--- a/jdk/src/java.base/share/conf/security/java.security	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/conf/security/java.security	Thu Mar 16 20:47:03 2017 +0000
@@ -116,6 +116,13 @@
 # Example:
 #   jdk.security.provider.preferred=AES/GCM/NoPadding:SunJCE, \
 #         MessageDigest.SHA-256:SUN, Group.HmacSHA2:SunJCE
+#
+#ifdef solaris-sparc
+# Optional Solaris-SPARC configuration for non-FIPS 140 configurations.
+#   jdk.security.provider.preferred=AES:SunJCE, SHA1:SUN, Group.SHA2:SUN, \
+#   HmacSHA1:SunJCE, Group.HmacSHA2:SunJCE
+#
+#endif
 #jdk.security.provider.preferred=
 
 
@@ -240,6 +247,7 @@
 #
 # The default value is an empty string, which is equivalent to
 #   securerandom.drbg.config=Hash_DRBG,SHA-256,128,none
+#
 securerandom.drbg.config=
 
 #
@@ -262,23 +270,27 @@
 
 # The default is to have a single system-wide policy file,
 # and a policy file in the user's home directory.
+#
 policy.url.1=file:${java.home}/conf/security/java.policy
 policy.url.2=file:${user.home}/.java.policy
 
 # whether or not we expand properties in the policy file
 # if this is set to false, properties (${...}) will not be expanded in policy
 # files.
+#
 policy.expandProperties=true
 
 # whether or not we allow an extra policy to be passed on the command line
 # with -Djava.security.policy=somefile. Comment out this line to disable
 # this feature.
+#
 policy.allowSystemProperty=true
 
 # whether or not we look into the IdentityScope for trusted Identities
 # when encountering a 1.1 signed JAR file. If the identity is found
 # and is trusted, we grant it AllPermission. Note: the default policy
 # provider (sun.security.provider.PolicyFile) does not support this property.
+#
 policy.ignoreIdentityScope=false
 
 #
@@ -360,7 +372,6 @@
 # For this reason the default caching policy is to maintain these
 # results for 10 seconds.
 #
-#
 networkaddress.cache.negative.ttl=10
 
 #
@@ -460,8 +471,10 @@
 # Example,
 #   krb5.kdc.bad.policy = tryLast
 #   krb5.kdc.bad.policy = tryLess:2,2000
+#
 krb5.kdc.bad.policy = tryLast
 
+#
 # Algorithm restrictions for certification path (CertPath) processing
 #
 # In some environments, certain algorithms or key lengths may be undesirable
@@ -481,7 +494,8 @@
 #       (see below)
 #
 #   Constraint:
-#       KeySizeConstraint | CAConstraint | DenyAfterConstraint
+#       KeySizeConstraint | CAConstraint | DenyAfterConstraint |
+#       UsageConstraint
 #
 #   KeySizeConstraint:
 #       keySize Operator KeyLength
@@ -498,6 +512,9 @@
 #   DenyAfterConstraint:
 #       denyAfter YYYY-MM-DD
 #
+#   UsageConstraint:
+#       usage [TLSServer] [TLSClient] [SignedJAR]
+#
 # The "AlgorithmName" is the standard algorithm name of the disabled
 # algorithm. See "Java Cryptography Architecture Standard Algorithm Name
 # Documentation" for information about Standard Algorithm Names.  Matching
@@ -547,6 +564,19 @@
 #       Example:  To deny usage of RSA 2048 bit certificates after Feb 3 2020,
 #       use the following:  "RSA keySize == 2048 & denyAfter 2020-02-03"
 #
+#   UsageConstraint:
+#     usage [TLSServer] [TLSClient] [SignedJAR]
+#       This constraint prohibits the specified algorithm for
+#       a specified usage.  This should be used when disabling an algorithm
+#       for all usages is not practical. 'TLSServer' restricts the algorithm
+#       in TLS server certificate chains when server authentication is
+#       performed. 'TLSClient' restricts the algorithm in TLS client
+#       certificate chains when client authentication is performed.
+#       'SignedJAR' constrains use of certificates in signed jar files.
+#       The usage type follows the keyword and more than one usage type can
+#       be specified with a whitespace delimiter.
+#       Example:  "SHA1 usage TLSServer TLSClient"
+#
 # When an algorithm must satisfy more than one constraint, it must be
 # delimited by an ampersand '&'.  For example, to restrict certificates in a
 # chain that terminate at a distribution provided trust anchor and contain
@@ -568,39 +598,10 @@
 #   jdk.certpath.disabledAlgorithms=MD2, DSA, RSA keySize < 2048
 #
 #
-jdk.certpath.disabledAlgorithms=MD2, MD5, SHA1 jdkCA & denyAfter 2017-01-01, \
-    RSA keySize < 1024, DSA keySize < 1024, EC keySize < 224
+jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024, \
+    DSA keySize < 1024, EC keySize < 224
 
 #
-# RMI Registry Serial Filter
-#
-# The filter pattern uses the same format as jdk.serialFilter.
-# This filter can override the builtin filter if additional types need to be
-# allowed or rejected from the RMI Registry.
-#
-# Note: This property is currently used by the JDK Reference implementation.
-# It is not guaranteed to be examined and used by other implementations.
-#
-#sun.rmi.registry.registryFilter=pattern;pattern
-#
-# RMI Distributed Garbage Collector (DGC) Serial Filter
-#
-# The filter pattern uses the same format as jdk.serialFilter.
-# This filter can override the builtin filter if additional types need to be
-# allowed or rejected from the RMI DGC.
-#
-# Note: This property is currently used by the JDK Reference implementation.
-# It is not guaranteed to be examined and used by other implementations.
-#
-# The builtin DGC filter can approximately be represented as the filter pattern:
-#
-#sun.rmi.transport.dgcFilter=\
-#    java.rmi.server.ObjID;\
-#    java.rmi.server.UID;\
-#    java.rmi.dgc.VMID;\
-#    java.rmi.dgc.Lease;\
-#    maxdepth=5;maxarray=10000
-
 # Algorithm restrictions for signed JAR files
 #
 # In some environments, certain algorithms or key lengths may be undesirable
@@ -615,17 +616,20 @@
 #       " DisabledAlgorithm { , DisabledAlgorithm } "
 #
 #   DisabledAlgorithm:
-#       AlgorithmName [Constraint]
+#       AlgorithmName [Constraint] { '&' Constraint }
 #
 #   AlgorithmName:
 #       (see below)
 #
 #   Constraint:
-#       KeySizeConstraint
+#       KeySizeConstraint | DenyAfterConstraint
 #
 #   KeySizeConstraint:
 #       keySize Operator KeyLength
 #
+#   DenyAfterConstraint:
+#       denyAfter YYYY-MM-DD
+#
 #   Operator:
 #       <= | < | == | != | >= | >
 #
@@ -636,9 +640,12 @@
 # implementation. It is not guaranteed to be examined and used by other
 # implementations.
 #
+# See "jdk.certpath.disabledAlgorithms" for syntax descriptions.
+#
 jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024, \
       DSA keySize < 1024
 
+#
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
 # (SSL/TLS/DTLS) processing
 #
@@ -939,3 +946,32 @@
 #
 #jdk.serialFilter=pattern;pattern
 
+#
+# RMI Registry Serial Filter
+#
+# The filter pattern uses the same format as jdk.serialFilter.
+# This filter can override the builtin filter if additional types need to be
+# allowed or rejected from the RMI Registry.
+#
+# Note: This property is currently used by the JDK Reference implementation.
+# It is not guaranteed to be examined and used by other implementations.
+#
+#sun.rmi.registry.registryFilter=pattern;pattern
+#
+# RMI Distributed Garbage Collector (DGC) Serial Filter
+#
+# The filter pattern uses the same format as jdk.serialFilter.
+# This filter can override the builtin filter if additional types need to be
+# allowed or rejected from the RMI DGC.
+#
+# Note: This property is currently used by the JDK Reference implementation.
+# It is not guaranteed to be examined and used by other implementations.
+#
+# The builtin DGC filter can approximately be represented as the filter pattern:
+#
+#sun.rmi.transport.dgcFilter=\
+#    java.rmi.server.ObjID;\
+#    java.rmi.server.UID;\
+#    java.rmi.dgc.VMID;\
+#    java.rmi.dgc.Lease;\
+#    maxdepth=5;maxarray=10000
--- a/jdk/src/java.base/share/lib/security/default.policy	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/lib/security/default.policy	Thu Mar 16 20:47:03 2017 +0000
@@ -70,6 +70,8 @@
 
 grant codeBase "jrt:/java.xml.bind" {
     permission java.lang.RuntimePermission
+                   "accessClassInPackage.sun.misc";
+    permission java.lang.RuntimePermission
                    "accessClassInPackage.com.sun.xml.internal.*";
     permission java.lang.RuntimePermission
                    "accessClassInPackage.com.sun.istack.internal";
@@ -102,18 +104,16 @@
 };
 
 grant codeBase "jrt:/java.xml.ws" {
+    permission java.net.NetPermission
+                   "getProxySelector";
     permission java.lang.RuntimePermission
-                   "accessClassInPackage.com.sun.org.apache.xml.internal.resolver";
-    permission java.lang.RuntimePermission
-                   "accessClassInPackage.com.sun.org.apache.xml.internal.resolver.tools";
+                   "accessClassInPackage.sun.misc";
     permission java.lang.RuntimePermission
                    "accessClassInPackage.com.sun.xml.internal.*";
     permission java.lang.RuntimePermission
                    "accessClassInPackage.com.sun.istack.internal";
     permission java.lang.RuntimePermission
                    "accessClassInPackage.com.sun.istack.internal.*";
-    permission java.lang.RuntimePermission
-                   "accessClassInPackage.com.sun.org.apache.xerces.internal.*";
     permission java.lang.RuntimePermission "accessDeclaredMembers";
     permission java.lang.reflect.ReflectPermission "suppressAccessChecks";
     permission java.util.PropertyPermission "*", "read";
@@ -213,3 +213,7 @@
     permission java.lang.RuntimePermission "accessClassInPackage.com.sun.java.swing.plaf.*";
     permission java.lang.RuntimePermission "accessClassInPackage.com.apple.*";
 };
+
+grant codeBase "jrt:/jdk.vm.compiler" {
+    permission java.security.AllPermission;
+};
--- a/jdk/src/java.base/share/native/launcher/main.c	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/native/launcher/main.c	Thu Mar 16 20:47:03 2017 +0000
@@ -130,10 +130,10 @@
 
         // Add first arg, which is the app name
         JLI_List_add(args, JLI_StringDup(argv[0]));
-        // Append JAVA_OPTIONS
-        if (JLI_AddArgsFromEnvVar(args, JAVA_OPTIONS)) {
+        // Append JDK_JAVA_OPTIONS
+        if (JLI_AddArgsFromEnvVar(args, JDK_JAVA_OPTIONS)) {
             // JLI_SetTraceLauncher is not called yet
-            // Show _JAVA_OPTIONS content along with JAVA_OPTIONS to aid diagnosis
+            // Show _JAVA_OPTIONS content along with JDK_JAVA_OPTIONS to aid diagnosis
             if (getenv(JLDEBUG_ENV_ENTRY)) {
                 char *tmp = getenv("_JAVA_OPTIONS");
                 if (NULL != tmp) {
--- a/jdk/src/java.base/share/native/libjli/args.c	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/native/libjli/args.c	Thu Mar 16 20:47:03 2017 +0000
@@ -34,7 +34,7 @@
     #define NO_JNI
   #endif
   #define JLI_ReportMessage(...) printf(__VA_ARGS__)
-  #define JAVA_OPTIONS "JAVA_OPTIONS"
+  #define JDK_JAVA_OPTIONS "JDK_JAVA_OPTIONS"
   int IsWhiteSpaceOption(const char* name) { return 1; }
 #else
   #include "java.h"
@@ -429,10 +429,6 @@
 }
 
 jboolean JLI_AddArgsFromEnvVar(JLI_List args, const char *var_name) {
-
-#ifndef ENABLE_JAVA_OPTIONS
-    return JNI_FALSE;
-#else
     char *env = getenv(var_name);
     char *p, *arg;
     char quote;
@@ -519,7 +515,6 @@
     }
 
     return JNI_TRUE;
-#endif
 }
 
 #ifdef DEBUG_ARGFILE
--- a/jdk/src/java.base/share/native/libjli/java.h	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/share/native/libjli/java.h	Thu Mar 16 20:47:03 2017 +0000
@@ -71,7 +71,7 @@
 
 #define SPLASH_FILE_ENV_ENTRY "_JAVA_SPLASH_FILE"
 #define SPLASH_JAR_ENV_ENTRY "_JAVA_SPLASH_JAR"
-#define JAVA_OPTIONS "JAVA_OPTIONS"
+#define JDK_JAVA_OPTIONS "JDK_JAVA_OPTIONS"
 
 /*
  * Pointers to the needed JNI invocation API, initialized by LoadJavaVM.
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/ChangeLog	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1472 +0,0 @@
-
-                ChangeLog file for zlib
-
-Changes in 1.2.8 (28 Apr 2013)
-- Update contrib/minizip/iowin32.c for Windows RT [Vollant]
-- Do not force Z_CONST for C++
-- Clean up contrib/vstudio [Ro§]
-- Correct spelling error in zlib.h
-- Fix mixed line endings in contrib/vstudio
-
-Changes in 1.2.7.3 (13 Apr 2013)
-- Fix version numbers and DLL names in contrib/vstudio/*/zlib.rc
-
-Changes in 1.2.7.2 (13 Apr 2013)
-- Change check for a four-byte type back to hexadecimal
-- Fix typo in win32/Makefile.msc
-- Add casts in gzwrite.c for pointer differences
-
-Changes in 1.2.7.1 (24 Mar 2013)
-- Replace use of unsafe string functions with snprintf if available
-- Avoid including stddef.h on Windows for Z_SOLO compile [Niessink]
-- Fix gzgetc undefine when Z_PREFIX set [Turk]
-- Eliminate use of mktemp in Makefile (not always available)
-- Fix bug in 'F' mode for gzopen()
-- Add inflateGetDictionary() function
-- Correct comment in deflate.h
-- Use _snprintf for snprintf in Microsoft C
-- On Darwin, only use /usr/bin/libtool if libtool is not Apple
-- Delete "--version" file if created by "ar --version" [Richard G.]
-- Fix configure check for veracity of compiler error return codes
-- Fix CMake compilation of static lib for MSVC2010 x64
-- Remove unused variable in infback9.c
-- Fix argument checks in gzlog_compress() and gzlog_write()
-- Clean up the usage of z_const and respect const usage within zlib
-- Clean up examples/gzlog.[ch] comparisons of different types
-- Avoid shift equal to bits in type (caused endless loop)
-- Fix unintialized value bug in gzputc() introduced by const patches
-- Fix memory allocation error in examples/zran.c [Nor]
-- Fix bug where gzopen(), gzclose() would write an empty file
-- Fix bug in gzclose() when gzwrite() runs out of memory
-- Check for input buffer malloc failure in examples/gzappend.c
-- Add note to contrib/blast to use binary mode in stdio
-- Fix comparisons of differently signed integers in contrib/blast
-- Check for invalid code length codes in contrib/puff
-- Fix serious but very rare decompression bug in inftrees.c
-- Update inflateBack() comments, since inflate() can be faster
-- Use underscored I/O function names for WINAPI_FAMILY
-- Add _tr_flush_bits to the external symbols prefixed by --zprefix
-- Add contrib/vstudio/vc10 pre-build step for static only
-- Quote --version-script argument in CMakeLists.txt
-- Don't specify --version-script on Apple platforms in CMakeLists.txt
-- Fix casting error in contrib/testzlib/testzlib.c
-- Fix types in contrib/minizip to match result of get_crc_table()
-- Simplify contrib/vstudio/vc10 with 'd' suffix
-- Add TOP support to win32/Makefile.msc
-- Suport i686 and amd64 assembler builds in CMakeLists.txt
-- Fix typos in the use of _LARGEFILE64_SOURCE in zconf.h
-- Add vc11 and vc12 build files to contrib/vstudio
-- Add gzvprintf() as an undocumented function in zlib
-- Fix configure for Sun shell
-- Remove runtime check in configure for four-byte integer type
-- Add casts and consts to ease user conversion to C++
-- Add man pages for minizip and miniunzip
-- In Makefile uninstall, don't rm if preceding cd fails
-- Do not return Z_BUF_ERROR if deflateParam() has nothing to write
-
-Changes in 1.2.7 (2 May 2012)
-- Replace use of memmove() with a simple copy for portability
-- Test for existence of strerror
-- Restore gzgetc_ for backward compatibility with 1.2.6
-- Fix build with non-GNU make on Solaris
-- Require gcc 4.0 or later on Mac OS X to use the hidden attribute
-- Include unistd.h for Watcom C
-- Use __WATCOMC__ instead of __WATCOM__
-- Do not use the visibility attribute if NO_VIZ defined
-- Improve the detection of no hidden visibility attribute
-- Avoid using __int64 for gcc or solo compilation
-- Cast to char * in gzprintf to avoid warnings [Zinser]
-- Fix make_vms.com for VAX [Zinser]
-- Don't use library or built-in byte swaps
-- Simplify test and use of gcc hidden attribute
-- Fix bug in gzclose_w() when gzwrite() fails to allocate memory
-- Add "x" (O_EXCL) and "e" (O_CLOEXEC) modes support to gzopen()
-- Fix bug in test/minigzip.c for configure --solo
-- Fix contrib/vstudio project link errors [Mohanathas]
-- Add ability to choose the builder in make_vms.com [Schweda]
-- Add DESTDIR support to mingw32 win32/Makefile.gcc
-- Fix comments in win32/Makefile.gcc for proper usage
-- Allow overriding the default install locations for cmake
-- Generate and install the pkg-config file with cmake
-- Build both a static and a shared version of zlib with cmake
-- Include version symbols for cmake builds
-- If using cmake with MSVC, add the source directory to the includes
-- Remove unneeded EXTRA_CFLAGS from win32/Makefile.gcc [Truta]
-- Move obsolete emx makefile to old [Truta]
-- Allow the use of -Wundef when compiling or using zlib
-- Avoid the use of the -u option with mktemp
-- Improve inflate() documentation on the use of Z_FINISH
-- Recognize clang as gcc
-- Add gzopen_w() in Windows for wide character path names
-- Rename zconf.h in CMakeLists.txt to move it out of the way
-- Add source directory in CMakeLists.txt for building examples
-- Look in build directory for zlib.pc in CMakeLists.txt
-- Remove gzflags from zlibvc.def in vc9 and vc10
-- Fix contrib/minizip compilation in the MinGW environment
-- Update ./configure for Solaris, support --64 [Mooney]
-- Remove -R. from Solaris shared build (possible security issue)
-- Avoid race condition for parallel make (-j) running example
-- Fix type mismatch between get_crc_table() and crc_table
-- Fix parsing of version with "-" in CMakeLists.txt [Snider, Ziegler]
-- Fix the path to zlib.map in CMakeLists.txt
-- Force the native libtool in Mac OS X to avoid GNU libtool [Beebe]
-- Add instructions to win32/Makefile.gcc for shared install [Torri]
-
-Changes in 1.2.6.1 (12 Feb 2012)
-- Avoid the use of the Objective-C reserved name "id"
-- Include io.h in gzguts.h for Microsoft compilers
-- Fix problem with ./configure --prefix and gzgetc macro
-- Include gz_header definition when compiling zlib solo
-- Put gzflags() functionality back in zutil.c
-- Avoid library header include in crc32.c for Z_SOLO
-- Use name in GCC_CLASSIC as C compiler for coverage testing, if set
-- Minor cleanup in contrib/minizip/zip.c [Vollant]
-- Update make_vms.com [Zinser]
-- Remove unnecessary gzgetc_ function
-- Use optimized byte swap operations for Microsoft and GNU [Snyder]
-- Fix minor typo in zlib.h comments [Rzesniowiecki]
-
-Changes in 1.2.6 (29 Jan 2012)
-- Update the Pascal interface in contrib/pascal
-- Fix function numbers for gzgetc_ in zlibvc.def files
-- Fix configure.ac for contrib/minizip [Schiffer]
-- Fix large-entry detection in minizip on 64-bit systems [Schiffer]
-- Have ./configure use the compiler return code for error indication
-- Fix CMakeLists.txt for cross compilation [McClure]
-- Fix contrib/minizip/zip.c for 64-bit architectures [Dalsnes]
-- Fix compilation of contrib/minizip on FreeBSD [Marquez]
-- Correct suggested usages in win32/Makefile.msc [Shachar, Horvath]
-- Include io.h for Turbo C / Borland C on all platforms [Truta]
-- Make version explicit in contrib/minizip/configure.ac [Bosmans]
-- Avoid warning for no encryption in contrib/minizip/zip.c [Vollant]
-- Minor cleanup up contrib/minizip/unzip.c [Vollant]
-- Fix bug when compiling minizip with C++ [Vollant]
-- Protect for long name and extra fields in contrib/minizip [Vollant]
-- Avoid some warnings in contrib/minizip [Vollant]
-- Add -I../.. -L../.. to CFLAGS for minizip and miniunzip
-- Add missing libs to minizip linker command
-- Add support for VPATH builds in contrib/minizip
-- Add an --enable-demos option to contrib/minizip/configure
-- Add the generation of configure.log by ./configure
-- Exit when required parameters not provided to win32/Makefile.gcc
-- Have gzputc return the character written instead of the argument
-- Use the -m option on ldconfig for BSD systems [Tobias]
-- Correct in zlib.map when deflateResetKeep was added
-
-Changes in 1.2.5.3 (15 Jan 2012)
-- Restore gzgetc function for binary compatibility
-- Do not use _lseeki64 under Borland C++ [Truta]
-- Update win32/Makefile.msc to build test/*.c [Truta]
-- Remove old/visualc6 given CMakefile and other alternatives
-- Update AS400 build files and documentation [Monnerat]
-- Update win32/Makefile.gcc to build test/*.c [Truta]
-- Permit stronger flushes after Z_BLOCK flushes
-- Avoid extraneous empty blocks when doing empty flushes
-- Permit Z_NULL arguments to deflatePending
-- Allow deflatePrime() to insert bits in the middle of a stream
-- Remove second empty static block for Z_PARTIAL_FLUSH
-- Write out all of the available bits when using Z_BLOCK
-- Insert the first two strings in the hash table after a flush
-
-Changes in 1.2.5.2 (17 Dec 2011)
-- fix ld error: unable to find version dependency 'ZLIB_1.2.5'
-- use relative symlinks for shared libs
-- Avoid searching past window for Z_RLE strategy
-- Assure that high-water mark initialization is always applied in deflate
-- Add assertions to fill_window() in deflate.c to match comments
-- Update python link in README
-- Correct spelling error in gzread.c
-- Fix bug in gzgets() for a concatenated empty gzip stream
-- Correct error in comment for gz_make()
-- Change gzread() and related to ignore junk after gzip streams
-- Allow gzread() and related to continue after gzclearerr()
-- Allow gzrewind() and gzseek() after a premature end-of-file
-- Simplify gzseek() now that raw after gzip is ignored
-- Change gzgetc() to a macro for speed (~40% speedup in testing)
-- Fix gzclose() to return the actual error last encountered
-- Always add large file support for windows
-- Include zconf.h for windows large file support
-- Include zconf.h.cmakein for windows large file support
-- Update zconf.h.cmakein on make distclean
-- Merge vestigial vsnprintf determination from zutil.h to gzguts.h
-- Clarify how gzopen() appends in zlib.h comments
-- Correct documentation of gzdirect() since junk at end now ignored
-- Add a transparent write mode to gzopen() when 'T' is in the mode
-- Update python link in zlib man page
-- Get inffixed.h and MAKEFIXED result to match
-- Add a ./config --solo option to make zlib subset with no libary use
-- Add undocumented inflateResetKeep() function for CAB file decoding
-- Add --cover option to ./configure for gcc coverage testing
-- Add #define ZLIB_CONST option to use const in the z_stream interface
-- Add comment to gzdopen() in zlib.h to use dup() when using fileno()
-- Note behavior of uncompress() to provide as much data as it can
-- Add files in contrib/minizip to aid in building libminizip
-- Split off AR options in Makefile.in and configure
-- Change ON macro to Z_ARG to avoid application conflicts
-- Facilitate compilation with Borland C++ for pragmas and vsnprintf
-- Include io.h for Turbo C / Borland C++
-- Move example.c and minigzip.c to test/
-- Simplify incomplete code table filling in inflate_table()
-- Remove code from inflate.c and infback.c that is impossible to execute
-- Test the inflate code with full coverage
-- Allow deflateSetDictionary, inflateSetDictionary at any time (in raw)
-- Add deflateResetKeep and fix inflateResetKeep to retain dictionary
-- Fix gzwrite.c to accommodate reduced memory zlib compilation
-- Have inflate() with Z_FINISH avoid the allocation of a window
-- Do not set strm->adler when doing raw inflate
-- Fix gzeof() to behave just like feof() when read is not past end of file
-- Fix bug in gzread.c when end-of-file is reached
-- Avoid use of Z_BUF_ERROR in gz* functions except for premature EOF
-- Document gzread() capability to read concurrently written files
-- Remove hard-coding of resource compiler in CMakeLists.txt [Blammo]
-
-Changes in 1.2.5.1 (10 Sep 2011)
-- Update FAQ entry on shared builds (#13)
-- Avoid symbolic argument to chmod in Makefile.in
-- Fix bug and add consts in contrib/puff [Oberhumer]
-- Update contrib/puff/zeros.raw test file to have all block types
-- Add full coverage test for puff in contrib/puff/Makefile
-- Fix static-only-build install in Makefile.in
-- Fix bug in unzGetCurrentFileInfo() in contrib/minizip [Kuno]
-- Add libz.a dependency to shared in Makefile.in for parallel builds
-- Spell out "number" (instead of "nb") in zlib.h for total_in, total_out
-- Replace $(...) with `...` in configure for non-bash sh [Bowler]
-- Add darwin* to Darwin* and solaris* to SunOS\ 5* in configure [Groffen]
-- Add solaris* to Linux* in configure to allow gcc use [Groffen]
-- Add *bsd* to Linux* case in configure [Bar-Lev]
-- Add inffast.obj to dependencies in win32/Makefile.msc
-- Correct spelling error in deflate.h [Kohler]
-- Change libzdll.a again to libz.dll.a (!) in win32/Makefile.gcc
-- Add test to configure for GNU C looking for gcc in output of $cc -v
-- Add zlib.pc generation to win32/Makefile.gcc [Weigelt]
-- Fix bug in zlib.h for _FILE_OFFSET_BITS set and _LARGEFILE64_SOURCE not
-- Add comment in zlib.h that adler32_combine with len2 < 0 makes no sense
-- Make NO_DIVIDE option in adler32.c much faster (thanks to John Reiser)
-- Make stronger test in zconf.h to include unistd.h for LFS
-- Apply Darwin patches for 64-bit file offsets to contrib/minizip [Slack]
-- Fix zlib.h LFS support when Z_PREFIX used
-- Add updated as400 support (removed from old) [Monnerat]
-- Avoid deflate sensitivity to volatile input data
-- Avoid division in adler32_combine for NO_DIVIDE
-- Clarify the use of Z_FINISH with deflateBound() amount of space
-- Set binary for output file in puff.c
-- Use u4 type for crc_table to avoid conversion warnings
-- Apply casts in zlib.h to avoid conversion warnings
-- Add OF to prototypes for adler32_combine_ and crc32_combine_ [Miller]
-- Improve inflateSync() documentation to note indeterminancy
-- Add deflatePending() function to return the amount of pending output
-- Correct the spelling of "specification" in FAQ [Randers-Pehrson]
-- Add a check in configure for stdarg.h, use for gzprintf()
-- Check that pointers fit in ints when gzprint() compiled old style
-- Add dummy name before $(SHAREDLIBV) in Makefile [Bar-Lev, Bowler]
-- Delete line in configure that adds -L. libz.a to LDFLAGS [Weigelt]
-- Add debug records in assmebler code [Londer]
-- Update RFC references to use http://tools.ietf.org/html/... [Li]
-- Add --archs option, use of libtool to configure for Mac OS X [Borstel]
-
-Changes in 1.2.5 (19 Apr 2010)
-- Disable visibility attribute in win32/Makefile.gcc [Bar-Lev]
-- Default to libdir as sharedlibdir in configure [Nieder]
-- Update copyright dates on modified source files
-- Update trees.c to be able to generate modified trees.h
-- Exit configure for MinGW, suggesting win32/Makefile.gcc
-- Check for NULL path in gz_open [Homurlu]
-
-Changes in 1.2.4.5 (18 Apr 2010)
-- Set sharedlibdir in configure [Torok]
-- Set LDFLAGS in Makefile.in [Bar-Lev]
-- Avoid mkdir objs race condition in Makefile.in [Bowler]
-- Add ZLIB_INTERNAL in front of internal inter-module functions and arrays
-- Define ZLIB_INTERNAL to hide internal functions and arrays for GNU C
-- Don't use hidden attribute when it is a warning generator (e.g. Solaris)
-
-Changes in 1.2.4.4 (18 Apr 2010)
-- Fix CROSS_PREFIX executable testing, CHOST extract, mingw* [Torok]
-- Undefine _LARGEFILE64_SOURCE in zconf.h if it is zero, but not if empty
-- Try to use bash or ksh regardless of functionality of /bin/sh
-- Fix configure incompatibility with NetBSD sh
-- Remove attempt to run under bash or ksh since have better NetBSD fix
-- Fix win32/Makefile.gcc for MinGW [Bar-Lev]
-- Add diagnostic messages when using CROSS_PREFIX in configure
-- Added --sharedlibdir option to configure [Weigelt]
-- Use hidden visibility attribute when available [Frysinger]
-
-Changes in 1.2.4.3 (10 Apr 2010)
-- Only use CROSS_PREFIX in configure for ar and ranlib if they exist
-- Use CROSS_PREFIX for nm [Bar-Lev]
-- Assume _LARGEFILE64_SOURCE defined is equivalent to true
-- Avoid use of undefined symbols in #if with && and ||
-- Make *64 prototypes in gzguts.h consistent with functions
-- Add -shared load option for MinGW in configure [Bowler]
-- Move z_off64_t to public interface, use instead of off64_t
-- Remove ! from shell test in configure (not portable to Solaris)
-- Change +0 macro tests to -0 for possibly increased portability
-
-Changes in 1.2.4.2 (9 Apr 2010)
-- Add consistent carriage returns to readme.txt's in masmx86 and masmx64
-- Really provide prototypes for *64 functions when building without LFS
-- Only define unlink() in minigzip.c if unistd.h not included
-- Update README to point to contrib/vstudio project files
-- Move projects/vc6 to old/ and remove projects/
-- Include stdlib.h in minigzip.c for setmode() definition under WinCE
-- Clean up assembler builds in win32/Makefile.msc [Rowe]
-- Include sys/types.h for Microsoft for off_t definition
-- Fix memory leak on error in gz_open()
-- Symbolize nm as $NM in configure [Weigelt]
-- Use TEST_LDSHARED instead of LDSHARED to link test programs [Weigelt]
-- Add +0 to _FILE_OFFSET_BITS and _LFS64_LARGEFILE in case not defined
-- Fix bug in gzeof() to take into account unused input data
-- Avoid initialization of structures with variables in puff.c
-- Updated win32/README-WIN32.txt [Rowe]
-
-Changes in 1.2.4.1 (28 Mar 2010)
-- Remove the use of [a-z] constructs for sed in configure [gentoo 310225]
-- Remove $(SHAREDLIB) from LIBS in Makefile.in [Creech]
-- Restore "for debugging" comment on sprintf() in gzlib.c
-- Remove fdopen for MVS from gzguts.h
-- Put new README-WIN32.txt in win32 [Rowe]
-- Add check for shell to configure and invoke another shell if needed
-- Fix big fat stinking bug in gzseek() on uncompressed files
-- Remove vestigial F_OPEN64 define in zutil.h
-- Set and check the value of _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE
-- Avoid errors on non-LFS systems when applications define LFS macros
-- Set EXE to ".exe" in configure for MINGW [Kahle]
-- Match crc32() in crc32.c exactly to the prototype in zlib.h [Sherrill]
-- Add prefix for cross-compilation in win32/makefile.gcc [Bar-Lev]
-- Add DLL install in win32/makefile.gcc [Bar-Lev]
-- Allow Linux* or linux* from uname in configure [Bar-Lev]
-- Allow ldconfig to be redefined in configure and Makefile.in [Bar-Lev]
-- Add cross-compilation prefixes to configure [Bar-Lev]
-- Match type exactly in gz_load() invocation in gzread.c
-- Match type exactly of zcalloc() in zutil.c to zlib.h alloc_func
-- Provide prototypes for *64 functions when building zlib without LFS
-- Don't use -lc when linking shared library on MinGW
-- Remove errno.h check in configure and vestigial errno code in zutil.h
-
-Changes in 1.2.4 (14 Mar 2010)
-- Fix VER3 extraction in configure for no fourth subversion
-- Update zlib.3, add docs to Makefile.in to make .pdf out of it
-- Add zlib.3.pdf to distribution
-- Don't set error code in gzerror() if passed pointer is NULL
-- Apply destination directory fixes to CMakeLists.txt [Lowman]
-- Move #cmakedefine's to a new zconf.in.cmakein
-- Restore zconf.h for builds that don't use configure or cmake
-- Add distclean to dummy Makefile for convenience
-- Update and improve INDEX, README, and FAQ
-- Update CMakeLists.txt for the return of zconf.h [Lowman]
-- Update contrib/vstudio/vc9 and vc10 [Vollant]
-- Change libz.dll.a back to libzdll.a in win32/Makefile.gcc
-- Apply license and readme changes to contrib/asm686 [Raiter]
-- Check file name lengths and add -c option in minigzip.c [Li]
-- Update contrib/amd64 and contrib/masmx86/ [Vollant]
-- Avoid use of "eof" parameter in trees.c to not shadow library variable
-- Update make_vms.com for removal of zlibdefs.h [Zinser]
-- Update assembler code and vstudio projects in contrib [Vollant]
-- Remove outdated assembler code contrib/masm686 and contrib/asm586
-- Remove old vc7 and vc8 from contrib/vstudio
-- Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe]
-- Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open()
-- Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant]
-- Remove *64 functions from win32/zlib.def (they're not 64-bit yet)
-- Fix bug in void-returning vsprintf() case in gzwrite.c
-- Fix name change from inflate.h in contrib/inflate86/inffas86.c
-- Check if temporary file exists before removing in make_vms.com [Zinser]
-- Fix make install and uninstall for --static option
-- Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta]
-- Update readme.txt in contrib/masmx64 and masmx86 to assemble
-
-Changes in 1.2.3.9 (21 Feb 2010)
-- Expunge gzio.c
-- Move as400 build information to old
-- Fix updates in contrib/minizip and contrib/vstudio
-- Add const to vsnprintf test in configure to avoid warnings [Weigelt]
-- Delete zconf.h (made by configure) [Weigelt]
-- Change zconf.in.h to zconf.h.in per convention [Weigelt]
-- Check for NULL buf in gzgets()
-- Return empty string for gzgets() with len == 1 (like fgets())
-- Fix description of gzgets() in zlib.h for end-of-file, NULL return
-- Update minizip to 1.1 [Vollant]
-- Avoid MSVC loss of data warnings in gzread.c, gzwrite.c
-- Note in zlib.h that gzerror() should be used to distinguish from EOF
-- Remove use of snprintf() from gzlib.c
-- Fix bug in gzseek()
-- Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant]
-- Fix zconf.h generation in CMakeLists.txt [Lowman]
-- Improve comments in zconf.h where modified by configure
-
-Changes in 1.2.3.8 (13 Feb 2010)
-- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer]
-- Use z_off64_t in gz_zero() and gz_skip() to match state->skip
-- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t)
-- Revert to Makefile.in from 1.2.3.6 (live with the clutter)
-- Fix missing error return in gzflush(), add zlib.h note
-- Add *64 functions to zlib.map [Levin]
-- Fix signed/unsigned comparison in gz_comp()
-- Use SFLAGS when testing shared linking in configure
-- Add --64 option to ./configure to use -m64 with gcc
-- Fix ./configure --help to correctly name options
-- Have make fail if a test fails [Levin]
-- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson]
-- Remove assembler object files from contrib
-
-Changes in 1.2.3.7 (24 Jan 2010)
-- Always gzopen() with O_LARGEFILE if available
-- Fix gzdirect() to work immediately after gzopen() or gzdopen()
-- Make gzdirect() more precise when the state changes while reading
-- Improve zlib.h documentation in many places
-- Catch memory allocation failure in gz_open()
-- Complete close operation if seek forward in gzclose_w() fails
-- Return Z_ERRNO from gzclose_r() if close() fails
-- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL
-- Return zero for gzwrite() errors to match zlib.h description
-- Return -1 on gzputs() error to match zlib.h description
-- Add zconf.in.h to allow recovery from configure modification [Weigelt]
-- Fix static library permissions in Makefile.in [Weigelt]
-- Avoid warnings in configure tests that hide functionality [Weigelt]
-- Add *BSD and DragonFly to Linux case in configure [gentoo 123571]
-- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212]
-- Avoid access of uninitialized data for first inflateReset2 call [Gomes]
-- Keep object files in subdirectories to reduce the clutter somewhat
-- Remove default Makefile and zlibdefs.h, add dummy Makefile
-- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_
-- Remove zlibdefs.h completely -- modify zconf.h instead
-
-Changes in 1.2.3.6 (17 Jan 2010)
-- Avoid void * arithmetic in gzread.c and gzwrite.c
-- Make compilers happier with const char * for gz_error message
-- Avoid unused parameter warning in inflate.c
-- Avoid signed-unsigned comparison warning in inflate.c
-- Indent #pragma's for traditional C
-- Fix usage of strwinerror() in glib.c, change to gz_strwinerror()
-- Correct email address in configure for system options
-- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser]
-- Update zlib.map [Brown]
-- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Torok]
-- Apply various fixes to CMakeLists.txt [Lowman]
-- Add checks on len in gzread() and gzwrite()
-- Add error message for no more room for gzungetc()
-- Remove zlib version check in gzwrite()
-- Defer compression of gzprintf() result until need to
-- Use snprintf() in gzdopen() if available
-- Remove USE_MMAP configuration determination (only used by minigzip)
-- Remove examples/pigz.c (available separately)
-- Update examples/gun.c to 1.6
-
-Changes in 1.2.3.5 (8 Jan 2010)
-- Add space after #if in zutil.h for some compilers
-- Fix relatively harmless bug in deflate_fast() [Exarevsky]
-- Fix same problem in deflate_slow()
-- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown]
-- Add deflate_rle() for faster Z_RLE strategy run-length encoding
-- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding
-- Change name of "write" variable in inffast.c to avoid library collisions
-- Fix premature EOF from gzread() in gzio.c [Brown]
-- Use zlib header window size if windowBits is 0 in inflateInit2()
-- Remove compressBound() call in deflate.c to avoid linking compress.o
-- Replace use of errno in gz* with functions, support WinCE [Alves]
-- Provide alternative to perror() in minigzip.c for WinCE [Alves]
-- Don't use _vsnprintf on later versions of MSVC [Lowman]
-- Add CMake build script and input file [Lowman]
-- Update contrib/minizip to 1.1 [Svensson, Vollant]
-- Moved nintendods directory from contrib to .
-- Replace gzio.c with a new set of routines with the same functionality
-- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above
-- Update contrib/minizip to 1.1b
-- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h
-
-Changes in 1.2.3.4 (21 Dec 2009)
-- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility
-- Update comments in configure and Makefile.in for default --shared
-- Fix test -z's in configure [Marquess]
-- Build examplesh and minigzipsh when not testing
-- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h
-- Import LDFLAGS from the environment in configure
-- Fix configure to populate SFLAGS with discovered CFLAGS options
-- Adapt make_vms.com to the new Makefile.in [Zinser]
-- Add zlib2ansi script for C++ compilation [Marquess]
-- Add _FILE_OFFSET_BITS=64 test to make test (when applicable)
-- Add AMD64 assembler code for longest match to contrib [Teterin]
-- Include options from $SFLAGS when doing $LDSHARED
-- Simplify 64-bit file support by introducing z_off64_t type
-- Make shared object files in objs directory to work around old Sun cc
-- Use only three-part version number for Darwin shared compiles
-- Add rc option to ar in Makefile.in for when ./configure not run
-- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4*
-- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile
-- Protect against _FILE_OFFSET_BITS being defined when compiling zlib
-- Rename Makefile.in targets allstatic to static and allshared to shared
-- Fix static and shared Makefile.in targets to be independent
-- Correct error return bug in gz_open() by setting state [Brown]
-- Put spaces before ;;'s in configure for better sh compatibility
-- Add pigz.c (parallel implementation of gzip) to examples/
-- Correct constant in crc32.c to UL [Leventhal]
-- Reject negative lengths in crc32_combine()
-- Add inflateReset2() function to work like inflateEnd()/inflateInit2()
-- Include sys/types.h for _LARGEFILE64_SOURCE [Brown]
-- Correct typo in doc/algorithm.txt [Janik]
-- Fix bug in adler32_combine() [Zhu]
-- Catch missing-end-of-block-code error in all inflates and in puff
-    Assures that random input to inflate eventually results in an error
-- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/
-- Update ENOUGH and its usage to reflect discovered bounds
-- Fix gzerror() error report on empty input file [Brown]
-- Add ush casts in trees.c to avoid pedantic runtime errors
-- Fix typo in zlib.h uncompress() description [Reiss]
-- Correct inflate() comments with regard to automatic header detection
-- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays)
-- Put new version of gzlog (2.0) in examples with interruption recovery
-- Add puff compile option to permit invalid distance-too-far streams
-- Add puff TEST command options, ability to read piped input
-- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but
-  _LARGEFILE64_SOURCE not defined
-- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart
-- Fix deflateSetDictionary() to use all 32K for output consistency
-- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h)
-- Clear bytes after deflate lookahead to avoid use of uninitialized data
-- Change a limit in inftrees.c to be more transparent to Coverity Prevent
-- Update win32/zlib.def with exported symbols from zlib.h
-- Correct spelling errors in zlib.h [Willem, Sobrado]
-- Allow Z_BLOCK for deflate() to force a new block
-- Allow negative bits in inflatePrime() to delete existing bit buffer
-- Add Z_TREES flush option to inflate() to return at end of trees
-- Add inflateMark() to return current state information for random access
-- Add Makefile for NintendoDS to contrib [Costa]
-- Add -w in configure compile tests to avoid spurious warnings [Beucler]
-- Fix typos in zlib.h comments for deflateSetDictionary()
-- Fix EOF detection in transparent gzread() [Maier]
-
-Changes in 1.2.3.3 (2 October 2006)
-- Make --shared the default for configure, add a --static option
-- Add compile option to permit invalid distance-too-far streams
-- Add inflateUndermine() function which is required to enable above
-- Remove use of "this" variable name for C++ compatibility [Marquess]
-- Add testing of shared library in make test, if shared library built
-- Use ftello() and fseeko() if available instead of ftell() and fseek()
-- Provide two versions of all functions that use the z_off_t type for
-  binary compatibility -- a normal version and a 64-bit offset version,
-  per the Large File Support Extension when _LARGEFILE64_SOURCE is
-  defined; use the 64-bit versions by default when _FILE_OFFSET_BITS
-  is defined to be 64
-- Add a --uname= option to configure to perhaps help with cross-compiling
-
-Changes in 1.2.3.2 (3 September 2006)
-- Turn off silly Borland warnings [Hay]
-- Use off64_t and define _LARGEFILE64_SOURCE when present
-- Fix missing dependency on inffixed.h in Makefile.in
-- Rig configure --shared to build both shared and static [Teredesai, Truta]
-- Remove zconf.in.h and instead create a new zlibdefs.h file
-- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant]
-- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt]
-
-Changes in 1.2.3.1 (16 August 2006)
-- Add watcom directory with OpenWatcom make files [Daniel]
-- Remove #undef of FAR in zconf.in.h for MVS [Fedtke]
-- Update make_vms.com [Zinser]
-- Use -fPIC for shared build in configure [Teredesai, Nicholson]
-- Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen]
-- Use fdopen() (not _fdopen()) for Interix in zutil.h [BŠck]
-- Add some FAQ entries about the contrib directory
-- Update the MVS question in the FAQ
-- Avoid extraneous reads after EOF in gzio.c [Brown]
-- Correct spelling of "successfully" in gzio.c [Randers-Pehrson]
-- Add comments to zlib.h about gzerror() usage [Brown]
-- Set extra flags in gzip header in gzopen() like deflate() does
-- Make configure options more compatible with double-dash conventions
-  [Weigelt]
-- Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen]
-- Fix uninstall target in Makefile.in [Truta]
-- Add pkgconfig support [Weigelt]
-- Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt]
-- Replace set_data_type() with a more accurate detect_data_type() in
-  trees.c, according to the txtvsbin.txt document [Truta]
-- Swap the order of #include <stdio.h> and #include "zlib.h" in
-  gzio.c, example.c and minigzip.c [Truta]
-- Shut up annoying VS2005 warnings about standard C deprecation [Rowe,
-  Truta] (where?)
-- Fix target "clean" from win32/Makefile.bor [Truta]
-- Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe]
-- Update zlib www home address in win32/DLL_FAQ.txt [Truta]
-- Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove]
-- Enable browse info in the "Debug" and "ASM Debug" configurations in
-  the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta]
-- Add pkgconfig support [Weigelt]
-- Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h,
-  for use in win32/zlib1.rc [Polushin, Rowe, Truta]
-- Add a document that explains the new text detection scheme to
-  doc/txtvsbin.txt [Truta]
-- Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta]
-- Move algorithm.txt into doc/ [Truta]
-- Synchronize FAQ with website
-- Fix compressBound(), was low for some pathological cases [Fearnley]
-- Take into account wrapper variations in deflateBound()
-- Set examples/zpipe.c input and output to binary mode for Windows
-- Update examples/zlib_how.html with new zpipe.c (also web site)
-- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems
-  that gcc became pickier in 4.0)
-- Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain
-  un-versioned, the patch adds versioning only for symbols introduced in
-  zlib-1.2.0 or later.  It also declares as local those symbols which are
-  not designed to be exported." [Levin]
-- Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure
-- Do not initialize global static by default in trees.c, add a response
-  NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess]
-- Don't use strerror() in gzio.c under WinCE [Yakimov]
-- Don't use errno.h in zutil.h under WinCE [Yakimov]
-- Move arguments for AR to its usage to allow replacing ar [Marot]
-- Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson]
-- Improve inflateInit() and inflateInit2() documentation
-- Fix structure size comment in inflate.h
-- Change configure help option from --h* to --help [Santos]
-
-Changes in 1.2.3 (18 July 2005)
-- Apply security vulnerability fixes to contrib/infback9 as well
-- Clean up some text files (carriage returns, trailing space)
-- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant]
-
-Changes in 1.2.2.4 (11 July 2005)
-- Add inflatePrime() function for starting inflation at bit boundary
-- Avoid some Visual C warnings in deflate.c
-- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit
-  compile
-- Fix some spelling errors in comments [Betts]
-- Correct inflateInit2() error return documentation in zlib.h
-- Add zran.c example of compressed data random access to examples
-  directory, shows use of inflatePrime()
-- Fix cast for assignments to strm->state in inflate.c and infback.c
-- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer]
-- Move declarations of gf2 functions to right place in crc32.c [Oberhumer]
-- Add cast in trees.c t avoid a warning [Oberhumer]
-- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer]
-- Update make_vms.com [Zinser]
-- Initialize state->write in inflateReset() since copied in inflate_fast()
-- Be more strict on incomplete code sets in inflate_table() and increase
-  ENOUGH and MAXD -- this repairs a possible security vulnerability for
-  invalid inflate input.  Thanks to Tavis Ormandy and Markus Oberhumer for
-  discovering the vulnerability and providing test cases.
-- Add ia64 support to configure for HP-UX [Smith]
-- Add error return to gzread() for format or i/o error [Levin]
-- Use malloc.h for OS/2 [Necasek]
-
-Changes in 1.2.2.3 (27 May 2005)
-- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile
-- Typecast fread() return values in gzio.c [Vollant]
-- Remove trailing space in minigzip.c outmode (VC++ can't deal with it)
-- Fix crc check bug in gzread() after gzungetc() [Heiner]
-- Add the deflateTune() function to adjust internal compression parameters
-- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack)
-- Remove an incorrect assertion in examples/zpipe.c
-- Add C++ wrapper in infback9.h [Donais]
-- Fix bug in inflateCopy() when decoding fixed codes
-- Note in zlib.h how much deflateSetDictionary() actually uses
-- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used)
-- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer]
-- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer]
-- Add gzdirect() function to indicate transparent reads
-- Update contrib/minizip [Vollant]
-- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer]
-- Add casts in crc32.c to avoid warnings [Oberhumer]
-- Add contrib/masmx64 [Vollant]
-- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant]
-
-Changes in 1.2.2.2 (30 December 2004)
-- Replace structure assignments in deflate.c and inflate.c with zmemcpy to
-  avoid implicit memcpy calls (portability for no-library compilation)
-- Increase sprintf() buffer size in gzdopen() to allow for large numbers
-- Add INFLATE_STRICT to check distances against zlib header
-- Improve WinCE errno handling and comments [Chang]
-- Remove comment about no gzip header processing in FAQ
-- Add Z_FIXED strategy option to deflateInit2() to force fixed trees
-- Add updated make_vms.com [Coghlan], update README
-- Create a new "examples" directory, move gzappend.c there, add zpipe.c,
-  fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html.
-- Add FAQ entry and comments in deflate.c on uninitialized memory access
-- Add Solaris 9 make options in configure [Gilbert]
-- Allow strerror() usage in gzio.c for STDC
-- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer]
-- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant]
-- Use z_off_t for adler32_combine() and crc32_combine() lengths
-- Make adler32() much faster for small len
-- Use OS_CODE in deflate() default gzip header
-
-Changes in 1.2.2.1 (31 October 2004)
-- Allow inflateSetDictionary() call for raw inflate
-- Fix inflate header crc check bug for file names and comments
-- Add deflateSetHeader() and gz_header structure for custom gzip headers
-- Add inflateGetheader() to retrieve gzip headers
-- Add crc32_combine() and adler32_combine() functions
-- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list
-- Use zstreamp consistently in zlib.h (inflate_back functions)
-- Remove GUNZIP condition from definition of inflate_mode in inflate.h
-  and in contrib/inflate86/inffast.S [Truta, Anderson]
-- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson]
-- Update projects/README.projects and projects/visualc6 [Truta]
-- Update win32/DLL_FAQ.txt [Truta]
-- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta]
-- Deprecate Z_ASCII; use Z_TEXT instead [Truta]
-- Use a new algorithm for setting strm->data_type in trees.c [Truta]
-- Do not define an exit() prototype in zutil.c unless DEBUG defined
-- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta]
-- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate()
-- Fix Darwin build version identification [Peterson]
-
-Changes in 1.2.2 (3 October 2004)
-- Update zlib.h comments on gzip in-memory processing
-- Set adler to 1 in inflateReset() to support Java test suite [Walles]
-- Add contrib/dotzlib [Ravn]
-- Update win32/DLL_FAQ.txt [Truta]
-- Update contrib/minizip [Vollant]
-- Move contrib/visual-basic.txt to old/ [Truta]
-- Fix assembler builds in projects/visualc6/ [Truta]
-
-Changes in 1.2.1.2 (9 September 2004)
-- Update INDEX file
-- Fix trees.c to update strm->data_type (no one ever noticed!)
-- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown]
-- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE)
-- Add limited multitasking protection to DYNAMIC_CRC_TABLE
-- Add NO_vsnprintf for VMS in zutil.h [Mozilla]
-- Don't declare strerror() under VMS [Mozilla]
-- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize
-- Update contrib/ada [Anisimkov]
-- Update contrib/minizip [Vollant]
-- Fix configure to not hardcode directories for Darwin [Peterson]
-- Fix gzio.c to not return error on empty files [Brown]
-- Fix indentation; update version in contrib/delphi/ZLib.pas and
-  contrib/pascal/zlibpas.pas [Truta]
-- Update mkasm.bat in contrib/masmx86 [Truta]
-- Update contrib/untgz [Truta]
-- Add projects/README.projects [Truta]
-- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta]
-- Update win32/DLL_FAQ.txt [Truta]
-- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta]
-- Remove an unnecessary assignment to curr in inftrees.c [Truta]
-- Add OS/2 to exe builds in configure [Poltorak]
-- Remove err dummy parameter in zlib.h [Kientzle]
-
-Changes in 1.2.1.1 (9 January 2004)
-- Update email address in README
-- Several FAQ updates
-- Fix a big fat bug in inftrees.c that prevented decoding valid
-  dynamic blocks with only literals and no distance codes --
-  Thanks to "Hot Emu" for the bug report and sample file
-- Add a note to puff.c on no distance codes case.
-
-Changes in 1.2.1 (17 November 2003)
-- Remove a tab in contrib/gzappend/gzappend.c
-- Update some interfaces in contrib for new zlib functions
-- Update zlib version number in some contrib entries
-- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta]
-- Support shared libraries on Hurd and KFreeBSD [Brown]
-- Fix error in NO_DIVIDE option of adler32.c
-
-Changes in 1.2.0.8 (4 November 2003)
-- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas
-- Add experimental NO_DIVIDE #define in adler32.c
-    - Possibly faster on some processors (let me know if it is)
-- Correct Z_BLOCK to not return on first inflate call if no wrap
-- Fix strm->data_type on inflate() return to correctly indicate EOB
-- Add deflatePrime() function for appending in the middle of a byte
-- Add contrib/gzappend for an example of appending to a stream
-- Update win32/DLL_FAQ.txt [Truta]
-- Delete Turbo C comment in README [Truta]
-- Improve some indentation in zconf.h [Truta]
-- Fix infinite loop on bad input in configure script [Church]
-- Fix gzeof() for concatenated gzip files [Johnson]
-- Add example to contrib/visual-basic.txt [Michael B.]
-- Add -p to mkdir's in Makefile.in [vda]
-- Fix configure to properly detect presence or lack of printf functions
-- Add AS400 support [Monnerat]
-- Add a little Cygwin support [Wilson]
-
-Changes in 1.2.0.7 (21 September 2003)
-- Correct some debug formats in contrib/infback9
-- Cast a type in a debug statement in trees.c
-- Change search and replace delimiter in configure from % to # [Beebe]
-- Update contrib/untgz to 0.2 with various fixes [Truta]
-- Add build support for Amiga [Nikl]
-- Remove some directories in old that have been updated to 1.2
-- Add dylib building for Mac OS X in configure and Makefile.in
-- Remove old distribution stuff from Makefile
-- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X
-- Update links in README
-
-Changes in 1.2.0.6 (13 September 2003)
-- Minor FAQ updates
-- Update contrib/minizip to 1.00 [Vollant]
-- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta]
-- Update POSTINC comment for 68060 [Nikl]
-- Add contrib/infback9 with deflate64 decoding (unsupported)
-- For MVS define NO_vsnprintf and undefine FAR [van Burik]
-- Add pragma for fdopen on MVS [van Burik]
-
-Changes in 1.2.0.5 (8 September 2003)
-- Add OF to inflateBackEnd() declaration in zlib.h
-- Remember start when using gzdopen in the middle of a file
-- Use internal off_t counters in gz* functions to properly handle seeks
-- Perform more rigorous check for distance-too-far in inffast.c
-- Add Z_BLOCK flush option to return from inflate at block boundary
-- Set strm->data_type on return from inflate
-    - Indicate bits unused, if at block boundary, and if in last block
-- Replace size_t with ptrdiff_t in crc32.c, and check for correct size
-- Add condition so old NO_DEFLATE define still works for compatibility
-- FAQ update regarding the Windows DLL [Truta]
-- INDEX update: add qnx entry, remove aix entry [Truta]
-- Install zlib.3 into mandir [Wilson]
-- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta]
-- Adapt the zlib interface to the new DLL convention guidelines [Truta]
-- Introduce ZLIB_WINAPI macro to allow the export of functions using
-  the WINAPI calling convention, for Visual Basic [Vollant, Truta]
-- Update msdos and win32 scripts and makefiles [Truta]
-- Export symbols by name, not by ordinal, in win32/zlib.def [Truta]
-- Add contrib/ada [Anisimkov]
-- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta]
-- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant]
-- Add contrib/masm686 [Truta]
-- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm
-  [Truta, Vollant]
-- Update contrib/delphi; rename to contrib/pascal; add example [Truta]
-- Remove contrib/delphi2; add a new contrib/delphi [Truta]
-- Avoid inclusion of the nonstandard <memory.h> in contrib/iostream,
-  and fix some method prototypes [Truta]
-- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip
-  [Truta]
-- Avoid the use of backslash (\) in contrib/minizip [Vollant]
-- Fix file time handling in contrib/untgz; update makefiles [Truta]
-- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines
-  [Vollant]
-- Remove contrib/vstudio/vc15_16 [Vollant]
-- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta]
-- Update README.contrib [Truta]
-- Invert the assignment order of match_head and s->prev[...] in
-  INSERT_STRING [Truta]
-- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings
-  [Truta]
-- Compare function pointers with 0, not with NULL or Z_NULL [Truta]
-- Fix prototype of syncsearch in inflate.c [Truta]
-- Introduce ASMINF macro to be enabled when using an ASM implementation
-  of inflate_fast [Truta]
-- Change NO_DEFLATE to NO_GZCOMPRESS [Truta]
-- Modify test_gzio in example.c to take a single file name as a
-  parameter [Truta]
-- Exit the example.c program if gzopen fails [Truta]
-- Add type casts around strlen in example.c [Truta]
-- Remove casting to sizeof in minigzip.c; give a proper type
-  to the variable compared with SUFFIX_LEN [Truta]
-- Update definitions of STDC and STDC99 in zconf.h [Truta]
-- Synchronize zconf.h with the new Windows DLL interface [Truta]
-- Use SYS16BIT instead of __32BIT__ to distinguish between
-  16- and 32-bit platforms [Truta]
-- Use far memory allocators in small 16-bit memory models for
-  Turbo C [Truta]
-- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in
-  zlibCompileFlags [Truta]
-- Cygwin has vsnprintf [Wilson]
-- In Windows16, OS_CODE is 0, as in MSDOS [Truta]
-- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson]
-
-Changes in 1.2.0.4 (10 August 2003)
-- Minor FAQ updates
-- Be more strict when checking inflateInit2's windowBits parameter
-- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well
-- Add gzip wrapper option to deflateInit2 using windowBits
-- Add updated QNX rule in configure and qnx directory [Bonnefoy]
-- Make inflate distance-too-far checks more rigorous
-- Clean up FAR usage in inflate
-- Add casting to sizeof() in gzio.c and minigzip.c
-
-Changes in 1.2.0.3 (19 July 2003)
-- Fix silly error in gzungetc() implementation [Vollant]
-- Update contrib/minizip and contrib/vstudio [Vollant]
-- Fix printf format in example.c
-- Correct cdecl support in zconf.in.h [Anisimkov]
-- Minor FAQ updates
-
-Changes in 1.2.0.2 (13 July 2003)
-- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons
-- Attempt to avoid warnings in crc32.c for pointer-int conversion
-- Add AIX to configure, remove aix directory [Bakker]
-- Add some casts to minigzip.c
-- Improve checking after insecure sprintf() or vsprintf() calls
-- Remove #elif's from crc32.c
-- Change leave label to inf_leave in inflate.c and infback.c to avoid
-  library conflicts
-- Remove inflate gzip decoding by default--only enable gzip decoding by
-  special request for stricter backward compatibility
-- Add zlibCompileFlags() function to return compilation information
-- More typecasting in deflate.c to avoid warnings
-- Remove leading underscore from _Capital #defines [Truta]
-- Fix configure to link shared library when testing
-- Add some Windows CE target adjustments [Mai]
-- Remove #define ZLIB_DLL in zconf.h [Vollant]
-- Add zlib.3 [Rodgers]
-- Update RFC URL in deflate.c and algorithm.txt [Mai]
-- Add zlib_dll_FAQ.txt to contrib [Truta]
-- Add UL to some constants [Truta]
-- Update minizip and vstudio [Vollant]
-- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h
-- Expand use of NO_DUMMY_DECL to avoid all dummy structures
-- Added iostream3 to contrib [Schwardt]
-- Replace rewind() with fseek() for WinCE [Truta]
-- Improve setting of zlib format compression level flags
-    - Report 0 for huffman and rle strategies and for level == 0 or 1
-    - Report 2 only for level == 6
-- Only deal with 64K limit when necessary at compile time [Truta]
-- Allow TOO_FAR check to be turned off at compile time [Truta]
-- Add gzclearerr() function [Souza]
-- Add gzungetc() function
-
-Changes in 1.2.0.1 (17 March 2003)
-- Add Z_RLE strategy for run-length encoding [Truta]
-    - When Z_RLE requested, restrict matches to distance one
-    - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE
-- Correct FASTEST compilation to allow level == 0
-- Clean up what gets compiled for FASTEST
-- Incorporate changes to zconf.in.h [Vollant]
-    - Refine detection of Turbo C need for dummy returns
-    - Refine ZLIB_DLL compilation
-    - Include additional header file on VMS for off_t typedef
-- Try to use _vsnprintf where it supplants vsprintf [Vollant]
-- Add some casts in inffast.c
-- Enchance comments in zlib.h on what happens if gzprintf() tries to
-  write more than 4095 bytes before compression
-- Remove unused state from inflateBackEnd()
-- Remove exit(0) from minigzip.c, example.c
-- Get rid of all those darn tabs
-- Add "check" target to Makefile.in that does the same thing as "test"
-- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in
-- Update contrib/inflate86 [Anderson]
-- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant]
-- Add msdos and win32 directories with makefiles [Truta]
-- More additions and improvements to the FAQ
-
-Changes in 1.2.0 (9 March 2003)
-- New and improved inflate code
-    - About 20% faster
-    - Does not allocate 32K window unless and until needed
-    - Automatically detects and decompresses gzip streams
-    - Raw inflate no longer needs an extra dummy byte at end
-    - Added inflateBack functions using a callback interface--even faster
-      than inflate, useful for file utilities (gzip, zip)
-    - Added inflateCopy() function to record state for random access on
-      externally generated deflate streams (e.g. in gzip files)
-    - More readable code (I hope)
-- New and improved crc32()
-    - About 50% faster, thanks to suggestions from Rodney Brown
-- Add deflateBound() and compressBound() functions
-- Fix memory leak in deflateInit2()
-- Permit setting dictionary for raw deflate (for parallel deflate)
-- Fix const declaration for gzwrite()
-- Check for some malloc() failures in gzio.c
-- Fix bug in gzopen() on single-byte file 0x1f
-- Fix bug in gzread() on concatenated file with 0x1f at end of buffer
-  and next buffer doesn't start with 0x8b
-- Fix uncompress() to return Z_DATA_ERROR on truncated input
-- Free memory at end of example.c
-- Remove MAX #define in trees.c (conflicted with some libraries)
-- Fix static const's in deflate.c, gzio.c, and zutil.[ch]
-- Declare malloc() and free() in gzio.c if STDC not defined
-- Use malloc() instead of calloc() in zutil.c if int big enough
-- Define STDC for AIX
-- Add aix/ with approach for compiling shared library on AIX
-- Add HP-UX support for shared libraries in configure
-- Add OpenUNIX support for shared libraries in configure
-- Use $cc instead of gcc to build shared library
-- Make prefix directory if needed when installing
-- Correct Macintosh avoidance of typedef Byte in zconf.h
-- Correct Turbo C memory allocation when under Linux
-- Use libz.a instead of -lz in Makefile (assure use of compiled library)
-- Update configure to check for snprintf or vsnprintf functions and their
-  return value, warn during make if using an insecure function
-- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that
-  is lost when library is used--resolution is to build new zconf.h
-- Documentation improvements (in zlib.h):
-    - Document raw deflate and inflate
-    - Update RFCs URL
-    - Point out that zlib and gzip formats are different
-    - Note that Z_BUF_ERROR is not fatal
-    - Document string limit for gzprintf() and possible buffer overflow
-    - Note requirement on avail_out when flushing
-    - Note permitted values of flush parameter of inflate()
-- Add some FAQs (and even answers) to the FAQ
-- Add contrib/inflate86/ for x86 faster inflate
-- Add contrib/blast/ for PKWare Data Compression Library decompression
-- Add contrib/puff/ simple inflate for deflate format description
-
-Changes in 1.1.4 (11 March 2002)
-- ZFREE was repeated on same allocation on some error conditions.
-  This creates a security problem described in
-  http://www.zlib.org/advisory-2002-03-11.txt
-- Returned incorrect error (Z_MEM_ERROR) on some invalid data
-- Avoid accesses before window for invalid distances with inflate window
-  less than 32K.
-- force windowBits > 8 to avoid a bug in the encoder for a window size
-  of 256 bytes. (A complete fix will be available in 1.1.5).
-
-Changes in 1.1.3 (9 July 1998)
-- fix "an inflate input buffer bug that shows up on rare but persistent
-  occasions" (Mark)
-- fix gzread and gztell for concatenated .gz files (Didier Le Botlan)
-- fix gzseek(..., SEEK_SET) in write mode
-- fix crc check after a gzeek (Frank Faubert)
-- fix miniunzip when the last entry in a zip file is itself a zip file
-  (J Lillge)
-- add contrib/asm586 and contrib/asm686 (Brian Raiter)
-  See http://www.muppetlabs.com/~breadbox/software/assembly.html
-- add support for Delphi 3 in contrib/delphi (Bob Dellaca)
-- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti)
-- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren)
-- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks)
-- added a FAQ file
-
-- Support gzdopen on Mac with Metrowerks (Jason Linhart)
-- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart)
-- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young)
-- avoid some warnings with Borland C (Tom Tanner)
-- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant)
-- emulate utime() for WIN32 in contrib/untgz  (Gilles Vollant)
-- allow several arguments to configure (Tim Mooney, Frodo Looijaard)
-- use libdir and includedir in Makefile.in (Tim Mooney)
-- support shared libraries on OSF1 V4 (Tim Mooney)
-- remove so_locations in "make clean"  (Tim Mooney)
-- fix maketree.c compilation error (Glenn, Mark)
-- Python interface to zlib now in Python 1.5 (Jeremy Hylton)
-- new Makefile.riscos (Rich Walker)
-- initialize static descriptors in trees.c for embedded targets (Nick Smith)
-- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith)
-- add the OS/2 files in Makefile.in too (Andrew Zabolotny)
-- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane)
-- fix maketree.c to allow clean compilation of inffixed.h (Mark)
-- fix parameter check in deflateCopy (Gunther Nikl)
-- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler)
-- Many portability patches by Christian Spieler:
-  . zutil.c, zutil.h: added "const" for zmem*
-  . Make_vms.com: fixed some typos
-  . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists
-  . msdos/Makefile.msc: remove "default rtl link library" info from obj files
-  . msdos/Makefile.*: use model-dependent name for the built zlib library
-  . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc:
-     new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT)
-- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane)
-- replace __far with _far for better portability (Christian Spieler, Tom Lane)
-- fix test for errno.h in configure (Tim Newsham)
-
-Changes in 1.1.2 (19 March 98)
-- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant)
-  See http://www.winimage.com/zLibDll/unzip.html
-- preinitialize the inflate tables for fixed codes, to make the code
-  completely thread safe (Mark)
-- some simplifications and slight speed-up to the inflate code (Mark)
-- fix gzeof on non-compressed files (Allan Schrum)
-- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs)
-- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn)
-- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny)
-- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori)
-- do not wrap extern "C" around system includes (Tom Lane)
-- mention zlib binding for TCL in README (Andreas Kupries)
-- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert)
-- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson)
-- allow "configure --prefix $HOME" (Tim Mooney)
-- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson)
-- move Makefile.sas to amiga/Makefile.sas
-
-Changes in 1.1.1 (27 Feb 98)
-- fix macros _tr_tally_* in deflate.h for debug mode  (Glenn Randers-Pehrson)
-- remove block truncation heuristic which had very marginal effect for zlib
-  (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the
-  compression ratio on some files. This also allows inlining _tr_tally for
-  matches in deflate_slow.
-- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier)
-
-Changes in 1.1.0 (24 Feb 98)
-- do not return STREAM_END prematurely in inflate (John Bowler)
-- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler)
-- compile with -DFASTEST to get compression code optimized for speed only
-- in minigzip, try mmap'ing the input file first (Miguel Albrecht)
-- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain
-  on Sun but significant on HP)
-
-- add a pointer to experimental unzip library in README (Gilles Vollant)
-- initialize variable gcc in configure (Chris Herborth)
-
-Changes in 1.0.9 (17 Feb 1998)
-- added gzputs and gzgets functions
-- do not clear eof flag in gzseek (Mark Diekhans)
-- fix gzseek for files in transparent mode (Mark Diekhans)
-- do not assume that vsprintf returns the number of bytes written (Jens Krinke)
-- replace EXPORT with ZEXPORT to avoid conflict with other programs
-- added compress2 in zconf.h, zlib.def, zlib.dnt
-- new asm code from Gilles Vollant in contrib/asm386
-- simplify the inflate code (Mark):
- . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new()
- . ZALLOC the length list in inflate_trees_fixed() instead of using stack
- . ZALLOC the value area for huft_build() instead of using stack
- . Simplify Z_FINISH check in inflate()
-
-- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8
-- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi)
-- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with
-  the declaration of FAR (Gilles VOllant)
-- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann)
-- read_buf buf parameter of type Bytef* instead of charf*
-- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout)
-- do not redeclare unlink in minigzip.c for WIN32 (John Bowler)
-- fix check for presence of directories in "make install" (Ian Willis)
-
-Changes in 1.0.8 (27 Jan 1998)
-- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant)
-- fix gzgetc and gzputc for big endian systems (Markus Oberhumer)
-- added compress2() to allow setting the compression level
-- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong)
-- use constant arrays for the static trees in trees.c instead of computing
-  them at run time (thanks to Ken Raeburn for this suggestion). To create
-  trees.h, compile with GEN_TREES_H and run "make test".
-- check return code of example in "make test" and display result
-- pass minigzip command line options to file_compress
-- simplifying code of inflateSync to avoid gcc 2.8 bug
-
-- support CC="gcc -Wall" in configure -s (QingLong)
-- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn)
-- fix test for shared library support to avoid compiler warnings
-- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant)
-- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit)
-- do not use fdopen for Metrowerks on Mac (Brad Pettit))
-- add checks for gzputc and gzputc in example.c
-- avoid warnings in gzio.c and deflate.c (Andreas Kleinert)
-- use const for the CRC table (Ken Raeburn)
-- fixed "make uninstall" for shared libraries
-- use Tracev instead of Trace in infblock.c
-- in example.c use correct compressed length for test_sync
-- suppress +vnocompatwarnings in configure for HPUX (not always supported)
-
-Changes in 1.0.7 (20 Jan 1998)
-- fix gzseek which was broken in write mode
-- return error for gzseek to negative absolute position
-- fix configure for Linux (Chun-Chung Chen)
-- increase stack space for MSC (Tim Wegner)
-- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant)
-- define EXPORTVA for gzprintf (Gilles Vollant)
-- added man page zlib.3 (Rick Rodgers)
-- for contrib/untgz, fix makedir() and improve Makefile
-
-- check gzseek in write mode in example.c
-- allocate extra buffer for seeks only if gzseek is actually called
-- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant)
-- add inflateSyncPoint in zconf.h
-- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def
-
-Changes in 1.0.6 (19 Jan 1998)
-- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and
-  gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code)
-- Fix a deflate bug occurring only with compression level 0 (thanks to
-  Andy Buckler for finding this one).
-- In minigzip, pass transparently also the first byte for .Z files.
-- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress()
-- check Z_FINISH in inflate (thanks to Marc Schluper)
-- Implement deflateCopy (thanks to Adam Costello)
-- make static libraries by default in configure, add --shared option.
-- move MSDOS or Windows specific files to directory msdos
-- suppress the notion of partial flush to simplify the interface
-  (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4)
-- suppress history buffer provided by application to simplify the interface
-  (this feature was not implemented anyway in 1.0.4)
-- next_in and avail_in must be initialized before calling inflateInit or
-  inflateInit2
-- add EXPORT in all exported functions (for Windows DLL)
-- added Makefile.nt (thanks to Stephen Williams)
-- added the unsupported "contrib" directory:
-   contrib/asm386/ by Gilles Vollant <info@winimage.com>
-        386 asm code replacing longest_match().
-   contrib/iostream/ by Kevin Ruland <kevin@rodin.wustl.edu>
-        A C++ I/O streams interface to the zlib gz* functions
-   contrib/iostream2/  by Tyge Løvset <Tyge.Lovset@cmr.no>
-        Another C++ I/O streams interface
-   contrib/untgz/  by "Pedro A. Aranda Guti\irrez" <paag@tid.es>
-        A very simple tar.gz file extractor using zlib
-   contrib/visual-basic.txt by Carlos Rios <c_rios@sonda.cl>
-        How to use compress(), uncompress() and the gz* functions from VB.
-- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression
-  level) in minigzip (thanks to Tom Lane)
-
-- use const for rommable constants in deflate
-- added test for gzseek and gztell in example.c
-- add undocumented function inflateSyncPoint() (hack for Paul Mackerras)
-- add undocumented function zError to convert error code to string
-  (for Tim Smithers)
-- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code.
-- Use default memcpy for Symantec MSDOS compiler.
-- Add EXPORT keyword for check_func (needed for Windows DLL)
-- add current directory to LD_LIBRARY_PATH for "make test"
-- create also a link for libz.so.1
-- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura)
-- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX)
-- added -soname for Linux in configure (Chun-Chung Chen,
-- assign numbers to the exported functions in zlib.def (for Windows DLL)
-- add advice in zlib.h for best usage of deflateSetDictionary
-- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn)
-- allow compilation with ANSI keywords only enabled for TurboC in large model
-- avoid "versionString"[0] (Borland bug)
-- add NEED_DUMMY_RETURN for Borland
-- use variable z_verbose for tracing in debug mode (L. Peter Deutsch).
-- allow compilation with CC
-- defined STDC for OS/2 (David Charlap)
-- limit external names to 8 chars for MVS (Thomas Lund)
-- in minigzip.c, use static buffers only for 16-bit systems
-- fix suffix check for "minigzip -d foo.gz"
-- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee)
-- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau)
-- added makelcc.bat for lcc-win32 (Tom St Denis)
-- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe)
-- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion.
-- check for unistd.h in configure (for off_t)
-- remove useless check parameter in inflate_blocks_free
-- avoid useless assignment of s->check to itself in inflate_blocks_new
-- do not flush twice in gzclose (thanks to Ken Raeburn)
-- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h
-- use NO_ERRNO_H instead of enumeration of operating systems with errno.h
-- work around buggy fclose on pipes for HP/UX
-- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson)
-- fix configure if CC is already equal to gcc
-
-Changes in 1.0.5 (3 Jan 98)
-- Fix inflate to terminate gracefully when fed corrupted or invalid data
-- Use const for rommable constants in inflate
-- Eliminate memory leaks on error conditions in inflate
-- Removed some vestigial code in inflate
-- Update web address in README
-
-Changes in 1.0.4 (24 Jul 96)
-- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF
-  bit, so the decompressor could decompress all the correct data but went
-  on to attempt decompressing extra garbage data. This affected minigzip too.
-- zlibVersion and gzerror return const char* (needed for DLL)
-- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno)
-- use z_error only for DEBUG (avoid problem with DLLs)
-
-Changes in 1.0.3 (2 Jul 96)
-- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS
-  small and medium models; this makes the library incompatible with previous
-  versions for these models. (No effect in large model or on other systems.)
-- return OK instead of BUF_ERROR if previous deflate call returned with
-  avail_out as zero but there is nothing to do
-- added memcmp for non STDC compilers
-- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly)
-- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO)
-- better check for 16-bit mode MSC (avoids problem with Symantec)
-
-Changes in 1.0.2 (23 May 96)
-- added Windows DLL support
-- added a function zlibVersion (for the DLL support)
-- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model)
-- Bytef is define's instead of typedef'd only for Borland C
-- avoid reading uninitialized memory in example.c
-- mention in README that the zlib format is now RFC1950
-- updated Makefile.dj2
-- added algorithm.doc
-
-Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion]
-- fix array overlay in deflate.c which sometimes caused bad compressed data
-- fix inflate bug with empty stored block
-- fix MSDOS medium model which was broken in 0.99
-- fix deflateParams() which could generated bad compressed data.
-- Bytef is define'd instead of typedef'ed (work around Borland bug)
-- added an INDEX file
-- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32),
-  Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas)
-- speed up adler32 for modern machines without auto-increment
-- added -ansi for IRIX in configure
-- static_init_done in trees.c is an int
-- define unlink as delete for VMS
-- fix configure for QNX
-- add configure branch for SCO and HPUX
-- avoid many warnings (unused variables, dead assignments, etc...)
-- no fdopen for BeOS
-- fix the Watcom fix for 32 bit mode (define FAR as empty)
-- removed redefinition of Byte for MKWERKS
-- work around an MWKERKS bug (incorrect merge of all .h files)
-
-Changes in 0.99 (27 Jan 96)
-- allow preset dictionary shared between compressor and decompressor
-- allow compression level 0 (no compression)
-- add deflateParams in zlib.h: allow dynamic change of compression level
-  and compression strategy.
-- test large buffers and deflateParams in example.c
-- add optional "configure" to build zlib as a shared library
-- suppress Makefile.qnx, use configure instead
-- fixed deflate for 64-bit systems (detected on Cray)
-- fixed inflate_blocks for 64-bit systems (detected on Alpha)
-- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2)
-- always return Z_BUF_ERROR when deflate() has nothing to do
-- deflateInit and inflateInit are now macros to allow version checking
-- prefix all global functions and types with z_ with -DZ_PREFIX
-- make falloc completely reentrant (inftrees.c)
-- fixed very unlikely race condition in ct_static_init
-- free in reverse order of allocation to help memory manager
-- use zlib-1.0/* instead of zlib/* inside the tar.gz
-- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith
-  -Wconversion -Wstrict-prototypes -Wmissing-prototypes"
-- allow gzread on concatenated .gz files
-- deflateEnd now returns Z_DATA_ERROR if it was premature
-- deflate is finally (?) fully deterministic (no matches beyond end of input)
-- Document Z_SYNC_FLUSH
-- add uninstall in Makefile
-- Check for __cpluplus in zlib.h
-- Better test in ct_align for partial flush
-- avoid harmless warnings for Borland C++
-- initialize hash_head in deflate.c
-- avoid warning on fdopen (gzio.c) for HP cc -Aa
-- include stdlib.h for STDC compilers
-- include errno.h for Cray
-- ignore error if ranlib doesn't exist
-- call ranlib twice for NeXTSTEP
-- use exec_prefix instead of prefix for libz.a
-- renamed ct_* as _tr_* to avoid conflict with applications
-- clear z->msg in inflateInit2 before any error return
-- initialize opaque in example.c, gzio.c, deflate.c and inflate.c
-- fixed typo in zconf.h (_GNUC__ => __GNUC__)
-- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode)
-- fix typo in Make_vms.com (f$trnlnm -> f$getsyi)
-- in fcalloc, normalize pointer if size > 65520 bytes
-- don't use special fcalloc for 32 bit Borland C++
-- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc...
-- use Z_BINARY instead of BINARY
-- document that gzclose after gzdopen will close the file
-- allow "a" as mode in gzopen.
-- fix error checking in gzread
-- allow skipping .gz extra-field on pipes
-- added reference to Perl interface in README
-- put the crc table in FAR data (I dislike more and more the medium model :)
-- added get_crc_table
-- added a dimension to all arrays (Borland C can't count).
-- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast
-- guard against multiple inclusion of *.h (for precompiled header on Mac)
-- Watcom C pretends to be Microsoft C small model even in 32 bit mode.
-- don't use unsized arrays to avoid silly warnings by Visual C++:
-     warning C4746: 'inflate_mask' : unsized array treated as  '__far'
-     (what's wrong with far data in far model?).
-- define enum out of inflate_blocks_state to allow compilation with C++
-
-Changes in 0.95 (16 Aug 95)
-- fix MSDOS small and medium model (now easier to adapt to any compiler)
-- inlined send_bits
-- fix the final (:-) bug for deflate with flush (output was correct but
-  not completely flushed in rare occasions).
-- default window size is same for compression and decompression
-  (it's now sufficient to set MAX_WBITS in zconf.h).
-- voidp -> voidpf and voidnp -> voidp (for consistency with other
-  typedefs and because voidnp was not near in large model).
-
-Changes in 0.94 (13 Aug 95)
-- support MSDOS medium model
-- fix deflate with flush (could sometimes generate bad output)
-- fix deflateReset (zlib header was incorrectly suppressed)
-- added support for VMS
-- allow a compression level in gzopen()
-- gzflush now calls fflush
-- For deflate with flush, flush even if no more input is provided.
-- rename libgz.a as libz.a
-- avoid complex expression in infcodes.c triggering Turbo C bug
-- work around a problem with gcc on Alpha (in INSERT_STRING)
-- don't use inline functions (problem with some gcc versions)
-- allow renaming of Byte, uInt, etc... with #define.
-- avoid warning about (unused) pointer before start of array in deflate.c
-- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c
-- avoid reserved word 'new' in trees.c
-
-Changes in 0.93 (25 June 95)
-- temporarily disable inline functions
-- make deflate deterministic
-- give enough lookahead for PARTIAL_FLUSH
-- Set binary mode for stdin/stdout in minigzip.c for OS/2
-- don't even use signed char in inflate (not portable enough)
-- fix inflate memory leak for segmented architectures
-
-Changes in 0.92 (3 May 95)
-- don't assume that char is signed (problem on SGI)
-- Clear bit buffer when starting a stored block
-- no memcpy on Pyramid
-- suppressed inftest.c
-- optimized fill_window, put longest_match inline for gcc
-- optimized inflate on stored blocks.
-- untabify all sources to simplify patches
-
-Changes in 0.91 (2 May 95)
-- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h
-- Document the memory requirements in zconf.h
-- added "make install"
-- fix sync search logic in inflateSync
-- deflate(Z_FULL_FLUSH) now works even if output buffer too short
-- after inflateSync, don't scare people with just "lo world"
-- added support for DJGPP
-
-Changes in 0.9 (1 May 95)
-- don't assume that zalloc clears the allocated memory (the TurboC bug
-  was Mark's bug after all :)
-- let again gzread copy uncompressed data unchanged (was working in 0.71)
-- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented
-- added a test of inflateSync in example.c
-- moved MAX_WBITS to zconf.h because users might want to change that.
-- document explicitly that zalloc(64K) on MSDOS must return a normalized
-  pointer (zero offset)
-- added Makefiles for Microsoft C, Turbo C, Borland C++
-- faster crc32()
-
-Changes in 0.8 (29 April 95)
-- added fast inflate (inffast.c)
-- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this
-  is incompatible with previous versions of zlib which returned Z_OK.
-- work around a TurboC compiler bug (bad code for b << 0, see infutil.h)
-  (actually that was not a compiler bug, see 0.81 above)
-- gzread no longer reads one extra byte in certain cases
-- In gzio destroy(), don't reference a freed structure
-- avoid many warnings for MSDOS
-- avoid the ERROR symbol which is used by MS Windows
-
-Changes in 0.71 (14 April 95)
-- Fixed more MSDOS compilation problems :( There is still a bug with
-  TurboC large model.
-
-Changes in 0.7 (14 April 95)
-- Added full inflate support.
-- Simplified the crc32() interface. The pre- and post-conditioning
-  (one's complement) is now done inside crc32(). WARNING: this is
-  incompatible with previous versions; see zlib.h for the new usage.
-
-Changes in 0.61 (12 April 95)
-- workaround for a bug in TurboC. example and minigzip now work on MSDOS.
-
-Changes in 0.6 (11 April 95)
-- added minigzip.c
-- added gzdopen to reopen a file descriptor as gzFile
-- added transparent reading of non-gziped files in gzread.
-- fixed bug in gzread (don't read crc as data)
-- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose).
-- don't allocate big arrays in the stack (for MSDOS)
-- fix some MSDOS compilation problems
-
-Changes in 0.5:
-- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but
-  not yet Z_FULL_FLUSH.
-- support decompression but only in a single step (forced Z_FINISH)
-- added opaque object for zalloc and zfree.
-- added deflateReset and inflateReset
-- added a variable zlib_version for consistency checking.
-- renamed the 'filter' parameter of deflateInit2 as 'strategy'.
-  Added Z_FILTERED and Z_HUFFMAN_ONLY constants.
-
-Changes in 0.4:
-- avoid "zip" everywhere, use zlib instead of ziplib.
-- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush
-  if compression method == 8.
-- added adler32 and crc32
-- renamed deflateOptions as deflateInit2, call one or the other but not both
-- added the method parameter for deflateInit2.
-- added inflateInit2
-- simplied considerably deflateInit and inflateInit by not supporting
-  user-provided history buffer. This is supported only in deflateInit2
-  and inflateInit2.
-
-Changes in 0.3:
-- prefix all macro names with Z_
-- use Z_FINISH instead of deflateEnd to finish compression.
-- added Z_HUFFMAN_ONLY
-- added gzerror()
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/README	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,115 +0,0 @@
-ZLIB DATA COMPRESSION LIBRARY
-
-zlib 1.2.8 is a general purpose data compression library.  All the code is
-thread safe.  The data format used by the zlib library is described by RFCs
-(Request for Comments) 1950 to 1952 in the files
-http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and
-rfc1952 (gzip format).
-
-All functions of the compression library are documented in the file zlib.h
-(volunteer to write man pages welcome, contact zlib@gzip.org).  A usage example
-of the library is given in the file test/example.c which also tests that
-the library is working correctly.  Another example is given in the file
-test/minigzip.c.  The compression library itself is composed of all source
-files in the root directory.
-
-To compile all files and run the test program, follow the instructions given at
-the top of Makefile.in.  In short "./configure; make test", and if that goes
-well, "make install" should work for most flavors of Unix.  For Windows, use
-one of the special makefiles in win32/ or contrib/vstudio/ .  For VMS, use
-make_vms.com.
-
-Questions about zlib should be sent to <zlib@gzip.org>, or to Gilles Vollant
-<info@winimage.com> for the Windows DLL version.  The zlib home page is
-http://zlib.net/ .  Before reporting a problem, please check this site to
-verify that you have the latest version of zlib; otherwise get the latest
-version and check whether the problem still exists or not.
-
-PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help.
-
-Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan.  1997
-issue of Dr.  Dobb's Journal; a copy of the article is available at
-http://marknelson.us/1997/01/01/zlib-engine/ .
-
-The changes made in version 1.2.8 are documented in the file ChangeLog.
-
-Unsupported third party contributions are provided in directory contrib/ .
-
-zlib is available in Java using the java.util.zip package, documented at
-http://java.sun.com/developer/technicalArticles/Programming/compression/ .
-
-A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is available
-at CPAN (Comprehensive Perl Archive Network) sites, including
-http://search.cpan.org/~pmqs/IO-Compress-Zlib/ .
-
-A Python interface to zlib written by A.M. Kuchling <amk@amk.ca> is
-available in Python 1.5 and later versions, see
-http://docs.python.org/library/zlib.html .
-
-zlib is built into tcl: http://wiki.tcl.tk/4610 .
-
-An experimental package to read and write files in .zip format, written on top
-of zlib by Gilles Vollant <info@winimage.com>, is available in the
-contrib/minizip directory of zlib.
-
-
-Notes for some targets:
-
-- For Windows DLL versions, please see win32/DLL_FAQ.txt
-
-- For 64-bit Irix, deflate.c must be compiled without any optimization. With
-  -O, one libpng test fails. The test works in 32 bit mode (with the -n32
-  compiler flag). The compiler bug has been reported to SGI.
-
-- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works
-  when compiled with cc.
-
-- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is
-  necessary to get gzprintf working correctly. This is done by configure.
-
-- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with
-  other compilers. Use "make test" to check your compiler.
-
-- gzdopen is not supported on RISCOS or BEOS.
-
-- For PalmOs, see http://palmzlib.sourceforge.net/
-
-
-Acknowledgments:
-
-  The deflate format used by zlib was defined by Phil Katz.  The deflate and
-  zlib specifications were written by L.  Peter Deutsch.  Thanks to all the
-  people who reported problems and suggested various improvements in zlib; they
-  are too numerous to cite here.
-
-Copyright notice:
-
- (C) 1995-2013 Jean-loup Gailly and Mark Adler
-
-  This software is provided 'as-is', without any express or implied
-  warranty.  In no event will the authors be held liable for any damages
-  arising from the use of this software.
-
-  Permission is granted to anyone to use this software for any purpose,
-  including commercial applications, and to alter it and redistribute it
-  freely, subject to the following restrictions:
-
-  1. The origin of this software must not be misrepresented; you must not
-     claim that you wrote the original software. If you use this software
-     in a product, an acknowledgment in the product documentation would be
-     appreciated but is not required.
-  2. Altered source versions must be plainly marked as such, and must not be
-     misrepresented as being the original software.
-  3. This notice may not be removed or altered from any source distribution.
-
-  Jean-loup Gailly        Mark Adler
-  jloup@gzip.org          madler@alumni.caltech.edu
-
-If you use the zlib library in a product, we would appreciate *not* receiving
-lengthy legal documents to sign.  The sources are provided for free but without
-warranty of any kind.  The library has been entirely written by Jean-loup
-Gailly and Mark Adler; it does not include third-party code.
-
-If you redistribute modified sources, we would appreciate that you include in
-the file ChangeLog history information documenting your changes.  Please read
-the FAQ for more information on the distribution of modified source versions.
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/compress.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,104 +0,0 @@
-/*
- * 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.
- */
-
-/* compress.c -- compress a memory buffer
- * Copyright (C) 1995-2005 Jean-loup Gailly.
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/* @(#) $Id$ */
-
-#define ZLIB_INTERNAL
-#include "zlib.h"
-
-/* ===========================================================================
-     Compresses the source buffer into the destination buffer. The level
-   parameter has the same meaning as in deflateInit.  sourceLen is the byte
-   length of the source buffer. Upon entry, destLen is the total size of the
-   destination buffer, which must be at least 0.1% larger than sourceLen plus
-   12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
-
-     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
-   memory, Z_BUF_ERROR if there was not enough room in the output buffer,
-   Z_STREAM_ERROR if the level parameter is invalid.
-*/
-int ZEXPORT compress2 (dest, destLen, source, sourceLen, level)
-    Bytef *dest;
-    uLongf *destLen;
-    const Bytef *source;
-    uLong sourceLen;
-    int level;
-{
-    z_stream stream;
-    int err;
-
-    stream.next_in = (z_const Bytef *)source;
-    stream.avail_in = (uInt)sourceLen;
-#ifdef MAXSEG_64K
-    /* Check for source > 64K on 16-bit machine: */
-    if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
-#endif
-    stream.next_out = dest;
-    stream.avail_out = (uInt)*destLen;
-    if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
-
-    stream.zalloc = (alloc_func)0;
-    stream.zfree = (free_func)0;
-    stream.opaque = (voidpf)0;
-
-    err = deflateInit(&stream, level);
-    if (err != Z_OK) return err;
-
-    err = deflate(&stream, Z_FINISH);
-    if (err != Z_STREAM_END) {
-        deflateEnd(&stream);
-        return err == Z_OK ? Z_BUF_ERROR : err;
-    }
-    *destLen = stream.total_out;
-
-    err = deflateEnd(&stream);
-    return err;
-}
-
-/* ===========================================================================
- */
-int ZEXPORT compress (dest, destLen, source, sourceLen)
-    Bytef *dest;
-    uLongf *destLen;
-    const Bytef *source;
-    uLong sourceLen;
-{
-    return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
-}
-
-/* ===========================================================================
-     If the default memLevel or windowBits for deflateInit() is changed, then
-   this function needs to be updated.
- */
-uLong ZEXPORT compressBound (sourceLen)
-    uLong sourceLen;
-{
-    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
-           (sourceLen >> 25) + 13;
-}
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/crc32.h	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,465 +0,0 @@
-/*
- * 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.
- */
-
-/* crc32.h -- tables for rapid CRC calculation
- * Generated automatically by crc32.c
- */
-
-local const z_crc_t FAR crc_table[TBLS][256] =
-{
-  {
-    0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
-    0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
-    0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
-    0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
-    0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
-    0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
-    0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
-    0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
-    0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
-    0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
-    0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
-    0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
-    0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
-    0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
-    0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
-    0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
-    0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
-    0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
-    0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
-    0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
-    0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
-    0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
-    0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
-    0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
-    0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
-    0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
-    0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
-    0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
-    0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
-    0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
-    0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
-    0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
-    0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
-    0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
-    0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
-    0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
-    0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
-    0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
-    0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
-    0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
-    0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
-    0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
-    0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
-    0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
-    0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
-    0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
-    0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
-    0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
-    0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
-    0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
-    0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
-    0x2d02ef8dUL
-#ifdef BYFOUR
-  },
-  {
-    0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
-    0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
-    0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
-    0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
-    0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
-    0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
-    0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
-    0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
-    0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
-    0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
-    0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
-    0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
-    0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
-    0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
-    0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
-    0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
-    0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
-    0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
-    0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
-    0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
-    0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
-    0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
-    0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
-    0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
-    0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
-    0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
-    0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
-    0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
-    0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
-    0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
-    0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
-    0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
-    0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
-    0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
-    0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
-    0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
-    0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
-    0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
-    0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
-    0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
-    0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
-    0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
-    0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
-    0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
-    0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
-    0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
-    0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
-    0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
-    0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
-    0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
-    0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
-    0x9324fd72UL
-  },
-  {
-    0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
-    0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
-    0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
-    0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
-    0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
-    0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
-    0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
-    0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
-    0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
-    0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
-    0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
-    0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
-    0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
-    0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
-    0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
-    0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
-    0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
-    0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
-    0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
-    0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
-    0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
-    0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
-    0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
-    0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
-    0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
-    0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
-    0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
-    0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
-    0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
-    0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
-    0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
-    0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
-    0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
-    0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
-    0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
-    0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
-    0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
-    0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
-    0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
-    0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
-    0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
-    0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
-    0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
-    0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
-    0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
-    0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
-    0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
-    0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
-    0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
-    0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
-    0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
-    0xbe9834edUL
-  },
-  {
-    0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
-    0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
-    0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
-    0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
-    0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
-    0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
-    0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
-    0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
-    0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
-    0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
-    0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
-    0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
-    0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
-    0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
-    0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
-    0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
-    0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
-    0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
-    0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
-    0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
-    0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
-    0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
-    0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
-    0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
-    0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
-    0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
-    0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
-    0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
-    0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
-    0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
-    0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
-    0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
-    0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
-    0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
-    0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
-    0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
-    0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
-    0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
-    0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
-    0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
-    0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
-    0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
-    0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
-    0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
-    0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
-    0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
-    0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
-    0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
-    0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
-    0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
-    0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
-    0xde0506f1UL
-  },
-  {
-    0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
-    0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
-    0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
-    0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
-    0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
-    0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
-    0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
-    0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
-    0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
-    0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
-    0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
-    0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
-    0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
-    0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
-    0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
-    0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
-    0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
-    0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
-    0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
-    0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
-    0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
-    0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
-    0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
-    0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
-    0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
-    0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
-    0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
-    0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
-    0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
-    0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
-    0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
-    0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
-    0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
-    0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
-    0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
-    0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
-    0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
-    0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
-    0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
-    0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
-    0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
-    0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
-    0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
-    0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
-    0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
-    0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
-    0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
-    0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
-    0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
-    0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
-    0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
-    0x8def022dUL
-  },
-  {
-    0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
-    0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
-    0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
-    0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
-    0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
-    0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
-    0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
-    0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
-    0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
-    0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
-    0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
-    0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
-    0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
-    0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
-    0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
-    0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
-    0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
-    0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
-    0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
-    0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
-    0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
-    0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
-    0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
-    0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
-    0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
-    0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
-    0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
-    0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
-    0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
-    0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
-    0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
-    0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
-    0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
-    0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
-    0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
-    0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
-    0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
-    0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
-    0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
-    0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
-    0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
-    0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
-    0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
-    0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
-    0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
-    0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
-    0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
-    0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
-    0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
-    0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
-    0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
-    0x72fd2493UL
-  },
-  {
-    0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
-    0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
-    0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
-    0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
-    0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
-    0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
-    0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
-    0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
-    0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
-    0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
-    0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
-    0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
-    0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
-    0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
-    0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
-    0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
-    0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
-    0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
-    0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
-    0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
-    0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
-    0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
-    0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
-    0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
-    0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
-    0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
-    0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
-    0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
-    0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
-    0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
-    0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
-    0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
-    0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
-    0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
-    0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
-    0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
-    0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
-    0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
-    0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
-    0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
-    0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
-    0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
-    0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
-    0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
-    0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
-    0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
-    0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
-    0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
-    0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
-    0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
-    0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
-    0xed3498beUL
-  },
-  {
-    0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
-    0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
-    0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
-    0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
-    0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
-    0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
-    0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
-    0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
-    0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
-    0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
-    0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
-    0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
-    0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
-    0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
-    0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
-    0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
-    0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
-    0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
-    0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
-    0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
-    0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
-    0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
-    0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
-    0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
-    0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
-    0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
-    0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
-    0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
-    0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
-    0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
-    0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
-    0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
-    0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
-    0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
-    0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
-    0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
-    0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
-    0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
-    0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
-    0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
-    0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
-    0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
-    0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
-    0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
-    0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
-    0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
-    0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
-    0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
-    0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
-    0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
-    0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
-    0xf10605deUL
-#endif
-  }
-};
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/deflate.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1991 +0,0 @@
-/*
- * 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.
- */
-
-/* deflate.c -- compress data using the deflation algorithm
- * Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/*
- *  ALGORITHM
- *
- *      The "deflation" process depends on being able to identify portions
- *      of the input text which are identical to earlier input (within a
- *      sliding window trailing behind the input currently being processed).
- *
- *      The most straightforward technique turns out to be the fastest for
- *      most input files: try all possible matches and select the longest.
- *      The key feature of this algorithm is that insertions into the string
- *      dictionary are very simple and thus fast, and deletions are avoided
- *      completely. Insertions are performed at each input character, whereas
- *      string matches are performed only when the previous match ends. So it
- *      is preferable to spend more time in matches to allow very fast string
- *      insertions and avoid deletions. The matching algorithm for small
- *      strings is inspired from that of Rabin & Karp. A brute force approach
- *      is used to find longer strings when a small match has been found.
- *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
- *      (by Leonid Broukhis).
- *         A previous version of this file used a more sophisticated algorithm
- *      (by Fiala and Greene) which is guaranteed to run in linear amortized
- *      time, but has a larger average cost, uses more memory and is patented.
- *      However the F&G algorithm may be faster for some highly redundant
- *      files if the parameter max_chain_length (described below) is too large.
- *
- *  ACKNOWLEDGEMENTS
- *
- *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
- *      I found it in 'freeze' written by Leonid Broukhis.
- *      Thanks to many people for bug reports and testing.
- *
- *  REFERENCES
- *
- *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
- *      Available in http://tools.ietf.org/html/rfc1951
- *
- *      A description of the Rabin and Karp algorithm is given in the book
- *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
- *
- *      Fiala,E.R., and Greene,D.H.
- *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
- *
- */
-
-/* @(#) $Id$ */
-
-#include "deflate.h"
-
-const char deflate_copyright[] =
-   " deflate 1.2.8 Copyright 1995-2013 Jean-loup Gailly and Mark Adler ";
-/*
-  If you use the zlib library in a product, an acknowledgment is welcome
-  in the documentation of your product. If for some reason you cannot
-  include such an acknowledgment, I would appreciate that you keep this
-  copyright string in the executable of your product.
- */
-
-/* ===========================================================================
- *  Function prototypes.
- */
-typedef enum {
-    need_more,      /* block not completed, need more input or more output */
-    block_done,     /* block flush performed */
-    finish_started, /* finish started, need only more output at next deflate */
-    finish_done     /* finish done, accept no more input or output */
-} block_state;
-
-typedef block_state (*compress_func) OF((deflate_state *s, int flush));
-/* Compression function. Returns the block state after the call. */
-
-local void fill_window    OF((deflate_state *s));
-local block_state deflate_stored OF((deflate_state *s, int flush));
-local block_state deflate_fast   OF((deflate_state *s, int flush));
-#ifndef FASTEST
-local block_state deflate_slow   OF((deflate_state *s, int flush));
-#endif
-local block_state deflate_rle    OF((deflate_state *s, int flush));
-local block_state deflate_huff   OF((deflate_state *s, int flush));
-local void lm_init        OF((deflate_state *s));
-local void putShortMSB    OF((deflate_state *s, uInt b));
-local void flush_pending  OF((z_streamp strm));
-local int read_buf        OF((z_streamp strm, Bytef *buf, unsigned size));
-#ifdef ASMV
-      void match_init OF((void)); /* asm code initialization */
-      uInt longest_match  OF((deflate_state *s, IPos cur_match));
-#else
-local uInt longest_match  OF((deflate_state *s, IPos cur_match));
-#endif
-
-#ifdef DEBUG
-local  void check_match OF((deflate_state *s, IPos start, IPos match,
-                            int length));
-#endif
-
-/* ===========================================================================
- * Local data
- */
-
-#define NIL 0
-/* Tail of hash chains */
-
-#ifndef TOO_FAR
-#  define TOO_FAR 4096
-#endif
-/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
-
-/* Values for max_lazy_match, good_match and max_chain_length, depending on
- * the desired pack level (0..9). The values given below have been tuned to
- * exclude worst case performance for pathological files. Better values may be
- * found for specific files.
- */
-typedef struct config_s {
-   ush good_length; /* reduce lazy search above this match length */
-   ush max_lazy;    /* do not perform lazy search above this match length */
-   ush nice_length; /* quit search above this match length */
-   ush max_chain;
-   compress_func func;
-} config;
-
-#ifdef FASTEST
-local const config configuration_table[2] = {
-/*      good lazy nice chain */
-/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
-/* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */
-#else
-local const config configuration_table[10] = {
-/*      good lazy nice chain */
-/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
-/* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
-/* 2 */ {4,    5, 16,    8, deflate_fast},
-/* 3 */ {4,    6, 32,   32, deflate_fast},
-
-/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
-/* 5 */ {8,   16, 32,   32, deflate_slow},
-/* 6 */ {8,   16, 128, 128, deflate_slow},
-/* 7 */ {8,   32, 128, 256, deflate_slow},
-/* 8 */ {32, 128, 258, 1024, deflate_slow},
-/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
-#endif
-
-/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
- * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
- * meaning.
- */
-
-#define EQUAL 0
-/* result of memcmp for equal strings */
-
-#ifndef NO_DUMMY_DECL
-struct static_tree_desc_s {int dummy;}; /* for buggy compilers */
-#endif
-
-/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
-#define RANK(f) (((f) << 1) - ((f) > 4 ? 9 : 0))
-
-/* ===========================================================================
- * Update a hash value with the given input byte
- * IN  assertion: all calls to to UPDATE_HASH are made with consecutive
- *    input characters, so that a running hash key can be computed from the
- *    previous key instead of complete recalculation each time.
- */
-#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
-
-
-/* ===========================================================================
- * Insert string str in the dictionary and set match_head to the previous head
- * of the hash chain (the most recent string with same hash key). Return
- * the previous length of the hash chain.
- * If this file is compiled with -DFASTEST, the compression level is forced
- * to 1, and no hash chains are maintained.
- * IN  assertion: all calls to to INSERT_STRING are made with consecutive
- *    input characters and the first MIN_MATCH bytes of str are valid
- *    (except for the last MIN_MATCH-1 bytes of the input file).
- */
-#ifdef FASTEST
-#define INSERT_STRING(s, str, match_head) \
-   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
-    match_head = s->head[s->ins_h], \
-    s->head[s->ins_h] = (Pos)(str))
-#else
-#define INSERT_STRING(s, str, match_head) \
-   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
-    match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
-    s->head[s->ins_h] = (Pos)(str))
-#endif
-
-/* ===========================================================================
- * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
- * prev[] will be initialized on the fly.
- */
-#define CLEAR_HASH(s) \
-    s->head[s->hash_size-1] = NIL; \
-    zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
-
-/* ========================================================================= */
-int ZEXPORT deflateInit_(strm, level, version, stream_size)
-    z_streamp strm;
-    int level;
-    const char *version;
-    int stream_size;
-{
-    return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
-                         Z_DEFAULT_STRATEGY, version, stream_size);
-    /* To do: ignore strm->next_in if we use it as window */
-}
-
-/* ========================================================================= */
-int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
-                  version, stream_size)
-    z_streamp strm;
-    int  level;
-    int  method;
-    int  windowBits;
-    int  memLevel;
-    int  strategy;
-    const char *version;
-    int stream_size;
-{
-    deflate_state *s;
-    int wrap = 1;
-    static const char my_version[] = ZLIB_VERSION;
-
-    ushf *overlay;
-    /* We overlay pending_buf and d_buf+l_buf. This works since the average
-     * output size for (length,distance) codes is <= 24 bits.
-     */
-
-    if (version == Z_NULL || version[0] != my_version[0] ||
-        stream_size != sizeof(z_stream)) {
-        return Z_VERSION_ERROR;
-    }
-    if (strm == Z_NULL) return Z_STREAM_ERROR;
-
-    strm->msg = Z_NULL;
-    if (strm->zalloc == (alloc_func)0) {
-#ifdef Z_SOLO
-        return Z_STREAM_ERROR;
-#else
-        strm->zalloc = zcalloc;
-        strm->opaque = (voidpf)0;
-#endif
-    }
-    if (strm->zfree == (free_func)0)
-#ifdef Z_SOLO
-        return Z_STREAM_ERROR;
-#else
-        strm->zfree = zcfree;
-#endif
-
-#ifdef FASTEST
-    if (level != 0) level = 1;
-#else
-    if (level == Z_DEFAULT_COMPRESSION) level = 6;
-#endif
-
-    if (windowBits < 0) { /* suppress zlib wrapper */
-        wrap = 0;
-        windowBits = -windowBits;
-    }
-#ifdef GZIP
-    else if (windowBits > 15) {
-        wrap = 2;       /* write gzip wrapper instead */
-        windowBits -= 16;
-    }
-#endif
-    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
-        windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
-        strategy < 0 || strategy > Z_FIXED) {
-        return Z_STREAM_ERROR;
-    }
-    if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
-    s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
-    if (s == Z_NULL) return Z_MEM_ERROR;
-    strm->state = (struct internal_state FAR *)s;
-    s->strm = strm;
-
-    s->wrap = wrap;
-    s->gzhead = Z_NULL;
-    s->w_bits = windowBits;
-    s->w_size = 1 << s->w_bits;
-    s->w_mask = s->w_size - 1;
-
-    s->hash_bits = memLevel + 7;
-    s->hash_size = 1 << s->hash_bits;
-    s->hash_mask = s->hash_size - 1;
-    s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
-
-    s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
-    s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
-    s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
-
-    s->high_water = 0;      /* nothing written to s->window yet */
-
-    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
-
-    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
-    s->pending_buf = (uchf *) overlay;
-    s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
-
-    if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
-        s->pending_buf == Z_NULL) {
-        s->status = FINISH_STATE;
-        strm->msg = ERR_MSG(Z_MEM_ERROR);
-        deflateEnd (strm);
-        return Z_MEM_ERROR;
-    }
-    s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
-    s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
-
-    s->level = level;
-    s->strategy = strategy;
-    s->method = (Byte)method;
-
-    return deflateReset(strm);
-}
-
-/* ========================================================================= */
-int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
-    z_streamp strm;
-    const Bytef *dictionary;
-    uInt  dictLength;
-{
-    deflate_state *s;
-    uInt str, n;
-    int wrap;
-    unsigned avail;
-    z_const unsigned char *next;
-
-    if (strm == Z_NULL || strm->state == Z_NULL || dictionary == Z_NULL)
-        return Z_STREAM_ERROR;
-    s = strm->state;
-    wrap = s->wrap;
-    if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
-        return Z_STREAM_ERROR;
-
-    /* when using zlib wrappers, compute Adler-32 for provided dictionary */
-    if (wrap == 1)
-        strm->adler = adler32(strm->adler, dictionary, dictLength);
-    s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */
-
-    /* if dictionary would fill window, just replace the history */
-    if (dictLength >= s->w_size) {
-        if (wrap == 0) {            /* already empty otherwise */
-            CLEAR_HASH(s);
-            s->strstart = 0;
-            s->block_start = 0L;
-            s->insert = 0;
-        }
-        dictionary += dictLength - s->w_size;  /* use the tail */
-        dictLength = s->w_size;
-    }
-
-    /* insert dictionary into window and hash */
-    avail = strm->avail_in;
-    next = strm->next_in;
-    strm->avail_in = dictLength;
-    strm->next_in = (z_const Bytef *)dictionary;
-    fill_window(s);
-    while (s->lookahead >= MIN_MATCH) {
-        str = s->strstart;
-        n = s->lookahead - (MIN_MATCH-1);
-        do {
-            UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
-#ifndef FASTEST
-            s->prev[str & s->w_mask] = s->head[s->ins_h];
-#endif
-            s->head[s->ins_h] = (Pos)str;
-            str++;
-        } while (--n);
-        s->strstart = str;
-        s->lookahead = MIN_MATCH-1;
-        fill_window(s);
-    }
-    s->strstart += s->lookahead;
-    s->block_start = (long)s->strstart;
-    s->insert = s->lookahead;
-    s->lookahead = 0;
-    s->match_length = s->prev_length = MIN_MATCH-1;
-    s->match_available = 0;
-    strm->next_in = next;
-    strm->avail_in = avail;
-    s->wrap = wrap;
-    return Z_OK;
-}
-
-/* ========================================================================= */
-int ZEXPORT deflateResetKeep (strm)
-    z_streamp strm;
-{
-    deflate_state *s;
-
-    if (strm == Z_NULL || strm->state == Z_NULL ||
-        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0) {
-        return Z_STREAM_ERROR;
-    }
-
-    strm->total_in = strm->total_out = 0;
-    strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
-    strm->data_type = Z_UNKNOWN;
-
-    s = (deflate_state *)strm->state;
-    s->pending = 0;
-    s->pending_out = s->pending_buf;
-
-    if (s->wrap < 0) {
-        s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
-    }
-    s->status = s->wrap ? INIT_STATE : BUSY_STATE;
-    strm->adler =
-#ifdef GZIP
-        s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
-#endif
-        adler32(0L, Z_NULL, 0);
-    s->last_flush = Z_NO_FLUSH;
-
-    _tr_init(s);
-
-    return Z_OK;
-}
-
-/* ========================================================================= */
-int ZEXPORT deflateReset (strm)
-    z_streamp strm;
-{
-    int ret;
-
-    ret = deflateResetKeep(strm);
-    if (ret == Z_OK)
-        lm_init(strm->state);
-    return ret;
-}
-
-/* ========================================================================= */
-int ZEXPORT deflateSetHeader (strm, head)
-    z_streamp strm;
-    gz_headerp head;
-{
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    if (strm->state->wrap != 2) return Z_STREAM_ERROR;
-    strm->state->gzhead = head;
-    return Z_OK;
-}
-
-/* ========================================================================= */
-int ZEXPORT deflatePending (strm, pending, bits)
-    unsigned *pending;
-    int *bits;
-    z_streamp strm;
-{
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    if (pending != Z_NULL)
-        *pending = strm->state->pending;
-    if (bits != Z_NULL)
-        *bits = strm->state->bi_valid;
-    return Z_OK;
-}
-
-/* ========================================================================= */
-int ZEXPORT deflatePrime (strm, bits, value)
-    z_streamp strm;
-    int bits;
-    int value;
-{
-    deflate_state *s;
-    int put;
-
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    s = strm->state;
-    if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))
-        return Z_BUF_ERROR;
-    do {
-        put = Buf_size - s->bi_valid;
-        if (put > bits)
-            put = bits;
-        s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
-        s->bi_valid += put;
-        _tr_flush_bits(s);
-        value >>= put;
-        bits -= put;
-    } while (bits);
-    return Z_OK;
-}
-
-/* ========================================================================= */
-int ZEXPORT deflateParams(strm, level, strategy)
-    z_streamp strm;
-    int level;
-    int strategy;
-{
-    deflate_state *s;
-    compress_func func;
-    int err = Z_OK;
-
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    s = strm->state;
-
-#ifdef FASTEST
-    if (level != 0) level = 1;
-#else
-    if (level == Z_DEFAULT_COMPRESSION) level = 6;
-#endif
-    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
-        return Z_STREAM_ERROR;
-    }
-    func = configuration_table[s->level].func;
-
-    if ((strategy != s->strategy || func != configuration_table[level].func) &&
-        strm->total_in != 0) {
-        /* Flush the last buffer: */
-        err = deflate(strm, Z_BLOCK);
-        if (err == Z_BUF_ERROR && s->pending == 0)
-            err = Z_OK;
-    }
-    if (s->level != level) {
-        s->level = level;
-        s->max_lazy_match   = configuration_table[level].max_lazy;
-        s->good_match       = configuration_table[level].good_length;
-        s->nice_match       = configuration_table[level].nice_length;
-        s->max_chain_length = configuration_table[level].max_chain;
-    }
-    s->strategy = strategy;
-    return err;
-}
-
-/* ========================================================================= */
-int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
-    z_streamp strm;
-    int good_length;
-    int max_lazy;
-    int nice_length;
-    int max_chain;
-{
-    deflate_state *s;
-
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    s = strm->state;
-    s->good_match = good_length;
-    s->max_lazy_match = max_lazy;
-    s->nice_match = nice_length;
-    s->max_chain_length = max_chain;
-    return Z_OK;
-}
-
-/* =========================================================================
- * For the default windowBits of 15 and memLevel of 8, this function returns
- * a close to exact, as well as small, upper bound on the compressed size.
- * They are coded as constants here for a reason--if the #define's are
- * changed, then this function needs to be changed as well.  The return
- * value for 15 and 8 only works for those exact settings.
- *
- * For any setting other than those defaults for windowBits and memLevel,
- * the value returned is a conservative worst case for the maximum expansion
- * resulting from using fixed blocks instead of stored blocks, which deflate
- * can emit on compressed data for some combinations of the parameters.
- *
- * This function could be more sophisticated to provide closer upper bounds for
- * every combination of windowBits and memLevel.  But even the conservative
- * upper bound of about 14% expansion does not seem onerous for output buffer
- * allocation.
- */
-uLong ZEXPORT deflateBound(strm, sourceLen)
-    z_streamp strm;
-    uLong sourceLen;
-{
-    deflate_state *s;
-    uLong complen, wraplen;
-    Bytef *str;
-
-    /* conservative upper bound for compressed data */
-    complen = sourceLen +
-              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
-
-    /* if can't get parameters, return conservative bound plus zlib wrapper */
-    if (strm == Z_NULL || strm->state == Z_NULL)
-        return complen + 6;
-
-    /* compute wrapper length */
-    s = strm->state;
-    switch (s->wrap) {
-    case 0:                                 /* raw deflate */
-        wraplen = 0;
-        break;
-    case 1:                                 /* zlib wrapper */
-        wraplen = 6 + (s->strstart ? 4 : 0);
-        break;
-    case 2:                                 /* gzip wrapper */
-        wraplen = 18;
-        if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */
-            if (s->gzhead->extra != Z_NULL)
-                wraplen += 2 + s->gzhead->extra_len;
-            str = s->gzhead->name;
-            if (str != Z_NULL)
-                do {
-                    wraplen++;
-                } while (*str++);
-            str = s->gzhead->comment;
-            if (str != Z_NULL)
-                do {
-                    wraplen++;
-                } while (*str++);
-            if (s->gzhead->hcrc)
-                wraplen += 2;
-        }
-        break;
-    default:                                /* for compiler happiness */
-        wraplen = 6;
-    }
-
-    /* if not default parameters, return conservative bound */
-    if (s->w_bits != 15 || s->hash_bits != 8 + 7)
-        return complen + wraplen;
-
-    /* default settings: return tight bound for that case */
-    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
-           (sourceLen >> 25) + 13 - 6 + wraplen;
-}
-
-/* =========================================================================
- * Put a short in the pending buffer. The 16-bit value is put in MSB order.
- * IN assertion: the stream state is correct and there is enough room in
- * pending_buf.
- */
-local void putShortMSB (s, b)
-    deflate_state *s;
-    uInt b;
-{
-    put_byte(s, (Byte)(b >> 8));
-    put_byte(s, (Byte)(b & 0xff));
-}
-
-/* =========================================================================
- * Flush as much pending output as possible. All deflate() output goes
- * through this function so some applications may wish to modify it
- * to avoid allocating a large strm->next_out buffer and copying into it.
- * (See also read_buf()).
- */
-local void flush_pending(strm)
-    z_streamp strm;
-{
-    unsigned len;
-    deflate_state *s = strm->state;
-
-    _tr_flush_bits(s);
-    len = s->pending;
-    if (len > strm->avail_out) len = strm->avail_out;
-    if (len == 0) return;
-
-    zmemcpy(strm->next_out, s->pending_out, len);
-    strm->next_out  += len;
-    s->pending_out  += len;
-    strm->total_out += len;
-    strm->avail_out  -= len;
-    s->pending -= len;
-    if (s->pending == 0) {
-        s->pending_out = s->pending_buf;
-    }
-}
-
-/* ========================================================================= */
-int ZEXPORT deflate (strm, flush)
-    z_streamp strm;
-    int flush;
-{
-    int old_flush; /* value of flush param for previous deflate call */
-    deflate_state *s;
-
-    if (strm == Z_NULL || strm->state == Z_NULL ||
-        flush > Z_BLOCK || flush < 0) {
-        return Z_STREAM_ERROR;
-    }
-    s = strm->state;
-
-    if (strm->next_out == Z_NULL ||
-        (strm->next_in == Z_NULL && strm->avail_in != 0) ||
-        (s->status == FINISH_STATE && flush != Z_FINISH)) {
-        ERR_RETURN(strm, Z_STREAM_ERROR);
-    }
-    if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
-
-    s->strm = strm; /* just in case */
-    old_flush = s->last_flush;
-    s->last_flush = flush;
-
-    /* Write the header */
-    if (s->status == INIT_STATE) {
-#ifdef GZIP
-        if (s->wrap == 2) {
-            strm->adler = crc32(0L, Z_NULL, 0);
-            put_byte(s, 31);
-            put_byte(s, 139);
-            put_byte(s, 8);
-            if (s->gzhead == Z_NULL) {
-                put_byte(s, 0);
-                put_byte(s, 0);
-                put_byte(s, 0);
-                put_byte(s, 0);
-                put_byte(s, 0);
-                put_byte(s, s->level == 9 ? 2 :
-                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
-                             4 : 0));
-                put_byte(s, OS_CODE);
-                s->status = BUSY_STATE;
-            }
-            else {
-                put_byte(s, (s->gzhead->text ? 1 : 0) +
-                            (s->gzhead->hcrc ? 2 : 0) +
-                            (s->gzhead->extra == Z_NULL ? 0 : 4) +
-                            (s->gzhead->name == Z_NULL ? 0 : 8) +
-                            (s->gzhead->comment == Z_NULL ? 0 : 16)
-                        );
-                put_byte(s, (Byte)(s->gzhead->time & 0xff));
-                put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
-                put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
-                put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
-                put_byte(s, s->level == 9 ? 2 :
-                            (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
-                             4 : 0));
-                put_byte(s, s->gzhead->os & 0xff);
-                if (s->gzhead->extra != Z_NULL) {
-                    put_byte(s, s->gzhead->extra_len & 0xff);
-                    put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
-                }
-                if (s->gzhead->hcrc)
-                    strm->adler = crc32(strm->adler, s->pending_buf,
-                                        s->pending);
-                s->gzindex = 0;
-                s->status = EXTRA_STATE;
-            }
-        }
-        else
-#endif
-        {
-            uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
-            uInt level_flags;
-
-            if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
-                level_flags = 0;
-            else if (s->level < 6)
-                level_flags = 1;
-            else if (s->level == 6)
-                level_flags = 2;
-            else
-                level_flags = 3;
-            header |= (level_flags << 6);
-            if (s->strstart != 0) header |= PRESET_DICT;
-            header += 31 - (header % 31);
-
-            s->status = BUSY_STATE;
-            putShortMSB(s, header);
-
-            /* Save the adler32 of the preset dictionary: */
-            if (s->strstart != 0) {
-                putShortMSB(s, (uInt)(strm->adler >> 16));
-                putShortMSB(s, (uInt)(strm->adler & 0xffff));
-            }
-            strm->adler = adler32(0L, Z_NULL, 0);
-        }
-    }
-#ifdef GZIP
-    if (s->status == EXTRA_STATE) {
-        if (s->gzhead->extra != Z_NULL) {
-            uInt beg = s->pending;  /* start of bytes to update crc */
-
-            while (s->gzindex < (s->gzhead->extra_len & 0xffff)) {
-                if (s->pending == s->pending_buf_size) {
-                    if (s->gzhead->hcrc && s->pending > beg)
-                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
-                                            s->pending - beg);
-                    flush_pending(strm);
-                    beg = s->pending;
-                    if (s->pending == s->pending_buf_size)
-                        break;
-                }
-                put_byte(s, s->gzhead->extra[s->gzindex]);
-                s->gzindex++;
-            }
-            if (s->gzhead->hcrc && s->pending > beg)
-                strm->adler = crc32(strm->adler, s->pending_buf + beg,
-                                    s->pending - beg);
-            if (s->gzindex == s->gzhead->extra_len) {
-                s->gzindex = 0;
-                s->status = NAME_STATE;
-            }
-        }
-        else
-            s->status = NAME_STATE;
-    }
-    if (s->status == NAME_STATE) {
-        if (s->gzhead->name != Z_NULL) {
-            uInt beg = s->pending;  /* start of bytes to update crc */
-            int val;
-
-            do {
-                if (s->pending == s->pending_buf_size) {
-                    if (s->gzhead->hcrc && s->pending > beg)
-                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
-                                            s->pending - beg);
-                    flush_pending(strm);
-                    beg = s->pending;
-                    if (s->pending == s->pending_buf_size) {
-                        val = 1;
-                        break;
-                    }
-                }
-                val = s->gzhead->name[s->gzindex++];
-                put_byte(s, val);
-            } while (val != 0);
-            if (s->gzhead->hcrc && s->pending > beg)
-                strm->adler = crc32(strm->adler, s->pending_buf + beg,
-                                    s->pending - beg);
-            if (val == 0) {
-                s->gzindex = 0;
-                s->status = COMMENT_STATE;
-            }
-        }
-        else
-            s->status = COMMENT_STATE;
-    }
-    if (s->status == COMMENT_STATE) {
-        if (s->gzhead->comment != Z_NULL) {
-            uInt beg = s->pending;  /* start of bytes to update crc */
-            int val;
-
-            do {
-                if (s->pending == s->pending_buf_size) {
-                    if (s->gzhead->hcrc && s->pending > beg)
-                        strm->adler = crc32(strm->adler, s->pending_buf + beg,
-                                            s->pending - beg);
-                    flush_pending(strm);
-                    beg = s->pending;
-                    if (s->pending == s->pending_buf_size) {
-                        val = 1;
-                        break;
-                    }
-                }
-                val = s->gzhead->comment[s->gzindex++];
-                put_byte(s, val);
-            } while (val != 0);
-            if (s->gzhead->hcrc && s->pending > beg)
-                strm->adler = crc32(strm->adler, s->pending_buf + beg,
-                                    s->pending - beg);
-            if (val == 0)
-                s->status = HCRC_STATE;
-        }
-        else
-            s->status = HCRC_STATE;
-    }
-    if (s->status == HCRC_STATE) {
-        if (s->gzhead->hcrc) {
-            if (s->pending + 2 > s->pending_buf_size)
-                flush_pending(strm);
-            if (s->pending + 2 <= s->pending_buf_size) {
-                put_byte(s, (Byte)(strm->adler & 0xff));
-                put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
-                strm->adler = crc32(0L, Z_NULL, 0);
-                s->status = BUSY_STATE;
-            }
-        }
-        else
-            s->status = BUSY_STATE;
-    }
-#endif
-
-    /* Flush as much pending output as possible */
-    if (s->pending != 0) {
-        flush_pending(strm);
-        if (strm->avail_out == 0) {
-            /* Since avail_out is 0, deflate will be called again with
-             * more output space, but possibly with both pending and
-             * avail_in equal to zero. There won't be anything to do,
-             * but this is not an error situation so make sure we
-             * return OK instead of BUF_ERROR at next call of deflate:
-             */
-            s->last_flush = -1;
-            return Z_OK;
-        }
-
-    /* Make sure there is something to do and avoid duplicate consecutive
-     * flushes. For repeated and useless calls with Z_FINISH, we keep
-     * returning Z_STREAM_END instead of Z_BUF_ERROR.
-     */
-    } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
-               flush != Z_FINISH) {
-        ERR_RETURN(strm, Z_BUF_ERROR);
-    }
-
-    /* User must not provide more input after the first FINISH: */
-    if (s->status == FINISH_STATE && strm->avail_in != 0) {
-        ERR_RETURN(strm, Z_BUF_ERROR);
-    }
-
-    /* Start a new block or continue the current one.
-     */
-    if (strm->avail_in != 0 || s->lookahead != 0 ||
-        (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
-        block_state bstate;
-
-        bstate = s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
-                    (s->strategy == Z_RLE ? deflate_rle(s, flush) :
-                        (*(configuration_table[s->level].func))(s, flush));
-
-        if (bstate == finish_started || bstate == finish_done) {
-            s->status = FINISH_STATE;
-        }
-        if (bstate == need_more || bstate == finish_started) {
-            if (strm->avail_out == 0) {
-                s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
-            }
-            return Z_OK;
-            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
-             * of deflate should use the same flush parameter to make sure
-             * that the flush is complete. So we don't have to output an
-             * empty block here, this will be done at next call. This also
-             * ensures that for a very small output buffer, we emit at most
-             * one empty block.
-             */
-        }
-        if (bstate == block_done) {
-            if (flush == Z_PARTIAL_FLUSH) {
-                _tr_align(s);
-            } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
-                _tr_stored_block(s, (char*)0, 0L, 0);
-                /* For a full flush, this empty block will be recognized
-                 * as a special marker by inflate_sync().
-                 */
-                if (flush == Z_FULL_FLUSH) {
-                    CLEAR_HASH(s);             /* forget history */
-                    if (s->lookahead == 0) {
-                        s->strstart = 0;
-                        s->block_start = 0L;
-                        s->insert = 0;
-                    }
-                }
-            }
-            flush_pending(strm);
-            if (strm->avail_out == 0) {
-              s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
-              return Z_OK;
-            }
-        }
-    }
-    Assert(strm->avail_out > 0, "bug2");
-
-    if (flush != Z_FINISH) return Z_OK;
-    if (s->wrap <= 0) return Z_STREAM_END;
-
-    /* Write the trailer */
-#ifdef GZIP
-    if (s->wrap == 2) {
-        put_byte(s, (Byte)(strm->adler & 0xff));
-        put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
-        put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
-        put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
-        put_byte(s, (Byte)(strm->total_in & 0xff));
-        put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
-        put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
-        put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
-    }
-    else
-#endif
-    {
-        putShortMSB(s, (uInt)(strm->adler >> 16));
-        putShortMSB(s, (uInt)(strm->adler & 0xffff));
-    }
-    flush_pending(strm);
-    /* If avail_out is zero, the application will call deflate again
-     * to flush the rest.
-     */
-    if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
-    return s->pending != 0 ? Z_OK : Z_STREAM_END;
-}
-
-/* ========================================================================= */
-int ZEXPORT deflateEnd (strm)
-    z_streamp strm;
-{
-    int status;
-
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-
-    status = strm->state->status;
-    if (status != INIT_STATE &&
-        status != EXTRA_STATE &&
-        status != NAME_STATE &&
-        status != COMMENT_STATE &&
-        status != HCRC_STATE &&
-        status != BUSY_STATE &&
-        status != FINISH_STATE) {
-      return Z_STREAM_ERROR;
-    }
-
-    /* Deallocate in reverse order of allocations: */
-    TRY_FREE(strm, strm->state->pending_buf);
-    TRY_FREE(strm, strm->state->head);
-    TRY_FREE(strm, strm->state->prev);
-    TRY_FREE(strm, strm->state->window);
-
-    ZFREE(strm, strm->state);
-    strm->state = Z_NULL;
-
-    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
-}
-
-/* =========================================================================
- * Copy the source state to the destination state.
- * To simplify the source, this is not supported for 16-bit MSDOS (which
- * doesn't have enough memory anyway to duplicate compression states).
- */
-int ZEXPORT deflateCopy (dest, source)
-    z_streamp dest;
-    z_streamp source;
-{
-#ifdef MAXSEG_64K
-    return Z_STREAM_ERROR;
-#else
-    deflate_state *ds;
-    deflate_state *ss;
-    ushf *overlay;
-
-
-    if (source == Z_NULL || dest == Z_NULL || source->state == Z_NULL) {
-        return Z_STREAM_ERROR;
-    }
-
-    ss = source->state;
-
-    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
-
-    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
-    if (ds == Z_NULL) return Z_MEM_ERROR;
-    dest->state = (struct internal_state FAR *) ds;
-    zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
-    ds->strm = dest;
-
-    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
-    ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
-    ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
-    overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
-    ds->pending_buf = (uchf *) overlay;
-
-    if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
-        ds->pending_buf == Z_NULL) {
-        deflateEnd (dest);
-        return Z_MEM_ERROR;
-    }
-    /* following zmemcpy do not work for 16-bit MSDOS */
-    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
-    zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
-    zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
-    zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
-
-    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
-    ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
-    ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
-
-    ds->l_desc.dyn_tree = ds->dyn_ltree;
-    ds->d_desc.dyn_tree = ds->dyn_dtree;
-    ds->bl_desc.dyn_tree = ds->bl_tree;
-
-    return Z_OK;
-#endif /* MAXSEG_64K */
-}
-
-/* ===========================================================================
- * Read a new buffer from the current input stream, update the adler32
- * and total number of bytes read.  All deflate() input goes through
- * this function so some applications may wish to modify it to avoid
- * allocating a large strm->next_in buffer and copying from it.
- * (See also flush_pending()).
- */
-local int read_buf(strm, buf, size)
-    z_streamp strm;
-    Bytef *buf;
-    unsigned size;
-{
-    unsigned len = strm->avail_in;
-
-    if (len > size) len = size;
-    if (len == 0) return 0;
-
-    strm->avail_in  -= len;
-
-    zmemcpy(buf, strm->next_in, len);
-    if (strm->state->wrap == 1) {
-        strm->adler = adler32(strm->adler, buf, len);
-    }
-#ifdef GZIP
-    else if (strm->state->wrap == 2) {
-        strm->adler = crc32(strm->adler, buf, len);
-    }
-#endif
-    strm->next_in  += len;
-    strm->total_in += len;
-
-    return (int)len;
-}
-
-/* ===========================================================================
- * Initialize the "longest match" routines for a new zlib stream
- */
-local void lm_init (s)
-    deflate_state *s;
-{
-    s->window_size = (ulg)2L*s->w_size;
-
-    CLEAR_HASH(s);
-
-    /* Set the default configuration parameters:
-     */
-    s->max_lazy_match   = configuration_table[s->level].max_lazy;
-    s->good_match       = configuration_table[s->level].good_length;
-    s->nice_match       = configuration_table[s->level].nice_length;
-    s->max_chain_length = configuration_table[s->level].max_chain;
-
-    s->strstart = 0;
-    s->block_start = 0L;
-    s->lookahead = 0;
-    s->insert = 0;
-    s->match_length = s->prev_length = MIN_MATCH-1;
-    s->match_available = 0;
-    s->ins_h = 0;
-#ifndef FASTEST
-#ifdef ASMV
-    match_init(); /* initialize the asm code */
-#endif
-#endif
-}
-
-#ifndef FASTEST
-/* ===========================================================================
- * Set match_start to the longest match starting at the given string and
- * return its length. Matches shorter or equal to prev_length are discarded,
- * in which case the result is equal to prev_length and match_start is
- * garbage.
- * IN assertions: cur_match is the head of the hash chain for the current
- *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
- * OUT assertion: the match length is not greater than s->lookahead.
- */
-#ifndef ASMV
-/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
- * match.S. The code will be functionally equivalent.
- */
-local uInt longest_match(s, cur_match)
-    deflate_state *s;
-    IPos cur_match;                             /* current match */
-{
-    unsigned chain_length = s->max_chain_length;/* max hash chain length */
-    register Bytef *scan = s->window + s->strstart; /* current string */
-    register Bytef *match;                       /* matched string */
-    register int len;                           /* length of current match */
-    int best_len = s->prev_length;              /* best match length so far */
-    int nice_match = s->nice_match;             /* stop if match long enough */
-    IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
-        s->strstart - (IPos)MAX_DIST(s) : NIL;
-    /* Stop when cur_match becomes <= limit. To simplify the code,
-     * we prevent matches with the string of window index 0.
-     */
-    Posf *prev = s->prev;
-    uInt wmask = s->w_mask;
-
-#ifdef UNALIGNED_OK
-    /* Compare two bytes at a time. Note: this is not always beneficial.
-     * Try with and without -DUNALIGNED_OK to check.
-     */
-    register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
-    register ush scan_start = *(ushf*)scan;
-    register ush scan_end   = *(ushf*)(scan+best_len-1);
-#else
-    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
-    register Byte scan_end1  = scan[best_len-1];
-    register Byte scan_end   = scan[best_len];
-#endif
-
-    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
-     * It is easy to get rid of this optimization if necessary.
-     */
-    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
-
-    /* Do not waste too much time if we already have a good match: */
-    if (s->prev_length >= s->good_match) {
-        chain_length >>= 2;
-    }
-    /* Do not look for matches beyond the end of the input. This is necessary
-     * to make deflate deterministic.
-     */
-    if ((uInt)nice_match > s->lookahead) nice_match = s->lookahead;
-
-    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
-
-    do {
-        Assert(cur_match < s->strstart, "no future");
-        match = s->window + cur_match;
-
-        /* Skip to next match if the match length cannot increase
-         * or if the match length is less than 2.  Note that the checks below
-         * for insufficient lookahead only occur occasionally for performance
-         * reasons.  Therefore uninitialized memory will be accessed, and
-         * conditional jumps will be made that depend on those values.
-         * However the length of the match is limited to the lookahead, so
-         * the output of deflate is not affected by the uninitialized values.
-         */
-#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
-        /* This code assumes sizeof(unsigned short) == 2. Do not use
-         * UNALIGNED_OK if your compiler uses a different size.
-         */
-        if (*(ushf*)(match+best_len-1) != scan_end ||
-            *(ushf*)match != scan_start) continue;
-
-        /* It is not necessary to compare scan[2] and match[2] since they are
-         * always equal when the other bytes match, given that the hash keys
-         * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
-         * strstart+3, +5, ... up to strstart+257. We check for insufficient
-         * lookahead only every 4th comparison; the 128th check will be made
-         * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
-         * necessary to put more guard bytes at the end of the window, or
-         * to check more often for insufficient lookahead.
-         */
-        Assert(scan[2] == match[2], "scan[2]?");
-        scan++, match++;
-        do {
-        } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
-                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
-                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
-                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
-                 scan < strend);
-        /* The funny "do {}" generates better code on most compilers */
-
-        /* Here, scan <= window+strstart+257 */
-        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
-        if (*scan == *match) scan++;
-
-        len = (MAX_MATCH - 1) - (int)(strend-scan);
-        scan = strend - (MAX_MATCH-1);
-
-#else /* UNALIGNED_OK */
-
-        if (match[best_len]   != scan_end  ||
-            match[best_len-1] != scan_end1 ||
-            *match            != *scan     ||
-            *++match          != scan[1])      continue;
-
-        /* The check at best_len-1 can be removed because it will be made
-         * again later. (This heuristic is not always a win.)
-         * It is not necessary to compare scan[2] and match[2] since they
-         * are always equal when the other bytes match, given that
-         * the hash keys are equal and that HASH_BITS >= 8.
-         */
-        scan += 2, match++;
-        Assert(*scan == *match, "match[2]?");
-
-        /* We check for insufficient lookahead only every 8th comparison;
-         * the 256th check will be made at strstart+258.
-         */
-        do {
-        } while (*++scan == *++match && *++scan == *++match &&
-                 *++scan == *++match && *++scan == *++match &&
-                 *++scan == *++match && *++scan == *++match &&
-                 *++scan == *++match && *++scan == *++match &&
-                 scan < strend);
-
-        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
-
-        len = MAX_MATCH - (int)(strend - scan);
-        scan = strend - MAX_MATCH;
-
-#endif /* UNALIGNED_OK */
-
-        if (len > best_len) {
-            s->match_start = cur_match;
-            best_len = len;
-            if (len >= nice_match) break;
-#ifdef UNALIGNED_OK
-            scan_end = *(ushf*)(scan+best_len-1);
-#else
-            scan_end1  = scan[best_len-1];
-            scan_end   = scan[best_len];
-#endif
-        }
-    } while ((cur_match = prev[cur_match & wmask]) > limit
-             && --chain_length != 0);
-
-    if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
-    return s->lookahead;
-}
-#endif /* ASMV */
-
-#else /* FASTEST */
-
-/* ---------------------------------------------------------------------------
- * Optimized version for FASTEST only
- */
-local uInt longest_match(s, cur_match)
-    deflate_state *s;
-    IPos cur_match;                             /* current match */
-{
-    register Bytef *scan = s->window + s->strstart; /* current string */
-    register Bytef *match;                       /* matched string */
-    register int len;                           /* length of current match */
-    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
-
-    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
-     * It is easy to get rid of this optimization if necessary.
-     */
-    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
-
-    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
-
-    Assert(cur_match < s->strstart, "no future");
-
-    match = s->window + cur_match;
-
-    /* Return failure if the match length is less than 2:
-     */
-    if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
-
-    /* The check at best_len-1 can be removed because it will be made
-     * again later. (This heuristic is not always a win.)
-     * It is not necessary to compare scan[2] and match[2] since they
-     * are always equal when the other bytes match, given that
-     * the hash keys are equal and that HASH_BITS >= 8.
-     */
-    scan += 2, match += 2;
-    Assert(*scan == *match, "match[2]?");
-
-    /* We check for insufficient lookahead only every 8th comparison;
-     * the 256th check will be made at strstart+258.
-     */
-    do {
-    } while (*++scan == *++match && *++scan == *++match &&
-             *++scan == *++match && *++scan == *++match &&
-             *++scan == *++match && *++scan == *++match &&
-             *++scan == *++match && *++scan == *++match &&
-             scan < strend);
-
-    Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
-
-    len = MAX_MATCH - (int)(strend - scan);
-
-    if (len < MIN_MATCH) return MIN_MATCH - 1;
-
-    s->match_start = cur_match;
-    return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
-}
-
-#endif /* FASTEST */
-
-#ifdef DEBUG
-/* ===========================================================================
- * Check that the match at match_start is indeed a match.
- */
-local void check_match(s, start, match, length)
-    deflate_state *s;
-    IPos start, match;
-    int length;
-{
-    /* check that the match is indeed a match */
-    if (zmemcmp(s->window + match,
-                s->window + start, length) != EQUAL) {
-        fprintf(stderr, " start %u, match %u, length %d\n",
-                start, match, length);
-        do {
-            fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
-        } while (--length != 0);
-        z_error("invalid match");
-    }
-    if (z_verbose > 1) {
-        fprintf(stderr,"\\[%d,%d]", start-match, length);
-        do { putc(s->window[start++], stderr); } while (--length != 0);
-    }
-}
-#else
-#  define check_match(s, start, match, length)
-#endif /* DEBUG */
-
-/* ===========================================================================
- * Fill the window when the lookahead becomes insufficient.
- * Updates strstart and lookahead.
- *
- * IN assertion: lookahead < MIN_LOOKAHEAD
- * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
- *    At least one byte has been read, or avail_in == 0; reads are
- *    performed for at least two bytes (required for the zip translate_eol
- *    option -- not supported here).
- */
-local void fill_window(s)
-    deflate_state *s;
-{
-    register unsigned n, m;
-    register Posf *p;
-    unsigned more;    /* Amount of free space at the end of the window. */
-    uInt wsize = s->w_size;
-
-    Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
-
-    do {
-        more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
-
-        /* Deal with !@#$% 64K limit: */
-        if (sizeof(int) <= 2) {
-            if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
-                more = wsize;
-
-            } else if (more == (unsigned)(-1)) {
-                /* Very unlikely, but possible on 16 bit machine if
-                 * strstart == 0 && lookahead == 1 (input done a byte at time)
-                 */
-                more--;
-            }
-        }
-
-        /* If the window is almost full and there is insufficient lookahead,
-         * move the upper half to the lower one to make room in the upper half.
-         */
-        if (s->strstart >= wsize+MAX_DIST(s)) {
-
-            zmemcpy(s->window, s->window+wsize, (unsigned)wsize);
-            s->match_start -= wsize;
-            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
-            s->block_start -= (long) wsize;
-
-            /* Slide the hash table (could be avoided with 32 bit values
-               at the expense of memory usage). We slide even when level == 0
-               to keep the hash table consistent if we switch back to level > 0
-               later. (Using level 0 permanently is not an optimal usage of
-               zlib, so we don't care about this pathological case.)
-             */
-            n = s->hash_size;
-            p = &s->head[n];
-            do {
-                m = *--p;
-                *p = (Pos)(m >= wsize ? m-wsize : NIL);
-            } while (--n);
-
-            n = wsize;
-#ifndef FASTEST
-            p = &s->prev[n];
-            do {
-                m = *--p;
-                *p = (Pos)(m >= wsize ? m-wsize : NIL);
-                /* If n is not on any hash chain, prev[n] is garbage but
-                 * its value will never be used.
-                 */
-            } while (--n);
-#endif
-            more += wsize;
-        }
-        if (s->strm->avail_in == 0) break;
-
-        /* If there was no sliding:
-         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
-         *    more == window_size - lookahead - strstart
-         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
-         * => more >= window_size - 2*WSIZE + 2
-         * In the BIG_MEM or MMAP case (not yet supported),
-         *   window_size == input_size + MIN_LOOKAHEAD  &&
-         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
-         * Otherwise, window_size == 2*WSIZE so more >= 2.
-         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
-         */
-        Assert(more >= 2, "more < 2");
-
-        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
-        s->lookahead += n;
-
-        /* Initialize the hash value now that we have some input: */
-        if (s->lookahead + s->insert >= MIN_MATCH) {
-            uInt str = s->strstart - s->insert;
-            s->ins_h = s->window[str];
-            UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
-#if MIN_MATCH != 3
-            Call UPDATE_HASH() MIN_MATCH-3 more times
-#endif
-            while (s->insert) {
-                UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
-#ifndef FASTEST
-                s->prev[str & s->w_mask] = s->head[s->ins_h];
-#endif
-                s->head[s->ins_h] = (Pos)str;
-                str++;
-                s->insert--;
-                if (s->lookahead + s->insert < MIN_MATCH)
-                    break;
-            }
-        }
-        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
-         * but this is not important since only literal bytes will be emitted.
-         */
-
-    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
-
-    /* If the WIN_INIT bytes after the end of the current data have never been
-     * written, then zero those bytes in order to avoid memory check reports of
-     * the use of uninitialized (or uninitialised as Julian writes) bytes by
-     * the longest match routines.  Update the high water mark for the next
-     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
-     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
-     */
-    if (s->high_water < s->window_size) {
-        ulg curr = s->strstart + (ulg)(s->lookahead);
-        ulg init;
-
-        if (s->high_water < curr) {
-            /* Previous high water mark below current data -- zero WIN_INIT
-             * bytes or up to end of window, whichever is less.
-             */
-            init = s->window_size - curr;
-            if (init > WIN_INIT)
-                init = WIN_INIT;
-            zmemzero(s->window + curr, (unsigned)init);
-            s->high_water = curr + init;
-        }
-        else if (s->high_water < (ulg)curr + WIN_INIT) {
-            /* High water mark at or above current data, but below current data
-             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
-             * to end of window, whichever is less.
-             */
-            init = (ulg)curr + WIN_INIT - s->high_water;
-            if (init > s->window_size - s->high_water)
-                init = s->window_size - s->high_water;
-            zmemzero(s->window + s->high_water, (unsigned)init);
-            s->high_water += init;
-        }
-    }
-
-    Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
-           "not enough room for search");
-}
-
-/* ===========================================================================
- * Flush the current block, with given end-of-file flag.
- * IN assertion: strstart is set to the end of the current match.
- */
-#define FLUSH_BLOCK_ONLY(s, last) { \
-   _tr_flush_block(s, (s->block_start >= 0L ? \
-                   (charf *)&s->window[(unsigned)s->block_start] : \
-                   (charf *)Z_NULL), \
-                (ulg)((long)s->strstart - s->block_start), \
-                (last)); \
-   s->block_start = s->strstart; \
-   flush_pending(s->strm); \
-   Tracev((stderr,"[FLUSH]")); \
-}
-
-/* Same but force premature exit if necessary. */
-#define FLUSH_BLOCK(s, last) { \
-   FLUSH_BLOCK_ONLY(s, last); \
-   if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
-}
-
-/* ===========================================================================
- * Copy without compression as much as possible from the input stream, return
- * the current block state.
- * This function does not insert new strings in the dictionary since
- * uncompressible data is probably not useful. This function is used
- * only for the level=0 compression option.
- * NOTE: this function should be optimized to avoid extra copying from
- * window to pending_buf.
- */
-local block_state deflate_stored(s, flush)
-    deflate_state *s;
-    int flush;
-{
-    /* Stored blocks are limited to 0xffff bytes, pending_buf is limited
-     * to pending_buf_size, and each stored block has a 5 byte header:
-     */
-    ulg max_block_size = 0xffff;
-    ulg max_start;
-
-    if (max_block_size > s->pending_buf_size - 5) {
-        max_block_size = s->pending_buf_size - 5;
-    }
-
-    /* Copy as much as possible from input to output: */
-    for (;;) {
-        /* Fill the window as much as possible: */
-        if (s->lookahead <= 1) {
-
-            Assert(s->strstart < s->w_size+MAX_DIST(s) ||
-                   s->block_start >= (long)s->w_size, "slide too late");
-
-            fill_window(s);
-            if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
-
-            if (s->lookahead == 0) break; /* flush the current block */
-        }
-        Assert(s->block_start >= 0L, "block gone");
-
-        s->strstart += s->lookahead;
-        s->lookahead = 0;
-
-        /* Emit a stored block if pending_buf will be full: */
-        max_start = s->block_start + max_block_size;
-        if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
-            /* strstart == 0 is possible when wraparound on 16-bit machine */
-            s->lookahead = (uInt)(s->strstart - max_start);
-            s->strstart = (uInt)max_start;
-            FLUSH_BLOCK(s, 0);
-        }
-        /* Flush if we may have to slide, otherwise block_start may become
-         * negative and the data will be gone:
-         */
-        if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
-            FLUSH_BLOCK(s, 0);
-        }
-    }
-    s->insert = 0;
-    if (flush == Z_FINISH) {
-        FLUSH_BLOCK(s, 1);
-        return finish_done;
-    }
-    if ((long)s->strstart > s->block_start)
-        FLUSH_BLOCK(s, 0);
-    return block_done;
-}
-
-/* ===========================================================================
- * Compress as much as possible from the input stream, return the current
- * block state.
- * This function does not perform lazy evaluation of matches and inserts
- * new strings in the dictionary only for unmatched strings or for short
- * matches. It is used only for the fast compression options.
- */
-local block_state deflate_fast(s, flush)
-    deflate_state *s;
-    int flush;
-{
-    IPos hash_head;       /* head of the hash chain */
-    int bflush;           /* set if current block must be flushed */
-
-    for (;;) {
-        /* Make sure that we always have enough lookahead, except
-         * at the end of the input file. We need MAX_MATCH bytes
-         * for the next match, plus MIN_MATCH bytes to insert the
-         * string following the next match.
-         */
-        if (s->lookahead < MIN_LOOKAHEAD) {
-            fill_window(s);
-            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
-                return need_more;
-            }
-            if (s->lookahead == 0) break; /* flush the current block */
-        }
-
-        /* Insert the string window[strstart .. strstart+2] in the
-         * dictionary, and set hash_head to the head of the hash chain:
-         */
-        hash_head = NIL;
-        if (s->lookahead >= MIN_MATCH) {
-            INSERT_STRING(s, s->strstart, hash_head);
-        }
-
-        /* Find the longest match, discarding those <= prev_length.
-         * At this point we have always match_length < MIN_MATCH
-         */
-        if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
-            /* To simplify the code, we prevent matches with the string
-             * of window index 0 (in particular we have to avoid a match
-             * of the string with itself at the start of the input file).
-             */
-            s->match_length = longest_match (s, hash_head);
-            /* longest_match() sets match_start */
-        }
-        if (s->match_length >= MIN_MATCH) {
-            check_match(s, s->strstart, s->match_start, s->match_length);
-
-            _tr_tally_dist(s, s->strstart - s->match_start,
-                           s->match_length - MIN_MATCH, bflush);
-
-            s->lookahead -= s->match_length;
-
-            /* Insert new strings in the hash table only if the match length
-             * is not too large. This saves time but degrades compression.
-             */
-#ifndef FASTEST
-            if (s->match_length <= s->max_insert_length &&
-                s->lookahead >= MIN_MATCH) {
-                s->match_length--; /* string at strstart already in table */
-                do {
-                    s->strstart++;
-                    INSERT_STRING(s, s->strstart, hash_head);
-                    /* strstart never exceeds WSIZE-MAX_MATCH, so there are
-                     * always MIN_MATCH bytes ahead.
-                     */
-                } while (--s->match_length != 0);
-                s->strstart++;
-            } else
-#endif
-            {
-                s->strstart += s->match_length;
-                s->match_length = 0;
-                s->ins_h = s->window[s->strstart];
-                UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
-#if MIN_MATCH != 3
-                Call UPDATE_HASH() MIN_MATCH-3 more times
-#endif
-                /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
-                 * matter since it will be recomputed at next deflate call.
-                 */
-            }
-        } else {
-            /* No match, output a literal byte */
-            Tracevv((stderr,"%c", s->window[s->strstart]));
-            _tr_tally_lit (s, s->window[s->strstart], bflush);
-            s->lookahead--;
-            s->strstart++;
-        }
-        if (bflush) FLUSH_BLOCK(s, 0);
-    }
-    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
-    if (flush == Z_FINISH) {
-        FLUSH_BLOCK(s, 1);
-        return finish_done;
-    }
-    if (s->last_lit)
-        FLUSH_BLOCK(s, 0);
-    return block_done;
-}
-
-#ifndef FASTEST
-/* ===========================================================================
- * Same as above, but achieves better compression. We use a lazy
- * evaluation for matches: a match is finally adopted only if there is
- * no better match at the next window position.
- */
-local block_state deflate_slow(s, flush)
-    deflate_state *s;
-    int flush;
-{
-    IPos hash_head;          /* head of hash chain */
-    int bflush;              /* set if current block must be flushed */
-
-    /* Process the input block. */
-    for (;;) {
-        /* Make sure that we always have enough lookahead, except
-         * at the end of the input file. We need MAX_MATCH bytes
-         * for the next match, plus MIN_MATCH bytes to insert the
-         * string following the next match.
-         */
-        if (s->lookahead < MIN_LOOKAHEAD) {
-            fill_window(s);
-            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
-                return need_more;
-            }
-            if (s->lookahead == 0) break; /* flush the current block */
-        }
-
-        /* Insert the string window[strstart .. strstart+2] in the
-         * dictionary, and set hash_head to the head of the hash chain:
-         */
-        hash_head = NIL;
-        if (s->lookahead >= MIN_MATCH) {
-            INSERT_STRING(s, s->strstart, hash_head);
-        }
-
-        /* Find the longest match, discarding those <= prev_length.
-         */
-        s->prev_length = s->match_length, s->prev_match = s->match_start;
-        s->match_length = MIN_MATCH-1;
-
-        if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
-            s->strstart - hash_head <= MAX_DIST(s)) {
-            /* To simplify the code, we prevent matches with the string
-             * of window index 0 (in particular we have to avoid a match
-             * of the string with itself at the start of the input file).
-             */
-            s->match_length = longest_match (s, hash_head);
-            /* longest_match() sets match_start */
-
-            if (s->match_length <= 5 && (s->strategy == Z_FILTERED
-#if TOO_FAR <= 32767
-                || (s->match_length == MIN_MATCH &&
-                    s->strstart - s->match_start > TOO_FAR)
-#endif
-                )) {
-
-                /* If prev_match is also MIN_MATCH, match_start is garbage
-                 * but we will ignore the current match anyway.
-                 */
-                s->match_length = MIN_MATCH-1;
-            }
-        }
-        /* If there was a match at the previous step and the current
-         * match is not better, output the previous match:
-         */
-        if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
-            uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
-            /* Do not insert strings in hash table beyond this. */
-
-            check_match(s, s->strstart-1, s->prev_match, s->prev_length);
-
-            _tr_tally_dist(s, s->strstart -1 - s->prev_match,
-                           s->prev_length - MIN_MATCH, bflush);
-
-            /* Insert in hash table all strings up to the end of the match.
-             * strstart-1 and strstart are already inserted. If there is not
-             * enough lookahead, the last two strings are not inserted in
-             * the hash table.
-             */
-            s->lookahead -= s->prev_length-1;
-            s->prev_length -= 2;
-            do {
-                if (++s->strstart <= max_insert) {
-                    INSERT_STRING(s, s->strstart, hash_head);
-                }
-            } while (--s->prev_length != 0);
-            s->match_available = 0;
-            s->match_length = MIN_MATCH-1;
-            s->strstart++;
-
-            if (bflush) FLUSH_BLOCK(s, 0);
-
-        } else if (s->match_available) {
-            /* If there was no match at the previous position, output a
-             * single literal. If there was a match but the current match
-             * is longer, truncate the previous match to a single literal.
-             */
-            Tracevv((stderr,"%c", s->window[s->strstart-1]));
-            _tr_tally_lit(s, s->window[s->strstart-1], bflush);
-            if (bflush) {
-                FLUSH_BLOCK_ONLY(s, 0);
-            }
-            s->strstart++;
-            s->lookahead--;
-            if (s->strm->avail_out == 0) return need_more;
-        } else {
-            /* There is no previous match to compare with, wait for
-             * the next step to decide.
-             */
-            s->match_available = 1;
-            s->strstart++;
-            s->lookahead--;
-        }
-    }
-    Assert (flush != Z_NO_FLUSH, "no flush?");
-    if (s->match_available) {
-        Tracevv((stderr,"%c", s->window[s->strstart-1]));
-        _tr_tally_lit(s, s->window[s->strstart-1], bflush);
-        s->match_available = 0;
-    }
-    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
-    if (flush == Z_FINISH) {
-        FLUSH_BLOCK(s, 1);
-        return finish_done;
-    }
-    if (s->last_lit)
-        FLUSH_BLOCK(s, 0);
-    return block_done;
-}
-#endif /* FASTEST */
-
-/* ===========================================================================
- * For Z_RLE, simply look for runs of bytes, generate matches only of distance
- * one.  Do not maintain a hash table.  (It will be regenerated if this run of
- * deflate switches away from Z_RLE.)
- */
-local block_state deflate_rle(s, flush)
-    deflate_state *s;
-    int flush;
-{
-    int bflush;             /* set if current block must be flushed */
-    uInt prev;              /* byte at distance one to match */
-    Bytef *scan, *strend;   /* scan goes up to strend for length of run */
-
-    for (;;) {
-        /* Make sure that we always have enough lookahead, except
-         * at the end of the input file. We need MAX_MATCH bytes
-         * for the longest run, plus one for the unrolled loop.
-         */
-        if (s->lookahead <= MAX_MATCH) {
-            fill_window(s);
-            if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
-                return need_more;
-            }
-            if (s->lookahead == 0) break; /* flush the current block */
-        }
-
-        /* See how many times the previous byte repeats */
-        s->match_length = 0;
-        if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
-            scan = s->window + s->strstart - 1;
-            prev = *scan;
-            if (prev == *++scan && prev == *++scan && prev == *++scan) {
-                strend = s->window + s->strstart + MAX_MATCH;
-                do {
-                } while (prev == *++scan && prev == *++scan &&
-                         prev == *++scan && prev == *++scan &&
-                         prev == *++scan && prev == *++scan &&
-                         prev == *++scan && prev == *++scan &&
-                         scan < strend);
-                s->match_length = MAX_MATCH - (int)(strend - scan);
-                if (s->match_length > s->lookahead)
-                    s->match_length = s->lookahead;
-            }
-            Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
-        }
-
-        /* Emit match if have run of MIN_MATCH or longer, else emit literal */
-        if (s->match_length >= MIN_MATCH) {
-            check_match(s, s->strstart, s->strstart - 1, s->match_length);
-
-            _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
-
-            s->lookahead -= s->match_length;
-            s->strstart += s->match_length;
-            s->match_length = 0;
-        } else {
-            /* No match, output a literal byte */
-            Tracevv((stderr,"%c", s->window[s->strstart]));
-            _tr_tally_lit (s, s->window[s->strstart], bflush);
-            s->lookahead--;
-            s->strstart++;
-        }
-        if (bflush) FLUSH_BLOCK(s, 0);
-    }
-    s->insert = 0;
-    if (flush == Z_FINISH) {
-        FLUSH_BLOCK(s, 1);
-        return finish_done;
-    }
-    if (s->last_lit)
-        FLUSH_BLOCK(s, 0);
-    return block_done;
-}
-
-/* ===========================================================================
- * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
- * (It will be regenerated if this run of deflate switches away from Huffman.)
- */
-local block_state deflate_huff(s, flush)
-    deflate_state *s;
-    int flush;
-{
-    int bflush;             /* set if current block must be flushed */
-
-    for (;;) {
-        /* Make sure that we have a literal to write. */
-        if (s->lookahead == 0) {
-            fill_window(s);
-            if (s->lookahead == 0) {
-                if (flush == Z_NO_FLUSH)
-                    return need_more;
-                break;      /* flush the current block */
-            }
-        }
-
-        /* Output a literal byte */
-        s->match_length = 0;
-        Tracevv((stderr,"%c", s->window[s->strstart]));
-        _tr_tally_lit (s, s->window[s->strstart], bflush);
-        s->lookahead--;
-        s->strstart++;
-        if (bflush) FLUSH_BLOCK(s, 0);
-    }
-    s->insert = 0;
-    if (flush == Z_FINISH) {
-        FLUSH_BLOCK(s, 1);
-        return finish_done;
-    }
-    if (s->last_lit)
-        FLUSH_BLOCK(s, 0);
-    return block_done;
-}
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/deflate.h	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,370 +0,0 @@
-/*
- * 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.
- */
-
-/* deflate.h -- internal compression state
- * Copyright (C) 1995-2012 Jean-loup Gailly
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/* WARNING: this file should *not* be used by applications. It is
-   part of the implementation of the compression library and is
-   subject to change. Applications should only use zlib.h.
- */
-
-/* @(#) $Id$ */
-
-#ifndef DEFLATE_H
-#define DEFLATE_H
-
-#include "zutil.h"
-
-/* define NO_GZIP when compiling if you want to disable gzip header and
-   trailer creation by deflate().  NO_GZIP would be used to avoid linking in
-   the crc code when it is not needed.  For shared libraries, gzip encoding
-   should be left enabled. */
-#ifndef NO_GZIP
-#  define GZIP
-#endif
-
-/* ===========================================================================
- * Internal compression state.
- */
-
-#define LENGTH_CODES 29
-/* number of length codes, not counting the special END_BLOCK code */
-
-#define LITERALS  256
-/* number of literal bytes 0..255 */
-
-#define L_CODES (LITERALS+1+LENGTH_CODES)
-/* number of Literal or Length codes, including the END_BLOCK code */
-
-#define D_CODES   30
-/* number of distance codes */
-
-#define BL_CODES  19
-/* number of codes used to transfer the bit lengths */
-
-#define HEAP_SIZE (2*L_CODES+1)
-/* maximum heap size */
-
-#define MAX_BITS 15
-/* All codes must not exceed MAX_BITS bits */
-
-#define Buf_size 16
-/* size of bit buffer in bi_buf */
-
-#define INIT_STATE    42
-#define EXTRA_STATE   69
-#define NAME_STATE    73
-#define COMMENT_STATE 91
-#define HCRC_STATE   103
-#define BUSY_STATE   113
-#define FINISH_STATE 666
-/* Stream status */
-
-
-/* Data structure describing a single value and its code string. */
-typedef struct ct_data_s {
-    union {
-        ush  freq;       /* frequency count */
-        ush  code;       /* bit string */
-    } fc;
-    union {
-        ush  dad;        /* father node in Huffman tree */
-        ush  len;        /* length of bit string */
-    } dl;
-} FAR ct_data;
-
-#define Freq fc.freq
-#define Code fc.code
-#define Dad  dl.dad
-#define Len  dl.len
-
-typedef struct static_tree_desc_s  static_tree_desc;
-
-typedef struct tree_desc_s {
-    ct_data *dyn_tree;           /* the dynamic tree */
-    int     max_code;            /* largest code with non zero frequency */
-    static_tree_desc *stat_desc; /* the corresponding static tree */
-} FAR tree_desc;
-
-typedef ush Pos;
-typedef Pos FAR Posf;
-typedef unsigned IPos;
-
-/* A Pos is an index in the character window. We use short instead of int to
- * save space in the various tables. IPos is used only for parameter passing.
- */
-
-typedef struct internal_state {
-    z_streamp strm;      /* pointer back to this zlib stream */
-    int   status;        /* as the name implies */
-    Bytef *pending_buf;  /* output still pending */
-    ulg   pending_buf_size; /* size of pending_buf */
-    Bytef *pending_out;  /* next pending byte to output to the stream */
-    uInt   pending;      /* nb of bytes in the pending buffer */
-    int   wrap;          /* bit 0 true for zlib, bit 1 true for gzip */
-    gz_headerp  gzhead;  /* gzip header information to write */
-    uInt   gzindex;      /* where in extra, name, or comment */
-    Byte  method;        /* can only be DEFLATED */
-    int   last_flush;    /* value of flush param for previous deflate call */
-
-                /* used by deflate.c: */
-
-    uInt  w_size;        /* LZ77 window size (32K by default) */
-    uInt  w_bits;        /* log2(w_size)  (8..16) */
-    uInt  w_mask;        /* w_size - 1 */
-
-    Bytef *window;
-    /* Sliding window. Input bytes are read into the second half of the window,
-     * and move to the first half later to keep a dictionary of at least wSize
-     * bytes. With this organization, matches are limited to a distance of
-     * wSize-MAX_MATCH bytes, but this ensures that IO is always
-     * performed with a length multiple of the block size. Also, it limits
-     * the window size to 64K, which is quite useful on MSDOS.
-     * To do: use the user input buffer as sliding window.
-     */
-
-    ulg window_size;
-    /* Actual size of window: 2*wSize, except when the user input buffer
-     * is directly used as sliding window.
-     */
-
-    Posf *prev;
-    /* Link to older string with same hash index. To limit the size of this
-     * array to 64K, this link is maintained only for the last 32K strings.
-     * An index in this array is thus a window index modulo 32K.
-     */
-
-    Posf *head; /* Heads of the hash chains or NIL. */
-
-    uInt  ins_h;          /* hash index of string to be inserted */
-    uInt  hash_size;      /* number of elements in hash table */
-    uInt  hash_bits;      /* log2(hash_size) */
-    uInt  hash_mask;      /* hash_size-1 */
-
-    uInt  hash_shift;
-    /* Number of bits by which ins_h must be shifted at each input
-     * step. It must be such that after MIN_MATCH steps, the oldest
-     * byte no longer takes part in the hash key, that is:
-     *   hash_shift * MIN_MATCH >= hash_bits
-     */
-
-    long block_start;
-    /* Window position at the beginning of the current output block. Gets
-     * negative when the window is moved backwards.
-     */
-
-    uInt match_length;           /* length of best match */
-    IPos prev_match;             /* previous match */
-    int match_available;         /* set if previous match exists */
-    uInt strstart;               /* start of string to insert */
-    uInt match_start;            /* start of matching string */
-    uInt lookahead;              /* number of valid bytes ahead in window */
-
-    uInt prev_length;
-    /* Length of the best match at previous step. Matches not greater than this
-     * are discarded. This is used in the lazy match evaluation.
-     */
-
-    uInt max_chain_length;
-    /* To speed up deflation, hash chains are never searched beyond this
-     * length.  A higher limit improves compression ratio but degrades the
-     * speed.
-     */
-
-    uInt max_lazy_match;
-    /* Attempt to find a better match only when the current match is strictly
-     * smaller than this value. This mechanism is used only for compression
-     * levels >= 4.
-     */
-#   define max_insert_length  max_lazy_match
-    /* Insert new strings in the hash table only if the match length is not
-     * greater than this length. This saves time but degrades compression.
-     * max_insert_length is used only for compression levels <= 3.
-     */
-
-    int level;    /* compression level (1..9) */
-    int strategy; /* favor or force Huffman coding*/
-
-    uInt good_match;
-    /* Use a faster search when the previous match is longer than this */
-
-    int nice_match; /* Stop searching when current match exceeds this */
-
-                /* used by trees.c: */
-    /* Didn't use ct_data typedef below to suppress compiler warning */
-    struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
-    struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
-    struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
-
-    struct tree_desc_s l_desc;               /* desc. for literal tree */
-    struct tree_desc_s d_desc;               /* desc. for distance tree */
-    struct tree_desc_s bl_desc;              /* desc. for bit length tree */
-
-    ush bl_count[MAX_BITS+1];
-    /* number of codes at each bit length for an optimal tree */
-
-    int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
-    int heap_len;               /* number of elements in the heap */
-    int heap_max;               /* element of largest frequency */
-    /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
-     * The same heap array is used to build all trees.
-     */
-
-    uch depth[2*L_CODES+1];
-    /* Depth of each subtree used as tie breaker for trees of equal frequency
-     */
-
-    uchf *l_buf;          /* buffer for literals or lengths */
-
-    uInt  lit_bufsize;
-    /* Size of match buffer for literals/lengths.  There are 4 reasons for
-     * limiting lit_bufsize to 64K:
-     *   - frequencies can be kept in 16 bit counters
-     *   - if compression is not successful for the first block, all input
-     *     data is still in the window so we can still emit a stored block even
-     *     when input comes from standard input.  (This can also be done for
-     *     all blocks if lit_bufsize is not greater than 32K.)
-     *   - if compression is not successful for a file smaller than 64K, we can
-     *     even emit a stored file instead of a stored block (saving 5 bytes).
-     *     This is applicable only for zip (not gzip or zlib).
-     *   - creating new Huffman trees less frequently may not provide fast
-     *     adaptation to changes in the input data statistics. (Take for
-     *     example a binary file with poorly compressible code followed by
-     *     a highly compressible string table.) Smaller buffer sizes give
-     *     fast adaptation but have of course the overhead of transmitting
-     *     trees more frequently.
-     *   - I can't count above 4
-     */
-
-    uInt last_lit;      /* running index in l_buf */
-
-    ushf *d_buf;
-    /* Buffer for distances. To simplify the code, d_buf and l_buf have
-     * the same number of elements. To use different lengths, an extra flag
-     * array would be necessary.
-     */
-
-    ulg opt_len;        /* bit length of current block with optimal trees */
-    ulg static_len;     /* bit length of current block with static trees */
-    uInt matches;       /* number of string matches in current block */
-    uInt insert;        /* bytes at end of window left to insert */
-
-#ifdef DEBUG
-    ulg compressed_len; /* total bit length of compressed file mod 2^32 */
-    ulg bits_sent;      /* bit length of compressed data sent mod 2^32 */
-#endif
-
-    ush bi_buf;
-    /* Output buffer. bits are inserted starting at the bottom (least
-     * significant bits).
-     */
-    int bi_valid;
-    /* Number of valid bits in bi_buf.  All bits above the last valid bit
-     * are always zero.
-     */
-
-    ulg high_water;
-    /* High water mark offset in window for initialized bytes -- bytes above
-     * this are set to zero in order to avoid memory check warnings when
-     * longest match routines access bytes past the input.  This is then
-     * updated to the new high water mark.
-     */
-
-} FAR deflate_state;
-
-/* Output a byte on the stream.
- * IN assertion: there is enough room in pending_buf.
- */
-#define put_byte(s, c) {s->pending_buf[s->pending++] = (c);}
-
-
-#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
-/* Minimum amount of lookahead, except at the end of the input file.
- * See deflate.c for comments about the MIN_MATCH+1.
- */
-
-#define MAX_DIST(s)  ((s)->w_size-MIN_LOOKAHEAD)
-/* In order to simplify the code, particularly on 16 bit machines, match
- * distances are limited to MAX_DIST instead of WSIZE.
- */
-
-#define WIN_INIT MAX_MATCH
-/* Number of bytes after end of data in window to initialize in order to avoid
-   memory checker errors from longest match routines */
-
-        /* in trees.c */
-void ZLIB_INTERNAL _tr_init OF((deflate_state *s));
-int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
-void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf,
-                        ulg stored_len, int last));
-void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s));
-void ZLIB_INTERNAL _tr_align OF((deflate_state *s));
-void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,
-                        ulg stored_len, int last));
-
-#define d_code(dist) \
-   ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
-/* Mapping from a distance to a distance code. dist is the distance - 1 and
- * must not have side effects. _dist_code[256] and _dist_code[257] are never
- * used.
- */
-
-#ifndef DEBUG
-/* Inline versions of _tr_tally for speed: */
-
-#if defined(GEN_TREES_H) || !defined(STDC)
-  extern uch ZLIB_INTERNAL _length_code[];
-  extern uch ZLIB_INTERNAL _dist_code[];
-#else
-  extern const uch ZLIB_INTERNAL _length_code[];
-  extern const uch ZLIB_INTERNAL _dist_code[];
-#endif
-
-# define _tr_tally_lit(s, c, flush) \
-  { uch cc = (c); \
-    s->d_buf[s->last_lit] = 0; \
-    s->l_buf[s->last_lit++] = cc; \
-    s->dyn_ltree[cc].Freq++; \
-    flush = (s->last_lit == s->lit_bufsize-1); \
-   }
-# define _tr_tally_dist(s, distance, length, flush) \
-  { uch len = (length); \
-    ush dist = (distance); \
-    s->d_buf[s->last_lit] = dist; \
-    s->l_buf[s->last_lit++] = len; \
-    dist--; \
-    s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
-    s->dyn_dtree[d_code(dist)].Freq++; \
-    flush = (s->last_lit == s->lit_bufsize-1); \
-  }
-#else
-# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
-# define _tr_tally_dist(s, distance, length, flush) \
-              flush = _tr_tally(s, distance, length)
-#endif
-
-#endif /* DEFLATE_H */
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzclose.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,49 +0,0 @@
-/*
- * 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.
- */
-
-/* gzclose.c -- zlib gzclose() function
- * Copyright (C) 2004, 2010 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-#include "gzguts.h"
-
-/* gzclose() is in a separate file so that it is linked in only if it is used.
-   That way the other gzclose functions can be used instead to avoid linking in
-   unneeded compression or decompression routines. */
-int ZEXPORT gzclose(file)
-    gzFile file;
-{
-#ifndef NO_GZCOMPRESS
-    gz_statep state;
-
-    if (file == NULL)
-        return Z_STREAM_ERROR;
-    state = (gz_statep)file;
-
-    return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file);
-#else
-    return gzclose_r(file);
-#endif
-}
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzguts.h	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,233 +0,0 @@
-/*
- * 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.
- */
-
-/* gzguts.h -- zlib internal header definitions for gz* operations
- * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-#ifdef _LARGEFILE64_SOURCE
-#  ifndef _LARGEFILE_SOURCE
-#    define _LARGEFILE_SOURCE 1
-#  endif
-#  ifdef _FILE_OFFSET_BITS
-#    undef _FILE_OFFSET_BITS
-#  endif
-#endif
-
-#ifdef HAVE_HIDDEN
-#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
-#else
-#  define ZLIB_INTERNAL
-#endif
-
-#include <stdio.h>
-#include "zlib.h"
-#ifdef STDC
-#  include <string.h>
-#  include <stdlib.h>
-#  include <limits.h>
-#endif
-#include <fcntl.h>
-
-#ifdef _WIN32
-#  include <stddef.h>
-#endif
-
-#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32)
-#  include <io.h>
-#endif
-
-#ifdef WINAPI_FAMILY
-#  define open _open
-#  define read _read
-#  define write _write
-#  define close _close
-#endif
-
-#ifdef NO_DEFLATE       /* for compatibility with old definition */
-#  define NO_GZCOMPRESS
-#endif
-
-#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
-#  ifndef HAVE_VSNPRINTF
-#    define HAVE_VSNPRINTF
-#  endif
-#endif
-
-#if defined(__CYGWIN__)
-#  ifndef HAVE_VSNPRINTF
-#    define HAVE_VSNPRINTF
-#  endif
-#endif
-
-#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410)
-#  ifndef HAVE_VSNPRINTF
-#    define HAVE_VSNPRINTF
-#  endif
-#endif
-
-#ifndef HAVE_VSNPRINTF
-#  ifdef MSDOS
-/* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
-   but for now we just assume it doesn't. */
-#    define NO_vsnprintf
-#  endif
-#  ifdef __TURBOC__
-#    define NO_vsnprintf
-#  endif
-#  ifdef WIN32
-/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
-#    if !defined(vsnprintf) && !defined(NO_vsnprintf)
-#      if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )
-#         define vsnprintf _vsnprintf
-#      endif
-#    endif
-#  endif
-#  ifdef __SASC
-#    define NO_vsnprintf
-#  endif
-#  ifdef VMS
-#    define NO_vsnprintf
-#  endif
-#  ifdef __OS400__
-#    define NO_vsnprintf
-#  endif
-#  ifdef __MVS__
-#    define NO_vsnprintf
-#  endif
-#endif
-
-/* unlike snprintf (which is required in C99, yet still not supported by
-   Microsoft more than a decade later!), _snprintf does not guarantee null
-   termination of the result -- however this is only used in gzlib.c where
-   the result is assured to fit in the space provided */
-#ifdef _MSC_VER
-#  define snprintf _snprintf
-#endif
-
-#ifndef local
-#  define local static
-#endif
-/* compile with -Dlocal if your debugger can't find static symbols */
-
-/* gz* functions always use library allocation functions */
-#ifndef STDC
-  extern voidp  malloc OF((uInt size));
-  extern void   free   OF((voidpf ptr));
-#endif
-
-/* get errno and strerror definition */
-#if defined UNDER_CE
-#  include <windows.h>
-#  define zstrerror() gz_strwinerror((DWORD)GetLastError())
-#else
-#  ifndef NO_STRERROR
-#    include <errno.h>
-#    define zstrerror() strerror(errno)
-#  else
-#    define zstrerror() "stdio error (consult errno)"
-#  endif
-#endif
-
-/* provide prototypes for these when building zlib without LFS */
-#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0
-    ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
-    ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
-    ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
-    ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
-#endif
-
-/* default memLevel */
-#if MAX_MEM_LEVEL >= 8
-#  define DEF_MEM_LEVEL 8
-#else
-#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
-#endif
-
-/* default i/o buffer size -- double this for output when reading (this and
-   twice this must be able to fit in an unsigned type) */
-#define GZBUFSIZE 8192
-
-/* gzip modes, also provide a little integrity check on the passed structure */
-#define GZ_NONE 0
-#define GZ_READ 7247
-#define GZ_WRITE 31153
-#define GZ_APPEND 1     /* mode set to GZ_WRITE after the file is opened */
-
-/* values for gz_state how */
-#define LOOK 0      /* look for a gzip header */
-#define COPY 1      /* copy input directly */
-#define GZIP 2      /* decompress a gzip stream */
-
-/* internal gzip file state data structure */
-typedef struct {
-        /* exposed contents for gzgetc() macro */
-    struct gzFile_s x;      /* "x" for exposed */
-                            /* x.have: number of bytes available at x.next */
-                            /* x.next: next output data to deliver or write */
-                            /* x.pos: current position in uncompressed data */
-        /* used for both reading and writing */
-    int mode;               /* see gzip modes above */
-    int fd;                 /* file descriptor */
-    char *path;             /* path or fd for error messages */
-    unsigned size;          /* buffer size, zero if not allocated yet */
-    unsigned want;          /* requested buffer size, default is GZBUFSIZE */
-    unsigned char *in;      /* input buffer */
-    unsigned char *out;     /* output buffer (double-sized when reading) */
-    int direct;             /* 0 if processing gzip, 1 if transparent */
-        /* just for reading */
-    int how;                /* 0: get header, 1: copy, 2: decompress */
-    z_off64_t start;        /* where the gzip data started, for rewinding */
-    int eof;                /* true if end of input file reached */
-    int past;               /* true if read requested past end */
-        /* just for writing */
-    int level;              /* compression level */
-    int strategy;           /* compression strategy */
-        /* seek request */
-    z_off64_t skip;         /* amount to skip (already rewound if backwards) */
-    int seek;               /* true if seek request pending */
-        /* error information */
-    int err;                /* error code */
-    char *msg;              /* error message */
-        /* zlib inflate or deflate stream */
-    z_stream strm;          /* stream structure in-place (not a pointer) */
-} gz_state;
-typedef gz_state FAR *gz_statep;
-
-/* shared functions */
-void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *));
-#if defined UNDER_CE
-char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error));
-#endif
-
-/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t
-   value -- needed when comparing unsigned to z_off64_t, which is signed
-   (possible z_off64_t types off_t, off64_t, and long are all signed) */
-#ifdef INT_MAX
-#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX)
-#else
-unsigned ZLIB_INTERNAL gz_intmax OF((void));
-#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax())
-#endif
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzlib.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,658 +0,0 @@
-/*
- * 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.
- */
-
-/* gzlib.c -- zlib functions common to reading and writing gzip files
- * Copyright (C) 2004, 2010, 2011, 2012, 2013 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-#include "gzguts.h"
-
-#if defined(_WIN32) && !defined(__BORLANDC__)
-#  define LSEEK _lseeki64
-#else
-#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
-#  define LSEEK lseek64
-#else
-#  define LSEEK lseek
-#endif
-#endif
-
-/* Local functions */
-local void gz_reset OF((gz_statep));
-local gzFile gz_open OF((const void *, int, const char *));
-
-#if defined UNDER_CE
-
-/* Map the Windows error number in ERROR to a locale-dependent error message
-   string and return a pointer to it.  Typically, the values for ERROR come
-   from GetLastError.
-
-   The string pointed to shall not be modified by the application, but may be
-   overwritten by a subsequent call to gz_strwinerror
-
-   The gz_strwinerror function does not change the current setting of
-   GetLastError. */
-char ZLIB_INTERNAL *gz_strwinerror (error)
-     DWORD error;
-{
-    static char buf[1024];
-
-    wchar_t *msgbuf;
-    DWORD lasterr = GetLastError();
-    DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
-        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
-        NULL,
-        error,
-        0, /* Default language */
-        (LPVOID)&msgbuf,
-        0,
-        NULL);
-    if (chars != 0) {
-        /* If there is an \r\n appended, zap it.  */
-        if (chars >= 2
-            && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
-            chars -= 2;
-            msgbuf[chars] = 0;
-        }
-
-        if (chars > sizeof (buf) - 1) {
-            chars = sizeof (buf) - 1;
-            msgbuf[chars] = 0;
-        }
-
-        wcstombs(buf, msgbuf, chars + 1);
-        LocalFree(msgbuf);
-    }
-    else {
-        sprintf(buf, "unknown win32 error (%ld)", error);
-    }
-
-    SetLastError(lasterr);
-    return buf;
-}
-
-#endif /* UNDER_CE */
-
-/* Reset gzip file state */
-local void gz_reset(state)
-    gz_statep state;
-{
-    state->x.have = 0;              /* no output data available */
-    if (state->mode == GZ_READ) {   /* for reading ... */
-        state->eof = 0;             /* not at end of file */
-        state->past = 0;            /* have not read past end yet */
-        state->how = LOOK;          /* look for gzip header */
-    }
-    state->seek = 0;                /* no seek request pending */
-    gz_error(state, Z_OK, NULL);    /* clear error */
-    state->x.pos = 0;               /* no uncompressed data yet */
-    state->strm.avail_in = 0;       /* no input data yet */
-}
-
-/* Open a gzip file either by name or file descriptor. */
-local gzFile gz_open(path, fd, mode)
-    const void *path;
-    int fd;
-    const char *mode;
-{
-    gz_statep state;
-    size_t len;
-    int oflag;
-#ifdef O_CLOEXEC
-    int cloexec = 0;
-#endif
-#ifdef O_EXCL
-    int exclusive = 0;
-#endif
-
-    /* check input */
-    if (path == NULL)
-        return NULL;
-
-    /* allocate gzFile structure to return */
-    state = (gz_statep)malloc(sizeof(gz_state));
-    if (state == NULL)
-        return NULL;
-    state->size = 0;            /* no buffers allocated yet */
-    state->want = GZBUFSIZE;    /* requested buffer size */
-    state->msg = NULL;          /* no error message yet */
-
-    /* interpret mode */
-    state->mode = GZ_NONE;
-    state->level = Z_DEFAULT_COMPRESSION;
-    state->strategy = Z_DEFAULT_STRATEGY;
-    state->direct = 0;
-    while (*mode) {
-        if (*mode >= '0' && *mode <= '9')
-            state->level = *mode - '0';
-        else
-            switch (*mode) {
-            case 'r':
-                state->mode = GZ_READ;
-                break;
-#ifndef NO_GZCOMPRESS
-            case 'w':
-                state->mode = GZ_WRITE;
-                break;
-            case 'a':
-                state->mode = GZ_APPEND;
-                break;
-#endif
-            case '+':       /* can't read and write at the same time */
-                free(state);
-                return NULL;
-            case 'b':       /* ignore -- will request binary anyway */
-                break;
-#ifdef O_CLOEXEC
-            case 'e':
-                cloexec = 1;
-                break;
-#endif
-#ifdef O_EXCL
-            case 'x':
-                exclusive = 1;
-                break;
-#endif
-            case 'f':
-                state->strategy = Z_FILTERED;
-                break;
-            case 'h':
-                state->strategy = Z_HUFFMAN_ONLY;
-                break;
-            case 'R':
-                state->strategy = Z_RLE;
-                break;
-            case 'F':
-                state->strategy = Z_FIXED;
-                break;
-            case 'T':
-                state->direct = 1;
-                break;
-            default:        /* could consider as an error, but just ignore */
-                ;
-            }
-        mode++;
-    }
-
-    /* must provide an "r", "w", or "a" */
-    if (state->mode == GZ_NONE) {
-        free(state);
-        return NULL;
-    }
-
-    /* can't force transparent read */
-    if (state->mode == GZ_READ) {
-        if (state->direct) {
-            free(state);
-            return NULL;
-        }
-        state->direct = 1;      /* for empty file */
-    }
-
-    /* save the path name for error messages */
-#ifdef _WIN32
-    if (fd == -2) {
-        len = wcstombs(NULL, path, 0);
-        if (len == (size_t)-1)
-            len = 0;
-    }
-    else
-#endif
-        len = strlen((const char *)path);
-    state->path = (char *)malloc(len + 1);
-    if (state->path == NULL) {
-        free(state);
-        return NULL;
-    }
-#ifdef _WIN32
-    if (fd == -2)
-        if (len)
-            wcstombs(state->path, path, len + 1);
-        else
-            *(state->path) = 0;
-    else
-#endif
-#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
-        snprintf(state->path, len + 1, "%s", (const char *)path);
-#else
-        strcpy(state->path, path);
-#endif
-
-    /* compute the flags for open() */
-    oflag =
-#ifdef O_LARGEFILE
-        O_LARGEFILE |
-#endif
-#ifdef O_BINARY
-        O_BINARY |
-#endif
-#ifdef O_CLOEXEC
-        (cloexec ? O_CLOEXEC : 0) |
-#endif
-        (state->mode == GZ_READ ?
-         O_RDONLY :
-         (O_WRONLY | O_CREAT |
-#ifdef O_EXCL
-          (exclusive ? O_EXCL : 0) |
-#endif
-          (state->mode == GZ_WRITE ?
-           O_TRUNC :
-           O_APPEND)));
-
-    /* open the file with the appropriate flags (or just use fd) */
-    state->fd = fd > -1 ? fd : (
-#ifdef _WIN32
-        fd == -2 ? _wopen(path, oflag, 0666) :
-#endif
-        open((const char *)path, oflag, 0666));
-    if (state->fd == -1) {
-        free(state->path);
-        free(state);
-        return NULL;
-    }
-    if (state->mode == GZ_APPEND)
-        state->mode = GZ_WRITE;         /* simplify later checks */
-
-    /* save the current position for rewinding (only if reading) */
-    if (state->mode == GZ_READ) {
-        state->start = LSEEK(state->fd, 0, SEEK_CUR);
-        if (state->start == -1) state->start = 0;
-    }
-
-    /* initialize stream */
-    gz_reset(state);
-
-    /* return stream */
-    return (gzFile)state;
-}
-
-/* -- see zlib.h -- */
-gzFile ZEXPORT gzopen(path, mode)
-    const char *path;
-    const char *mode;
-{
-    return gz_open(path, -1, mode);
-}
-
-/* -- see zlib.h -- */
-gzFile ZEXPORT gzopen64(path, mode)
-    const char *path;
-    const char *mode;
-{
-    return gz_open(path, -1, mode);
-}
-
-/* -- see zlib.h -- */
-gzFile ZEXPORT gzdopen(fd, mode)
-    int fd;
-    const char *mode;
-{
-    char *path;         /* identifier for error messages */
-    gzFile gz;
-
-    if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL)
-        return NULL;
-#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
-    snprintf(path, 7 + 3 * sizeof(int), "<fd:%d>", fd); /* for debugging */
-#else
-    sprintf(path, "<fd:%d>", fd);   /* for debugging */
-#endif
-    gz = gz_open(path, fd, mode);
-    free(path);
-    return gz;
-}
-
-/* -- see zlib.h -- */
-#ifdef _WIN32
-gzFile ZEXPORT gzopen_w(path, mode)
-    const wchar_t *path;
-    const char *mode;
-{
-    return gz_open(path, -2, mode);
-}
-#endif
-
-/* -- see zlib.h -- */
-int ZEXPORT gzbuffer(file, size)
-    gzFile file;
-    unsigned size;
-{
-    gz_statep state;
-
-    /* get internal structure and check integrity */
-    if (file == NULL)
-        return -1;
-    state = (gz_statep)file;
-    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
-        return -1;
-
-    /* make sure we haven't already allocated memory */
-    if (state->size != 0)
-        return -1;
-
-    /* check and set requested size */
-    if (size < 2)
-        size = 2;               /* need two bytes to check magic header */
-    state->want = size;
-    return 0;
-}
-
-/* -- see zlib.h -- */
-int ZEXPORT gzrewind(file)
-    gzFile file;
-{
-    gz_statep state;
-
-    /* get internal structure */
-    if (file == NULL)
-        return -1;
-    state = (gz_statep)file;
-
-    /* check that we're reading and that there's no error */
-    if (state->mode != GZ_READ ||
-            (state->err != Z_OK && state->err != Z_BUF_ERROR))
-        return -1;
-
-    /* back up and start over */
-    if (LSEEK(state->fd, state->start, SEEK_SET) == -1)
-        return -1;
-    gz_reset(state);
-    return 0;
-}
-
-/* -- see zlib.h -- */
-z_off64_t ZEXPORT gzseek64(file, offset, whence)
-    gzFile file;
-    z_off64_t offset;
-    int whence;
-{
-    unsigned n;
-    z_off64_t ret;
-    gz_statep state;
-
-    /* get internal structure and check integrity */
-    if (file == NULL)
-        return -1;
-    state = (gz_statep)file;
-    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
-        return -1;
-
-    /* check that there's no error */
-    if (state->err != Z_OK && state->err != Z_BUF_ERROR)
-        return -1;
-
-    /* can only seek from start or relative to current position */
-    if (whence != SEEK_SET && whence != SEEK_CUR)
-        return -1;
-
-    /* normalize offset to a SEEK_CUR specification */
-    if (whence == SEEK_SET)
-        offset -= state->x.pos;
-    else if (state->seek)
-        offset += state->skip;
-    state->seek = 0;
-
-    /* if within raw area while reading, just go there */
-    if (state->mode == GZ_READ && state->how == COPY &&
-            state->x.pos + offset >= 0) {
-        ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR);
-        if (ret == -1)
-            return -1;
-        state->x.have = 0;
-        state->eof = 0;
-        state->past = 0;
-        state->seek = 0;
-        gz_error(state, Z_OK, NULL);
-        state->strm.avail_in = 0;
-        state->x.pos += offset;
-        return state->x.pos;
-    }
-
-    /* calculate skip amount, rewinding if needed for back seek when reading */
-    if (offset < 0) {
-        if (state->mode != GZ_READ)         /* writing -- can't go backwards */
-            return -1;
-        offset += state->x.pos;
-        if (offset < 0)                     /* before start of file! */
-            return -1;
-        if (gzrewind(file) == -1)           /* rewind, then skip to offset */
-            return -1;
-    }
-
-    /* if reading, skip what's in output buffer (one less gzgetc() check) */
-    if (state->mode == GZ_READ) {
-        n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ?
-            (unsigned)offset : state->x.have;
-        state->x.have -= n;
-        state->x.next += n;
-        state->x.pos += n;
-        offset -= n;
-    }
-
-    /* request skip (if not zero) */
-    if (offset) {
-        state->seek = 1;
-        state->skip = offset;
-    }
-    return state->x.pos + offset;
-}
-
-/* -- see zlib.h -- */
-z_off_t ZEXPORT gzseek(file, offset, whence)
-    gzFile file;
-    z_off_t offset;
-    int whence;
-{
-    z_off64_t ret;
-
-    ret = gzseek64(file, (z_off64_t)offset, whence);
-    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
-}
-
-/* -- see zlib.h -- */
-z_off64_t ZEXPORT gztell64(file)
-    gzFile file;
-{
-    gz_statep state;
-
-    /* get internal structure and check integrity */
-    if (file == NULL)
-        return -1;
-    state = (gz_statep)file;
-    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
-        return -1;
-
-    /* return position */
-    return state->x.pos + (state->seek ? state->skip : 0);
-}
-
-/* -- see zlib.h -- */
-z_off_t ZEXPORT gztell(file)
-    gzFile file;
-{
-    z_off64_t ret;
-
-    ret = gztell64(file);
-    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
-}
-
-/* -- see zlib.h -- */
-z_off64_t ZEXPORT gzoffset64(file)
-    gzFile file;
-{
-    z_off64_t offset;
-    gz_statep state;
-
-    /* get internal structure and check integrity */
-    if (file == NULL)
-        return -1;
-    state = (gz_statep)file;
-    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
-        return -1;
-
-    /* compute and return effective offset in file */
-    offset = LSEEK(state->fd, 0, SEEK_CUR);
-    if (offset == -1)
-        return -1;
-    if (state->mode == GZ_READ)             /* reading */
-        offset -= state->strm.avail_in;     /* don't count buffered input */
-    return offset;
-}
-
-/* -- see zlib.h -- */
-z_off_t ZEXPORT gzoffset(file)
-    gzFile file;
-{
-    z_off64_t ret;
-
-    ret = gzoffset64(file);
-    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
-}
-
-/* -- see zlib.h -- */
-int ZEXPORT gzeof(file)
-    gzFile file;
-{
-    gz_statep state;
-
-    /* get internal structure and check integrity */
-    if (file == NULL)
-        return 0;
-    state = (gz_statep)file;
-    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
-        return 0;
-
-    /* return end-of-file state */
-    return state->mode == GZ_READ ? state->past : 0;
-}
-
-/* -- see zlib.h -- */
-const char * ZEXPORT gzerror(file, errnum)
-    gzFile file;
-    int *errnum;
-{
-    gz_statep state;
-
-    /* get internal structure and check integrity */
-    if (file == NULL)
-        return NULL;
-    state = (gz_statep)file;
-    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
-        return NULL;
-
-    /* return error information */
-    if (errnum != NULL)
-        *errnum = state->err;
-    return state->err == Z_MEM_ERROR ? "out of memory" :
-                                       (state->msg == NULL ? "" : state->msg);
-}
-
-/* -- see zlib.h -- */
-void ZEXPORT gzclearerr(file)
-    gzFile file;
-{
-    gz_statep state;
-
-    /* get internal structure and check integrity */
-    if (file == NULL)
-        return;
-    state = (gz_statep)file;
-    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
-        return;
-
-    /* clear error and end-of-file */
-    if (state->mode == GZ_READ) {
-        state->eof = 0;
-        state->past = 0;
-    }
-    gz_error(state, Z_OK, NULL);
-}
-
-/* Create an error message in allocated memory and set state->err and
-   state->msg accordingly.  Free any previous error message already there.  Do
-   not try to free or allocate space if the error is Z_MEM_ERROR (out of
-   memory).  Simply save the error message as a static string.  If there is an
-   allocation failure constructing the error message, then convert the error to
-   out of memory. */
-void ZLIB_INTERNAL gz_error(state, err, msg)
-    gz_statep state;
-    int err;
-    const char *msg;
-{
-    /* free previously allocated message and clear */
-    if (state->msg != NULL) {
-        if (state->err != Z_MEM_ERROR)
-            free(state->msg);
-        state->msg = NULL;
-    }
-
-    /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */
-    if (err != Z_OK && err != Z_BUF_ERROR)
-        state->x.have = 0;
-
-    /* set error code, and if no message, then done */
-    state->err = err;
-    if (msg == NULL)
-        return;
-
-    /* for an out of memory error, return literal string when requested */
-    if (err == Z_MEM_ERROR)
-        return;
-
-    /* construct error message with path */
-    if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) ==
-            NULL) {
-        state->err = Z_MEM_ERROR;
-        return;
-    }
-#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
-    snprintf(state->msg, strlen(state->path) + strlen(msg) + 3,
-             "%s%s%s", state->path, ": ", msg);
-#else
-    strcpy(state->msg, state->path);
-    strcat(state->msg, ": ");
-    strcat(state->msg, msg);
-#endif
-    return;
-}
-
-#ifndef INT_MAX
-/* portably return maximum value for an int (when limits.h presumed not
-   available) -- we need to do this to cover cases where 2's complement not
-   used, since C standard permits 1's complement and sign-bit representations,
-   otherwise we could just use ((unsigned)-1) >> 1 */
-unsigned ZLIB_INTERNAL gz_intmax()
-{
-    unsigned p, q;
-
-    p = 1;
-    do {
-        q = p;
-        p <<= 1;
-        p++;
-    } while (p > q);
-    return q >> 1;
-}
-#endif
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzread.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,618 +0,0 @@
-/*
- * 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.
- */
-
-/* gzread.c -- zlib functions for reading gzip files
- * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-#include "gzguts.h"
-
-/* Local functions */
-local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *));
-local int gz_avail OF((gz_statep));
-local int gz_look OF((gz_statep));
-local int gz_decomp OF((gz_statep));
-local int gz_fetch OF((gz_statep));
-local int gz_skip OF((gz_statep, z_off64_t));
-
-/* Use read() to load a buffer -- return -1 on error, otherwise 0.  Read from
-   state->fd, and update state->eof, state->err, and state->msg as appropriate.
-   This function needs to loop on read(), since read() is not guaranteed to
-   read the number of bytes requested, depending on the type of descriptor. */
-local int gz_load(state, buf, len, have)
-    gz_statep state;
-    unsigned char *buf;
-    unsigned len;
-    unsigned *have;
-{
-    int ret;
-
-    *have = 0;
-    do {
-        ret = read(state->fd, buf + *have, len - *have);
-        if (ret <= 0)
-            break;
-        *have += ret;
-    } while (*have < len);
-    if (ret < 0) {
-        gz_error(state, Z_ERRNO, zstrerror());
-        return -1;
-    }
-    if (ret == 0)
-        state->eof = 1;
-    return 0;
-}
-
-/* Load up input buffer and set eof flag if last data loaded -- return -1 on
-   error, 0 otherwise.  Note that the eof flag is set when the end of the input
-   file is reached, even though there may be unused data in the buffer.  Once
-   that data has been used, no more attempts will be made to read the file.
-   If strm->avail_in != 0, then the current data is moved to the beginning of
-   the input buffer, and then the remainder of the buffer is loaded with the
-   available data from the input file. */
-local int gz_avail(state)
-    gz_statep state;
-{
-    unsigned got;
-    z_streamp strm = &(state->strm);
-
-    if (state->err != Z_OK && state->err != Z_BUF_ERROR)
-        return -1;
-    if (state->eof == 0) {
-        if (strm->avail_in) {       /* copy what's there to the start */
-            unsigned char *p = state->in;
-            unsigned const char *q = strm->next_in;
-            unsigned n = strm->avail_in;
-            do {
-                *p++ = *q++;
-            } while (--n);
-        }
-        if (gz_load(state, state->in + strm->avail_in,
-                    state->size - strm->avail_in, &got) == -1)
-            return -1;
-        strm->avail_in += got;
-        strm->next_in = state->in;
-    }
-    return 0;
-}
-
-/* Look for gzip header, set up for inflate or copy.  state->x.have must be 0.
-   If this is the first time in, allocate required memory.  state->how will be
-   left unchanged if there is no more input data available, will be set to COPY
-   if there is no gzip header and direct copying will be performed, or it will
-   be set to GZIP for decompression.  If direct copying, then leftover input
-   data from the input buffer will be copied to the output buffer.  In that
-   case, all further file reads will be directly to either the output buffer or
-   a user buffer.  If decompressing, the inflate state will be initialized.
-   gz_look() will return 0 on success or -1 on failure. */
-local int gz_look(state)
-    gz_statep state;
-{
-    z_streamp strm = &(state->strm);
-
-    /* allocate read buffers and inflate memory */
-    if (state->size == 0) {
-        /* allocate buffers */
-        state->in = (unsigned char *)malloc(state->want);
-        state->out = (unsigned char *)malloc(state->want << 1);
-        if (state->in == NULL || state->out == NULL) {
-            if (state->out != NULL)
-                free(state->out);
-            if (state->in != NULL)
-                free(state->in);
-            gz_error(state, Z_MEM_ERROR, "out of memory");
-            return -1;
-        }
-        state->size = state->want;
-
-        /* allocate inflate memory */
-        state->strm.zalloc = Z_NULL;
-        state->strm.zfree = Z_NULL;
-        state->strm.opaque = Z_NULL;
-        state->strm.avail_in = 0;
-        state->strm.next_in = Z_NULL;
-        if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) {    /* gunzip */
-            free(state->out);
-            free(state->in);
-            state->size = 0;
-            gz_error(state, Z_MEM_ERROR, "out of memory");
-            return -1;
-        }
-    }
-
-    /* get at least the magic bytes in the input buffer */
-    if (strm->avail_in < 2) {
-        if (gz_avail(state) == -1)
-            return -1;
-        if (strm->avail_in == 0)
-            return 0;
-    }
-
-    /* look for gzip magic bytes -- if there, do gzip decoding (note: there is
-       a logical dilemma here when considering the case of a partially written
-       gzip file, to wit, if a single 31 byte is written, then we cannot tell
-       whether this is a single-byte file, or just a partially written gzip
-       file -- for here we assume that if a gzip file is being written, then
-       the header will be written in a single operation, so that reading a
-       single byte is sufficient indication that it is not a gzip file) */
-    if (strm->avail_in > 1 &&
-            strm->next_in[0] == 31 && strm->next_in[1] == 139) {
-        inflateReset(strm);
-        state->how = GZIP;
-        state->direct = 0;
-        return 0;
-    }
-
-    /* no gzip header -- if we were decoding gzip before, then this is trailing
-       garbage.  Ignore the trailing garbage and finish. */
-    if (state->direct == 0) {
-        strm->avail_in = 0;
-        state->eof = 1;
-        state->x.have = 0;
-        return 0;
-    }
-
-    /* doing raw i/o, copy any leftover input to output -- this assumes that
-       the output buffer is larger than the input buffer, which also assures
-       space for gzungetc() */
-    state->x.next = state->out;
-    if (strm->avail_in) {
-        memcpy(state->x.next, strm->next_in, strm->avail_in);
-        state->x.have = strm->avail_in;
-        strm->avail_in = 0;
-    }
-    state->how = COPY;
-    state->direct = 1;
-    return 0;
-}
-
-/* Decompress from input to the provided next_out and avail_out in the state.
-   On return, state->x.have and state->x.next point to the just decompressed
-   data.  If the gzip stream completes, state->how is reset to LOOK to look for
-   the next gzip stream or raw data, once state->x.have is depleted.  Returns 0
-   on success, -1 on failure. */
-local int gz_decomp(state)
-    gz_statep state;
-{
-    int ret = Z_OK;
-    unsigned had;
-    z_streamp strm = &(state->strm);
-
-    /* fill output buffer up to end of deflate stream */
-    had = strm->avail_out;
-    do {
-        /* get more input for inflate() */
-        if (strm->avail_in == 0 && gz_avail(state) == -1)
-            return -1;
-        if (strm->avail_in == 0) {
-            gz_error(state, Z_BUF_ERROR, "unexpected end of file");
-            break;
-        }
-
-        /* decompress and handle errors */
-        ret = inflate(strm, Z_NO_FLUSH);
-        if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {
-            gz_error(state, Z_STREAM_ERROR,
-                     "internal error: inflate stream corrupt");
-            return -1;
-        }
-        if (ret == Z_MEM_ERROR) {
-            gz_error(state, Z_MEM_ERROR, "out of memory");
-            return -1;
-        }
-        if (ret == Z_DATA_ERROR) {              /* deflate stream invalid */
-            gz_error(state, Z_DATA_ERROR,
-                     strm->msg == NULL ? "compressed data error" : strm->msg);
-            return -1;
-        }
-    } while (strm->avail_out && ret != Z_STREAM_END);
-
-    /* update available output */
-    state->x.have = had - strm->avail_out;
-    state->x.next = strm->next_out - state->x.have;
-
-    /* if the gzip stream completed successfully, look for another */
-    if (ret == Z_STREAM_END)
-        state->how = LOOK;
-
-    /* good decompression */
-    return 0;
-}
-
-/* Fetch data and put it in the output buffer.  Assumes state->x.have is 0.
-   Data is either copied from the input file or decompressed from the input
-   file depending on state->how.  If state->how is LOOK, then a gzip header is
-   looked for to determine whether to copy or decompress.  Returns -1 on error,
-   otherwise 0.  gz_fetch() will leave state->how as COPY or GZIP unless the
-   end of the input file has been reached and all data has been processed.  */
-local int gz_fetch(state)
-    gz_statep state;
-{
-    z_streamp strm = &(state->strm);
-
-    do {
-        switch(state->how) {
-        case LOOK:      /* -> LOOK, COPY (only if never GZIP), or GZIP */
-            if (gz_look(state) == -1)
-                return -1;
-            if (state->how == LOOK)
-                return 0;
-            break;
-        case COPY:      /* -> COPY */
-            if (gz_load(state, state->out, state->size << 1, &(state->x.have))
-                    == -1)
-                return -1;
-            state->x.next = state->out;
-            return 0;
-        case GZIP:      /* -> GZIP or LOOK (if end of gzip stream) */
-            strm->avail_out = state->size << 1;
-            strm->next_out = state->out;
-            if (gz_decomp(state) == -1)
-                return -1;
-        }
-    } while (state->x.have == 0 && (!state->eof || strm->avail_in));
-    return 0;
-}
-
-/* Skip len uncompressed bytes of output.  Return -1 on error, 0 on success. */
-local int gz_skip(state, len)
-    gz_statep state;
-    z_off64_t len;
-{
-    unsigned n;
-
-    /* skip over len bytes or reach end-of-file, whichever comes first */
-    while (len)
-        /* skip over whatever is in output buffer */
-        if (state->x.have) {
-            n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ?
-                (unsigned)len : state->x.have;
-            state->x.have -= n;
-            state->x.next += n;
-            state->x.pos += n;
-            len -= n;
-        }
-
-        /* output buffer empty -- return if we're at the end of the input */
-        else if (state->eof && state->strm.avail_in == 0)
-            break;
-
-        /* need more data to skip -- load up output buffer */
-        else {
-            /* get more output, looking for header if required */
-            if (gz_fetch(state) == -1)
-                return -1;
-        }
-    return 0;
-}
-
-/* -- see zlib.h -- */
-int ZEXPORT gzread(file, buf, len)
-    gzFile file;
-    voidp buf;
-    unsigned len;
-{
-    unsigned got, n;
-    gz_statep state;
-    z_streamp strm;
-
-    /* get internal structure */
-    if (file == NULL)
-        return -1;
-    state = (gz_statep)file;
-    strm = &(state->strm);
-
-    /* check that we're reading and that there's no (serious) error */
-    if (state->mode != GZ_READ ||
-            (state->err != Z_OK && state->err != Z_BUF_ERROR))
-        return -1;
-
-    /* since an int is returned, make sure len fits in one, otherwise return
-       with an error (this avoids the flaw in the interface) */
-    if ((int)len < 0) {
-        gz_error(state, Z_DATA_ERROR, "requested length does not fit in int");
-        return -1;
-    }
-
-    /* if len is zero, avoid unnecessary operations */
-    if (len == 0)
-        return 0;
-
-    /* process a skip request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_skip(state, state->skip) == -1)
-            return -1;
-    }
-
-    /* get len bytes to buf, or less than len if at the end */
-    got = 0;
-    do {
-        /* first just try copying data from the output buffer */
-        if (state->x.have) {
-            n = state->x.have > len ? len : state->x.have;
-            memcpy(buf, state->x.next, n);
-            state->x.next += n;
-            state->x.have -= n;
-        }
-
-        /* output buffer empty -- return if we're at the end of the input */
-        else if (state->eof && strm->avail_in == 0) {
-            state->past = 1;        /* tried to read past end */
-            break;
-        }
-
-        /* need output data -- for small len or new stream load up our output
-           buffer */
-        else if (state->how == LOOK || len < (state->size << 1)) {
-            /* get more output, looking for header if required */
-            if (gz_fetch(state) == -1)
-                return -1;
-            continue;       /* no progress yet -- go back to copy above */
-            /* the copy above assures that we will leave with space in the
-               output buffer, allowing at least one gzungetc() to succeed */
-        }
-
-        /* large len -- read directly into user buffer */
-        else if (state->how == COPY) {      /* read directly */
-            if (gz_load(state, (unsigned char *)buf, len, &n) == -1)
-                return -1;
-        }
-
-        /* large len -- decompress directly into user buffer */
-        else {  /* state->how == GZIP */
-            strm->avail_out = len;
-            strm->next_out = (unsigned char *)buf;
-            if (gz_decomp(state) == -1)
-                return -1;
-            n = state->x.have;
-            state->x.have = 0;
-        }
-
-        /* update progress */
-        len -= n;
-        buf = (char *)buf + n;
-        got += n;
-        state->x.pos += n;
-    } while (len);
-
-    /* return number of bytes read into user buffer (will fit in int) */
-    return (int)got;
-}
-
-/* -- see zlib.h -- */
-#ifdef Z_PREFIX_SET
-#  undef z_gzgetc
-#else
-#  undef gzgetc
-#endif
-int ZEXPORT gzgetc(file)
-    gzFile file;
-{
-    int ret;
-    unsigned char buf[1];
-    gz_statep state;
-
-    /* get internal structure */
-    if (file == NULL)
-        return -1;
-    state = (gz_statep)file;
-
-    /* check that we're reading and that there's no (serious) error */
-    if (state->mode != GZ_READ ||
-        (state->err != Z_OK && state->err != Z_BUF_ERROR))
-        return -1;
-
-    /* try output buffer (no need to check for skip request) */
-    if (state->x.have) {
-        state->x.have--;
-        state->x.pos++;
-        return *(state->x.next)++;
-    }
-
-    /* nothing there -- try gzread() */
-    ret = gzread(file, buf, 1);
-    return ret < 1 ? -1 : buf[0];
-}
-
-int ZEXPORT gzgetc_(file)
-gzFile file;
-{
-    return gzgetc(file);
-}
-
-/* -- see zlib.h -- */
-int ZEXPORT gzungetc(c, file)
-    int c;
-    gzFile file;
-{
-    gz_statep state;
-
-    /* get internal structure */
-    if (file == NULL)
-        return -1;
-    state = (gz_statep)file;
-
-    /* check that we're reading and that there's no (serious) error */
-    if (state->mode != GZ_READ ||
-        (state->err != Z_OK && state->err != Z_BUF_ERROR))
-        return -1;
-
-    /* process a skip request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_skip(state, state->skip) == -1)
-            return -1;
-    }
-
-    /* can't push EOF */
-    if (c < 0)
-        return -1;
-
-    /* if output buffer empty, put byte at end (allows more pushing) */
-    if (state->x.have == 0) {
-        state->x.have = 1;
-        state->x.next = state->out + (state->size << 1) - 1;
-        state->x.next[0] = c;
-        state->x.pos--;
-        state->past = 0;
-        return c;
-    }
-
-    /* if no room, give up (must have already done a gzungetc()) */
-    if (state->x.have == (state->size << 1)) {
-        gz_error(state, Z_DATA_ERROR, "out of room to push characters");
-        return -1;
-    }
-
-    /* slide output data if needed and insert byte before existing data */
-    if (state->x.next == state->out) {
-        unsigned char *src = state->out + state->x.have;
-        unsigned char *dest = state->out + (state->size << 1);
-        while (src > state->out)
-            *--dest = *--src;
-        state->x.next = dest;
-    }
-    state->x.have++;
-    state->x.next--;
-    state->x.next[0] = c;
-    state->x.pos--;
-    state->past = 0;
-    return c;
-}
-
-/* -- see zlib.h -- */
-char * ZEXPORT gzgets(file, buf, len)
-    gzFile file;
-    char *buf;
-    int len;
-{
-    unsigned left, n;
-    char *str;
-    unsigned char *eol;
-    gz_statep state;
-
-    /* check parameters and get internal structure */
-    if (file == NULL || buf == NULL || len < 1)
-        return NULL;
-    state = (gz_statep)file;
-
-    /* check that we're reading and that there's no (serious) error */
-    if (state->mode != GZ_READ ||
-        (state->err != Z_OK && state->err != Z_BUF_ERROR))
-        return NULL;
-
-    /* process a skip request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_skip(state, state->skip) == -1)
-            return NULL;
-    }
-
-    /* copy output bytes up to new line or len - 1, whichever comes first --
-       append a terminating zero to the string (we don't check for a zero in
-       the contents, let the user worry about that) */
-    str = buf;
-    left = (unsigned)len - 1;
-    if (left) do {
-        /* assure that something is in the output buffer */
-        if (state->x.have == 0 && gz_fetch(state) == -1)
-            return NULL;                /* error */
-        if (state->x.have == 0) {       /* end of file */
-            state->past = 1;            /* read past end */
-            break;                      /* return what we have */
-        }
-
-        /* look for end-of-line in current output buffer */
-        n = state->x.have > left ? left : state->x.have;
-        eol = (unsigned char *)memchr(state->x.next, '\n', n);
-        if (eol != NULL)
-            n = (unsigned)(eol - state->x.next) + 1;
-
-        /* copy through end-of-line, or remainder if not found */
-        memcpy(buf, state->x.next, n);
-        state->x.have -= n;
-        state->x.next += n;
-        state->x.pos += n;
-        left -= n;
-        buf += n;
-    } while (left && eol == NULL);
-
-    /* return terminated string, or if nothing, end of file */
-    if (buf == str)
-        return NULL;
-    buf[0] = 0;
-    return str;
-}
-
-/* -- see zlib.h -- */
-int ZEXPORT gzdirect(file)
-    gzFile file;
-{
-    gz_statep state;
-
-    /* get internal structure */
-    if (file == NULL)
-        return 0;
-    state = (gz_statep)file;
-
-    /* if the state is not known, but we can find out, then do so (this is
-       mainly for right after a gzopen() or gzdopen()) */
-    if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0)
-        (void)gz_look(state);
-
-    /* return 1 if transparent, 0 if processing a gzip stream */
-    return state->direct;
-}
-
-/* -- see zlib.h -- */
-int ZEXPORT gzclose_r(file)
-    gzFile file;
-{
-    int ret, err;
-    gz_statep state;
-
-    /* get internal structure */
-    if (file == NULL)
-        return Z_STREAM_ERROR;
-    state = (gz_statep)file;
-
-    /* check that we're reading */
-    if (state->mode != GZ_READ)
-        return Z_STREAM_ERROR;
-
-    /* free memory and close file */
-    if (state->size) {
-        inflateEnd(&(state->strm));
-        free(state->out);
-        free(state->in);
-    }
-    err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK;
-    gz_error(state, Z_OK, NULL);
-    free(state->path);
-    ret = close(state->fd);
-    free(state);
-    return ret ? Z_ERRNO : err;
-}
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/gzwrite.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,601 +0,0 @@
-/*
- * 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.
- */
-
-/* gzwrite.c -- zlib functions for writing gzip files
- * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-#include "gzguts.h"
-
-/* Local functions */
-local int gz_init OF((gz_statep));
-local int gz_comp OF((gz_statep, int));
-local int gz_zero OF((gz_statep, z_off64_t));
-
-/* Initialize state for writing a gzip file.  Mark initialization by setting
-   state->size to non-zero.  Return -1 on failure or 0 on success. */
-local int gz_init(state)
-    gz_statep state;
-{
-    int ret;
-    z_streamp strm = &(state->strm);
-
-    /* allocate input buffer */
-    state->in = (unsigned char *)malloc(state->want);
-    if (state->in == NULL) {
-        gz_error(state, Z_MEM_ERROR, "out of memory");
-        return -1;
-    }
-
-    /* only need output buffer and deflate state if compressing */
-    if (!state->direct) {
-        /* allocate output buffer */
-        state->out = (unsigned char *)malloc(state->want);
-        if (state->out == NULL) {
-            free(state->in);
-            gz_error(state, Z_MEM_ERROR, "out of memory");
-            return -1;
-        }
-
-        /* allocate deflate memory, set up for gzip compression */
-        strm->zalloc = Z_NULL;
-        strm->zfree = Z_NULL;
-        strm->opaque = Z_NULL;
-        ret = deflateInit2(strm, state->level, Z_DEFLATED,
-                           MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy);
-        if (ret != Z_OK) {
-            free(state->out);
-            free(state->in);
-            gz_error(state, Z_MEM_ERROR, "out of memory");
-            return -1;
-        }
-    }
-
-    /* mark state as initialized */
-    state->size = state->want;
-
-    /* initialize write buffer if compressing */
-    if (!state->direct) {
-        strm->avail_out = state->size;
-        strm->next_out = state->out;
-        state->x.next = strm->next_out;
-    }
-    return 0;
-}
-
-/* Compress whatever is at avail_in and next_in and write to the output file.
-   Return -1 if there is an error writing to the output file, otherwise 0.
-   flush is assumed to be a valid deflate() flush value.  If flush is Z_FINISH,
-   then the deflate() state is reset to start a new gzip stream.  If gz->direct
-   is true, then simply write to the output file without compressing, and
-   ignore flush. */
-local int gz_comp(state, flush)
-    gz_statep state;
-    int flush;
-{
-    int ret, got;
-    unsigned have;
-    z_streamp strm = &(state->strm);
-
-    /* allocate memory if this is the first time through */
-    if (state->size == 0 && gz_init(state) == -1)
-        return -1;
-
-    /* write directly if requested */
-    if (state->direct) {
-        got = write(state->fd, strm->next_in, strm->avail_in);
-        if (got < 0 || (unsigned)got != strm->avail_in) {
-            gz_error(state, Z_ERRNO, zstrerror());
-            return -1;
-        }
-        strm->avail_in = 0;
-        return 0;
-    }
-
-    /* run deflate() on provided input until it produces no more output */
-    ret = Z_OK;
-    do {
-        /* write out current buffer contents if full, or if flushing, but if
-           doing Z_FINISH then don't write until we get to Z_STREAM_END */
-        if (strm->avail_out == 0 || (flush != Z_NO_FLUSH &&
-            (flush != Z_FINISH || ret == Z_STREAM_END))) {
-            have = (unsigned)(strm->next_out - state->x.next);
-            if (have && ((got = write(state->fd, state->x.next, have)) < 0 ||
-                         (unsigned)got != have)) {
-                gz_error(state, Z_ERRNO, zstrerror());
-                return -1;
-            }
-            if (strm->avail_out == 0) {
-                strm->avail_out = state->size;
-                strm->next_out = state->out;
-            }
-            state->x.next = strm->next_out;
-        }
-
-        /* compress */
-        have = strm->avail_out;
-        ret = deflate(strm, flush);
-        if (ret == Z_STREAM_ERROR) {
-            gz_error(state, Z_STREAM_ERROR,
-                      "internal error: deflate stream corrupt");
-            return -1;
-        }
-        have -= strm->avail_out;
-    } while (have);
-
-    /* if that completed a deflate stream, allow another to start */
-    if (flush == Z_FINISH)
-        deflateReset(strm);
-
-    /* all done, no errors */
-    return 0;
-}
-
-/* Compress len zeros to output.  Return -1 on error, 0 on success. */
-local int gz_zero(state, len)
-    gz_statep state;
-    z_off64_t len;
-{
-    int first;
-    unsigned n;
-    z_streamp strm = &(state->strm);
-
-    /* consume whatever's left in the input buffer */
-    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
-        return -1;
-
-    /* compress len zeros (len guaranteed > 0) */
-    first = 1;
-    while (len) {
-        n = GT_OFF(state->size) || (z_off64_t)state->size > len ?
-            (unsigned)len : state->size;
-        if (first) {
-            memset(state->in, 0, n);
-            first = 0;
-        }
-        strm->avail_in = n;
-        strm->next_in = state->in;
-        state->x.pos += n;
-        if (gz_comp(state, Z_NO_FLUSH) == -1)
-            return -1;
-        len -= n;
-    }
-    return 0;
-}
-
-/* -- see zlib.h -- */
-int ZEXPORT gzwrite(file, buf, len)
-    gzFile file;
-    voidpc buf;
-    unsigned len;
-{
-    unsigned put = len;
-    gz_statep state;
-    z_streamp strm;
-
-    /* get internal structure */
-    if (file == NULL)
-        return 0;
-    state = (gz_statep)file;
-    strm = &(state->strm);
-
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
-        return 0;
-
-    /* since an int is returned, make sure len fits in one, otherwise return
-       with an error (this avoids the flaw in the interface) */
-    if ((int)len < 0) {
-        gz_error(state, Z_DATA_ERROR, "requested length does not fit in int");
-        return 0;
-    }
-
-    /* if len is zero, avoid unnecessary operations */
-    if (len == 0)
-        return 0;
-
-    /* allocate memory if this is the first time through */
-    if (state->size == 0 && gz_init(state) == -1)
-        return 0;
-
-    /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            return 0;
-    }
-
-    /* for small len, copy to input buffer, otherwise compress directly */
-    if (len < state->size) {
-        /* copy to input buffer, compress when full */
-        do {
-            unsigned have, copy;
-
-            if (strm->avail_in == 0)
-                strm->next_in = state->in;
-            have = (unsigned)((strm->next_in + strm->avail_in) - state->in);
-            copy = state->size - have;
-            if (copy > len)
-                copy = len;
-            memcpy(state->in + have, buf, copy);
-            strm->avail_in += copy;
-            state->x.pos += copy;
-            buf = (const char *)buf + copy;
-            len -= copy;
-            if (len && gz_comp(state, Z_NO_FLUSH) == -1)
-                return 0;
-        } while (len);
-    }
-    else {
-        /* consume whatever's left in the input buffer */
-        if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
-            return 0;
-
-        /* directly compress user buffer to file */
-        strm->avail_in = len;
-        strm->next_in = (z_const Bytef *)buf;
-        state->x.pos += len;
-        if (gz_comp(state, Z_NO_FLUSH) == -1)
-            return 0;
-    }
-
-    /* input was all buffered or compressed (put will fit in int) */
-    return (int)put;
-}
-
-/* -- see zlib.h -- */
-int ZEXPORT gzputc(file, c)
-    gzFile file;
-    int c;
-{
-    unsigned have;
-    unsigned char buf[1];
-    gz_statep state;
-    z_streamp strm;
-
-    /* get internal structure */
-    if (file == NULL)
-        return -1;
-    state = (gz_statep)file;
-    strm = &(state->strm);
-
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
-        return -1;
-
-    /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            return -1;
-    }
-
-    /* try writing to input buffer for speed (state->size == 0 if buffer not
-       initialized) */
-    if (state->size) {
-        if (strm->avail_in == 0)
-            strm->next_in = state->in;
-        have = (unsigned)((strm->next_in + strm->avail_in) - state->in);
-        if (have < state->size) {
-            state->in[have] = c;
-            strm->avail_in++;
-            state->x.pos++;
-            return c & 0xff;
-        }
-    }
-
-    /* no room in buffer or not initialized, use gz_write() */
-    buf[0] = c;
-    if (gzwrite(file, buf, 1) != 1)
-        return -1;
-    return c & 0xff;
-}
-
-/* -- see zlib.h -- */
-int ZEXPORT gzputs(file, str)
-    gzFile file;
-    const char *str;
-{
-    int ret;
-    unsigned len;
-
-    /* write string */
-    len = (unsigned)strlen(str);
-    ret = gzwrite(file, str, len);
-    return ret == 0 && len != 0 ? -1 : ret;
-}
-
-#if defined(STDC) || defined(Z_HAVE_STDARG_H)
-#include <stdarg.h>
-
-/* -- see zlib.h -- */
-int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va)
-{
-    int size, len;
-    gz_statep state;
-    z_streamp strm;
-
-    /* get internal structure */
-    if (file == NULL)
-        return -1;
-    state = (gz_statep)file;
-    strm = &(state->strm);
-
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
-        return 0;
-
-    /* make sure we have some buffer space */
-    if (state->size == 0 && gz_init(state) == -1)
-        return 0;
-
-    /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            return 0;
-    }
-
-    /* consume whatever's left in the input buffer */
-    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
-        return 0;
-
-    /* do the printf() into the input buffer, put length in len */
-    size = (int)(state->size);
-    state->in[size - 1] = 0;
-#ifdef NO_vsnprintf
-#  ifdef HAS_vsprintf_void
-    (void)vsprintf((char *)(state->in), format, va);
-    for (len = 0; len < size; len++)
-        if (state->in[len] == 0) break;
-#  else
-    len = vsprintf((char *)(state->in), format, va);
-#  endif
-#else
-#  ifdef HAS_vsnprintf_void
-    (void)vsnprintf((char *)(state->in), size, format, va);
-    len = strlen((char *)(state->in));
-#  else
-    len = vsnprintf((char *)(state->in), size, format, va);
-#  endif
-#endif
-
-    /* check that printf() results fit in buffer */
-    if (len <= 0 || len >= (int)size || state->in[size - 1] != 0)
-        return 0;
-
-    /* update buffer and position, defer compression until needed */
-    strm->avail_in = (unsigned)len;
-    strm->next_in = state->in;
-    state->x.pos += len;
-    return len;
-}
-
-int ZEXPORTVA gzprintf(gzFile file, const char *format, ...)
-{
-    va_list va;
-    int ret;
-
-    va_start(va, format);
-    ret = gzvprintf(file, format, va);
-    va_end(va);
-    return ret;
-}
-
-#else /* !STDC && !Z_HAVE_STDARG_H */
-
-/* -- see zlib.h -- */
-int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
-                       a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
-    gzFile file;
-    const char *format;
-    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
-        a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
-{
-    int size, len;
-    gz_statep state;
-    z_streamp strm;
-
-    /* get internal structure */
-    if (file == NULL)
-        return -1;
-    state = (gz_statep)file;
-    strm = &(state->strm);
-
-    /* check that can really pass pointer in ints */
-    if (sizeof(int) != sizeof(void *))
-        return 0;
-
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
-        return 0;
-
-    /* make sure we have some buffer space */
-    if (state->size == 0 && gz_init(state) == -1)
-        return 0;
-
-    /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            return 0;
-    }
-
-    /* consume whatever's left in the input buffer */
-    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
-        return 0;
-
-    /* do the printf() into the input buffer, put length in len */
-    size = (int)(state->size);
-    state->in[size - 1] = 0;
-#ifdef NO_snprintf
-#  ifdef HAS_sprintf_void
-    sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8,
-            a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
-    for (len = 0; len < size; len++)
-        if (state->in[len] == 0) break;
-#  else
-    len = sprintf((char *)(state->in), format, a1, a2, a3, a4, a5, a6, a7, a8,
-                  a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
-#  endif
-#else
-#  ifdef HAS_snprintf_void
-    snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6, a7, a8,
-             a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
-    len = strlen((char *)(state->in));
-#  else
-    len = snprintf((char *)(state->in), size, format, a1, a2, a3, a4, a5, a6,
-                   a7, a8, a9, a10, a11, a12, a13, a14, a15, a16, a17, a18,
-                   a19, a20);
-#  endif
-#endif
-
-    /* check that printf() results fit in buffer */
-    if (len <= 0 || len >= (int)size || state->in[size - 1] != 0)
-        return 0;
-
-    /* update buffer and position, defer compression until needed */
-    strm->avail_in = (unsigned)len;
-    strm->next_in = state->in;
-    state->x.pos += len;
-    return len;
-}
-
-#endif
-
-/* -- see zlib.h -- */
-int ZEXPORT gzflush(file, flush)
-    gzFile file;
-    int flush;
-{
-    gz_statep state;
-
-    /* get internal structure */
-    if (file == NULL)
-        return -1;
-    state = (gz_statep)file;
-
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
-        return Z_STREAM_ERROR;
-
-    /* check flush parameter */
-    if (flush < 0 || flush > Z_FINISH)
-        return Z_STREAM_ERROR;
-
-    /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            return -1;
-    }
-
-    /* compress remaining data with requested flush */
-    gz_comp(state, flush);
-    return state->err;
-}
-
-/* -- see zlib.h -- */
-int ZEXPORT gzsetparams(file, level, strategy)
-    gzFile file;
-    int level;
-    int strategy;
-{
-    gz_statep state;
-    z_streamp strm;
-
-    /* get internal structure */
-    if (file == NULL)
-        return Z_STREAM_ERROR;
-    state = (gz_statep)file;
-    strm = &(state->strm);
-
-    /* check that we're writing and that there's no error */
-    if (state->mode != GZ_WRITE || state->err != Z_OK)
-        return Z_STREAM_ERROR;
-
-    /* if no change is requested, then do nothing */
-    if (level == state->level && strategy == state->strategy)
-        return Z_OK;
-
-    /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            return -1;
-    }
-
-    /* change compression parameters for subsequent input */
-    if (state->size) {
-        /* flush previous input with previous parameters before changing */
-        if (strm->avail_in && gz_comp(state, Z_PARTIAL_FLUSH) == -1)
-            return state->err;
-        deflateParams(strm, level, strategy);
-    }
-    state->level = level;
-    state->strategy = strategy;
-    return Z_OK;
-}
-
-/* -- see zlib.h -- */
-int ZEXPORT gzclose_w(file)
-    gzFile file;
-{
-    int ret = Z_OK;
-    gz_statep state;
-
-    /* get internal structure */
-    if (file == NULL)
-        return Z_STREAM_ERROR;
-    state = (gz_statep)file;
-
-    /* check that we're writing */
-    if (state->mode != GZ_WRITE)
-        return Z_STREAM_ERROR;
-
-    /* check for seek request */
-    if (state->seek) {
-        state->seek = 0;
-        if (gz_zero(state, state->skip) == -1)
-            ret = state->err;
-    }
-
-    /* flush, free memory, and close file */
-    if (gz_comp(state, Z_FINISH) == -1)
-        ret = state->err;
-    if (state->size) {
-        if (!state->direct) {
-            (void)deflateEnd(&(state->strm));
-            free(state->out);
-        }
-        free(state->in);
-    }
-    gz_error(state, Z_OK, NULL);
-    free(state->path);
-    if (close(state->fd) == -1)
-        ret = Z_ERRNO;
-    free(state);
-    return ret;
-}
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/infback.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,664 +0,0 @@
-/*
- * 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.
- */
-
-/* infback.c -- inflate using a call-back interface
- * Copyright (C) 1995-2011 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/*
-   This code is largely copied from inflate.c.  Normally either infback.o or
-   inflate.o would be linked into an application--not both.  The interface
-   with inffast.c is retained so that optimized assembler-coded versions of
-   inflate_fast() can be used with either inflate.c or infback.c.
- */
-
-#include "zutil.h"
-#include "inftrees.h"
-#include "inflate.h"
-#include "inffast.h"
-
-/* function prototypes */
-local void fixedtables OF((struct inflate_state FAR *state));
-
-/*
-   strm provides memory allocation functions in zalloc and zfree, or
-   Z_NULL to use the library memory allocation functions.
-
-   windowBits is in the range 8..15, and window is a user-supplied
-   window and output buffer that is 2**windowBits bytes.
- */
-int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)
-z_streamp strm;
-int windowBits;
-unsigned char FAR *window;
-const char *version;
-int stream_size;
-{
-    struct inflate_state FAR *state;
-
-    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
-        stream_size != (int)(sizeof(z_stream)))
-        return Z_VERSION_ERROR;
-    if (strm == Z_NULL || window == Z_NULL ||
-        windowBits < 8 || windowBits > 15)
-        return Z_STREAM_ERROR;
-    strm->msg = Z_NULL;                 /* in case we return an error */
-    if (strm->zalloc == (alloc_func)0) {
-#ifdef Z_SOLO
-        return Z_STREAM_ERROR;
-#else
-        strm->zalloc = zcalloc;
-        strm->opaque = (voidpf)0;
-#endif
-    }
-    if (strm->zfree == (free_func)0)
-#ifdef Z_SOLO
-        return Z_STREAM_ERROR;
-#else
-    strm->zfree = zcfree;
-#endif
-    state = (struct inflate_state FAR *)ZALLOC(strm, 1,
-                                               sizeof(struct inflate_state));
-    if (state == Z_NULL) return Z_MEM_ERROR;
-    Tracev((stderr, "inflate: allocated\n"));
-    strm->state = (struct internal_state FAR *)state;
-    state->dmax = 32768U;
-    state->wbits = windowBits;
-    state->wsize = 1U << windowBits;
-    state->window = window;
-    state->wnext = 0;
-    state->whave = 0;
-    return Z_OK;
-}
-
-/*
-   Return state with length and distance decoding tables and index sizes set to
-   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
-   If BUILDFIXED is defined, then instead this routine builds the tables the
-   first time it's called, and returns those tables the first time and
-   thereafter.  This reduces the size of the code by about 2K bytes, in
-   exchange for a little execution time.  However, BUILDFIXED should not be
-   used for threaded applications, since the rewriting of the tables and virgin
-   may not be thread-safe.
- */
-local void fixedtables(state)
-struct inflate_state FAR *state;
-{
-#ifdef BUILDFIXED
-    static int virgin = 1;
-    static code *lenfix, *distfix;
-    static code fixed[544];
-
-    /* build fixed huffman tables if first call (may not be thread safe) */
-    if (virgin) {
-        unsigned sym, bits;
-        static code *next;
-
-        /* literal/length table */
-        sym = 0;
-        while (sym < 144) state->lens[sym++] = 8;
-        while (sym < 256) state->lens[sym++] = 9;
-        while (sym < 280) state->lens[sym++] = 7;
-        while (sym < 288) state->lens[sym++] = 8;
-        next = fixed;
-        lenfix = next;
-        bits = 9;
-        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
-
-        /* distance table */
-        sym = 0;
-        while (sym < 32) state->lens[sym++] = 5;
-        distfix = next;
-        bits = 5;
-        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
-
-        /* do this just once */
-        virgin = 0;
-    }
-#else /* !BUILDFIXED */
-#   include "inffixed.h"
-#endif /* BUILDFIXED */
-    state->lencode = lenfix;
-    state->lenbits = 9;
-    state->distcode = distfix;
-    state->distbits = 5;
-}
-
-/* Macros for inflateBack(): */
-
-/* Load returned state from inflate_fast() */
-#define LOAD() \
-    do { \
-        put = strm->next_out; \
-        left = strm->avail_out; \
-        next = strm->next_in; \
-        have = strm->avail_in; \
-        hold = state->hold; \
-        bits = state->bits; \
-    } while (0)
-
-/* Set state from registers for inflate_fast() */
-#define RESTORE() \
-    do { \
-        strm->next_out = put; \
-        strm->avail_out = left; \
-        strm->next_in = next; \
-        strm->avail_in = have; \
-        state->hold = hold; \
-        state->bits = bits; \
-    } while (0)
-
-/* Clear the input bit accumulator */
-#define INITBITS() \
-    do { \
-        hold = 0; \
-        bits = 0; \
-    } while (0)
-
-/* Assure that some input is available.  If input is requested, but denied,
-   then return a Z_BUF_ERROR from inflateBack(). */
-#define PULL() \
-    do { \
-        if (have == 0) { \
-            have = in(in_desc, &next); \
-            if (have == 0) { \
-                next = Z_NULL; \
-                ret = Z_BUF_ERROR; \
-                goto inf_leave; \
-            } \
-        } \
-    } while (0)
-
-/* Get a byte of input into the bit accumulator, or return from inflateBack()
-   with an error if there is no input available. */
-#define PULLBYTE() \
-    do { \
-        PULL(); \
-        have--; \
-        hold += (unsigned long)(*next++) << bits; \
-        bits += 8; \
-    } while (0)
-
-/* Assure that there are at least n bits in the bit accumulator.  If there is
-   not enough available input to do that, then return from inflateBack() with
-   an error. */
-#define NEEDBITS(n) \
-    do { \
-        while (bits < (unsigned)(n)) \
-            PULLBYTE(); \
-    } while (0)
-
-/* Return the low n bits of the bit accumulator (n < 16) */
-#define BITS(n) \
-    ((unsigned)hold & ((1U << (n)) - 1))
-
-/* Remove n bits from the bit accumulator */
-#define DROPBITS(n) \
-    do { \
-        hold >>= (n); \
-        bits -= (unsigned)(n); \
-    } while (0)
-
-/* Remove zero to seven bits as needed to go to a byte boundary */
-#define BYTEBITS() \
-    do { \
-        hold >>= bits & 7; \
-        bits -= bits & 7; \
-    } while (0)
-
-/* Assure that some output space is available, by writing out the window
-   if it's full.  If the write fails, return from inflateBack() with a
-   Z_BUF_ERROR. */
-#define ROOM() \
-    do { \
-        if (left == 0) { \
-            put = state->window; \
-            left = state->wsize; \
-            state->whave = left; \
-            if (out(out_desc, put, left)) { \
-                ret = Z_BUF_ERROR; \
-                goto inf_leave; \
-            } \
-        } \
-    } while (0)
-
-/*
-   strm provides the memory allocation functions and window buffer on input,
-   and provides information on the unused input on return.  For Z_DATA_ERROR
-   returns, strm will also provide an error message.
-
-   in() and out() are the call-back input and output functions.  When
-   inflateBack() needs more input, it calls in().  When inflateBack() has
-   filled the window with output, or when it completes with data in the
-   window, it calls out() to write out the data.  The application must not
-   change the provided input until in() is called again or inflateBack()
-   returns.  The application must not change the window/output buffer until
-   inflateBack() returns.
-
-   in() and out() are called with a descriptor parameter provided in the
-   inflateBack() call.  This parameter can be a structure that provides the
-   information required to do the read or write, as well as accumulated
-   information on the input and output such as totals and check values.
-
-   in() should return zero on failure.  out() should return non-zero on
-   failure.  If either in() or out() fails, than inflateBack() returns a
-   Z_BUF_ERROR.  strm->next_in can be checked for Z_NULL to see whether it
-   was in() or out() that caused in the error.  Otherwise,  inflateBack()
-   returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
-   error, or Z_MEM_ERROR if it could not allocate memory for the state.
-   inflateBack() can also return Z_STREAM_ERROR if the input parameters
-   are not correct, i.e. strm is Z_NULL or the state was not initialized.
- */
-int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)
-z_streamp strm;
-in_func in;
-void FAR *in_desc;
-out_func out;
-void FAR *out_desc;
-{
-    struct inflate_state FAR *state;
-    z_const unsigned char FAR *next;    /* next input */
-    unsigned char FAR *put;     /* next output */
-    unsigned have, left;        /* available input and output */
-    unsigned long hold;         /* bit buffer */
-    unsigned bits;              /* bits in bit buffer */
-    unsigned copy;              /* number of stored or match bytes to copy */
-    unsigned char FAR *from;    /* where to copy match bytes from */
-    code here;                  /* current decoding table entry */
-    code last;                  /* parent table entry */
-    unsigned len;               /* length to copy for repeats, bits to drop */
-    int ret;                    /* return code */
-    static const unsigned short order[19] = /* permutation of code lengths */
-        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
-
-    /* Check that the strm exists and that the state was initialized */
-    if (strm == Z_NULL || strm->state == Z_NULL)
-        return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)strm->state;
-
-    /* Reset the state */
-    strm->msg = Z_NULL;
-    state->mode = TYPE;
-    state->last = 0;
-    state->whave = 0;
-    next = strm->next_in;
-    have = next != Z_NULL ? strm->avail_in : 0;
-    hold = 0;
-    bits = 0;
-    put = state->window;
-    left = state->wsize;
-
-    /* Inflate until end of block marked as last */
-    for (;;)
-        switch (state->mode) {
-        case TYPE:
-            /* determine and dispatch block type */
-            if (state->last) {
-                BYTEBITS();
-                state->mode = DONE;
-                break;
-            }
-            NEEDBITS(3);
-            state->last = BITS(1);
-            DROPBITS(1);
-            switch (BITS(2)) {
-            case 0:                             /* stored block */
-                Tracev((stderr, "inflate:     stored block%s\n",
-                        state->last ? " (last)" : ""));
-                state->mode = STORED;
-                break;
-            case 1:                             /* fixed block */
-                fixedtables(state);
-                Tracev((stderr, "inflate:     fixed codes block%s\n",
-                        state->last ? " (last)" : ""));
-                state->mode = LEN;              /* decode codes */
-                break;
-            case 2:                             /* dynamic block */
-                Tracev((stderr, "inflate:     dynamic codes block%s\n",
-                        state->last ? " (last)" : ""));
-                state->mode = TABLE;
-                break;
-            case 3:
-                strm->msg = (char *)"invalid block type";
-                state->mode = BAD;
-            }
-            DROPBITS(2);
-            break;
-
-        case STORED:
-            /* get and verify stored block length */
-            BYTEBITS();                         /* go to byte boundary */
-            NEEDBITS(32);
-            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
-                strm->msg = (char *)"invalid stored block lengths";
-                state->mode = BAD;
-                break;
-            }
-            state->length = (unsigned)hold & 0xffff;
-            Tracev((stderr, "inflate:       stored length %u\n",
-                    state->length));
-            INITBITS();
-
-            /* copy stored block from input to output */
-            while (state->length != 0) {
-                copy = state->length;
-                PULL();
-                ROOM();
-                if (copy > have) copy = have;
-                if (copy > left) copy = left;
-                zmemcpy(put, next, copy);
-                have -= copy;
-                next += copy;
-                left -= copy;
-                put += copy;
-                state->length -= copy;
-            }
-            Tracev((stderr, "inflate:       stored end\n"));
-            state->mode = TYPE;
-            break;
-
-        case TABLE:
-            /* get dynamic table entries descriptor */
-            NEEDBITS(14);
-            state->nlen = BITS(5) + 257;
-            DROPBITS(5);
-            state->ndist = BITS(5) + 1;
-            DROPBITS(5);
-            state->ncode = BITS(4) + 4;
-            DROPBITS(4);
-#ifndef PKZIP_BUG_WORKAROUND
-            if (state->nlen > 286 || state->ndist > 30) {
-                strm->msg = (char *)"too many length or distance symbols";
-                state->mode = BAD;
-                break;
-            }
-#endif
-            Tracev((stderr, "inflate:       table sizes ok\n"));
-
-            /* get code length code lengths (not a typo) */
-            state->have = 0;
-            while (state->have < state->ncode) {
-                NEEDBITS(3);
-                state->lens[order[state->have++]] = (unsigned short)BITS(3);
-                DROPBITS(3);
-            }
-            while (state->have < 19)
-                state->lens[order[state->have++]] = 0;
-            state->next = state->codes;
-            state->lencode = (code const FAR *)(state->next);
-            state->lenbits = 7;
-            ret = inflate_table(CODES, state->lens, 19, &(state->next),
-                                &(state->lenbits), state->work);
-            if (ret) {
-                strm->msg = (char *)"invalid code lengths set";
-                state->mode = BAD;
-                break;
-            }
-            Tracev((stderr, "inflate:       code lengths ok\n"));
-
-            /* get length and distance code code lengths */
-            state->have = 0;
-            while (state->have < state->nlen + state->ndist) {
-                for (;;) {
-                    here = state->lencode[BITS(state->lenbits)];
-                    if ((unsigned)(here.bits) <= bits) break;
-                    PULLBYTE();
-                }
-                if (here.val < 16) {
-                    DROPBITS(here.bits);
-                    state->lens[state->have++] = here.val;
-                }
-                else {
-                    if (here.val == 16) {
-                        NEEDBITS(here.bits + 2);
-                        DROPBITS(here.bits);
-                        if (state->have == 0) {
-                            strm->msg = (char *)"invalid bit length repeat";
-                            state->mode = BAD;
-                            break;
-                        }
-                        len = (unsigned)(state->lens[state->have - 1]);
-                        copy = 3 + BITS(2);
-                        DROPBITS(2);
-                    }
-                    else if (here.val == 17) {
-                        NEEDBITS(here.bits + 3);
-                        DROPBITS(here.bits);
-                        len = 0;
-                        copy = 3 + BITS(3);
-                        DROPBITS(3);
-                    }
-                    else {
-                        NEEDBITS(here.bits + 7);
-                        DROPBITS(here.bits);
-                        len = 0;
-                        copy = 11 + BITS(7);
-                        DROPBITS(7);
-                    }
-                    if (state->have + copy > state->nlen + state->ndist) {
-                        strm->msg = (char *)"invalid bit length repeat";
-                        state->mode = BAD;
-                        break;
-                    }
-                    while (copy--)
-                        state->lens[state->have++] = (unsigned short)len;
-                }
-            }
-
-            /* handle error breaks in while */
-            if (state->mode == BAD) break;
-
-            /* check for end-of-block code (better have one) */
-            if (state->lens[256] == 0) {
-                strm->msg = (char *)"invalid code -- missing end-of-block";
-                state->mode = BAD;
-                break;
-            }
-
-            /* build code tables -- note: do not change the lenbits or distbits
-               values here (9 and 6) without reading the comments in inftrees.h
-               concerning the ENOUGH constants, which depend on those values */
-            state->next = state->codes;
-            state->lencode = (code const FAR *)(state->next);
-            state->lenbits = 9;
-            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
-                                &(state->lenbits), state->work);
-            if (ret) {
-                strm->msg = (char *)"invalid literal/lengths set";
-                state->mode = BAD;
-                break;
-            }
-            state->distcode = (code const FAR *)(state->next);
-            state->distbits = 6;
-            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
-                            &(state->next), &(state->distbits), state->work);
-            if (ret) {
-                strm->msg = (char *)"invalid distances set";
-                state->mode = BAD;
-                break;
-            }
-            Tracev((stderr, "inflate:       codes ok\n"));
-            state->mode = LEN;
-
-        case LEN:
-            /* use inflate_fast() if we have enough input and output */
-            if (have >= 6 && left >= 258) {
-                RESTORE();
-                if (state->whave < state->wsize)
-                    state->whave = state->wsize - left;
-                inflate_fast(strm, state->wsize);
-                LOAD();
-                break;
-            }
-
-            /* get a literal, length, or end-of-block code */
-            for (;;) {
-                here = state->lencode[BITS(state->lenbits)];
-                if ((unsigned)(here.bits) <= bits) break;
-                PULLBYTE();
-            }
-            if (here.op && (here.op & 0xf0) == 0) {
-                last = here;
-                for (;;) {
-                    here = state->lencode[last.val +
-                            (BITS(last.bits + last.op) >> last.bits)];
-                    if ((unsigned)(last.bits + here.bits) <= bits) break;
-                    PULLBYTE();
-                }
-                DROPBITS(last.bits);
-            }
-            DROPBITS(here.bits);
-            state->length = (unsigned)here.val;
-
-            /* process literal */
-            if (here.op == 0) {
-                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
-                        "inflate:         literal '%c'\n" :
-                        "inflate:         literal 0x%02x\n", here.val));
-                ROOM();
-                *put++ = (unsigned char)(state->length);
-                left--;
-                state->mode = LEN;
-                break;
-            }
-
-            /* process end of block */
-            if (here.op & 32) {
-                Tracevv((stderr, "inflate:         end of block\n"));
-                state->mode = TYPE;
-                break;
-            }
-
-            /* invalid code */
-            if (here.op & 64) {
-                strm->msg = (char *)"invalid literal/length code";
-                state->mode = BAD;
-                break;
-            }
-
-            /* length code -- get extra bits, if any */
-            state->extra = (unsigned)(here.op) & 15;
-            if (state->extra != 0) {
-                NEEDBITS(state->extra);
-                state->length += BITS(state->extra);
-                DROPBITS(state->extra);
-            }
-            Tracevv((stderr, "inflate:         length %u\n", state->length));
-
-            /* get distance code */
-            for (;;) {
-                here = state->distcode[BITS(state->distbits)];
-                if ((unsigned)(here.bits) <= bits) break;
-                PULLBYTE();
-            }
-            if ((here.op & 0xf0) == 0) {
-                last = here;
-                for (;;) {
-                    here = state->distcode[last.val +
-                            (BITS(last.bits + last.op) >> last.bits)];
-                    if ((unsigned)(last.bits + here.bits) <= bits) break;
-                    PULLBYTE();
-                }
-                DROPBITS(last.bits);
-            }
-            DROPBITS(here.bits);
-            if (here.op & 64) {
-                strm->msg = (char *)"invalid distance code";
-                state->mode = BAD;
-                break;
-            }
-            state->offset = (unsigned)here.val;
-
-            /* get distance extra bits, if any */
-            state->extra = (unsigned)(here.op) & 15;
-            if (state->extra != 0) {
-                NEEDBITS(state->extra);
-                state->offset += BITS(state->extra);
-                DROPBITS(state->extra);
-            }
-            if (state->offset > state->wsize - (state->whave < state->wsize ?
-                                                left : 0)) {
-                strm->msg = (char *)"invalid distance too far back";
-                state->mode = BAD;
-                break;
-            }
-            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
-
-            /* copy match from window to output */
-            do {
-                ROOM();
-                copy = state->wsize - state->offset;
-                if (copy < left) {
-                    from = put + copy;
-                    copy = left - copy;
-                }
-                else {
-                    from = put - state->offset;
-                    copy = left;
-                }
-                if (copy > state->length) copy = state->length;
-                state->length -= copy;
-                left -= copy;
-                do {
-                    *put++ = *from++;
-                } while (--copy);
-            } while (state->length != 0);
-            break;
-
-        case DONE:
-            /* inflate stream terminated properly -- write leftover output */
-            ret = Z_STREAM_END;
-            if (left < state->wsize) {
-                if (out(out_desc, state->window, state->wsize - left))
-                    ret = Z_BUF_ERROR;
-            }
-            goto inf_leave;
-
-        case BAD:
-            ret = Z_DATA_ERROR;
-            goto inf_leave;
-
-        default:                /* can't happen, but makes compilers happy */
-            ret = Z_STREAM_ERROR;
-            goto inf_leave;
-        }
-
-    /* Return unused input */
-  inf_leave:
-    strm->next_in = next;
-    strm->avail_in = have;
-    return ret;
-}
-
-int ZEXPORT inflateBackEnd(strm)
-z_streamp strm;
-{
-    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
-        return Z_STREAM_ERROR;
-    ZFREE(strm, strm->state);
-    strm->state = Z_NULL;
-    Tracev((stderr, "inflate: end\n"));
-    return Z_OK;
-}
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/inffast.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,364 +0,0 @@
-/*
- * 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.
- */
-
-/* inffast.c -- fast decoding
- * Copyright (C) 1995-2008, 2010, 2013 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-#include "zutil.h"
-#include "inftrees.h"
-#include "inflate.h"
-#include "inffast.h"
-
-#ifndef ASMINF
-
-/* Allow machine dependent optimization for post-increment or pre-increment.
-   Based on testing to date,
-   Pre-increment preferred for:
-   - PowerPC G3 (Adler)
-   - MIPS R5000 (Randers-Pehrson)
-   Post-increment preferred for:
-   - none
-   No measurable difference:
-   - Pentium III (Anderson)
-   - M68060 (Nikl)
- */
-#ifdef POSTINC
-#  define OFF 0
-#  define PUP(a) *(a)++
-#else
-#  define OFF 1
-#  define PUP(a) *++(a)
-#endif
-
-/*
-   Decode literal, length, and distance codes and write out the resulting
-   literal and match bytes until either not enough input or output is
-   available, an end-of-block is encountered, or a data error is encountered.
-   When large enough input and output buffers are supplied to inflate(), for
-   example, a 16K input buffer and a 64K output buffer, more than 95% of the
-   inflate execution time is spent in this routine.
-
-   Entry assumptions:
-
-        state->mode == LEN
-        strm->avail_in >= 6
-        strm->avail_out >= 258
-        start >= strm->avail_out
-        state->bits < 8
-
-   On return, state->mode is one of:
-
-        LEN -- ran out of enough output space or enough available input
-        TYPE -- reached end of block code, inflate() to interpret next block
-        BAD -- error in block data
-
-   Notes:
-
-    - The maximum input bits used by a length/distance pair is 15 bits for the
-      length code, 5 bits for the length extra, 15 bits for the distance code,
-      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
-      Therefore if strm->avail_in >= 6, then there is enough input to avoid
-      checking for available input while decoding.
-
-    - The maximum bytes that a single length/distance pair can output is 258
-      bytes, which is the maximum length that can be coded.  inflate_fast()
-      requires strm->avail_out >= 258 for each loop to avoid checking for
-      output space.
- */
-void ZLIB_INTERNAL inflate_fast(strm, start)
-z_streamp strm;
-unsigned start;         /* inflate()'s starting value for strm->avail_out */
-{
-    struct inflate_state FAR *state;
-    z_const unsigned char FAR *in;      /* local strm->next_in */
-    z_const unsigned char FAR *last;    /* have enough input while in < last */
-    unsigned char FAR *out;     /* local strm->next_out */
-    unsigned char FAR *beg;     /* inflate()'s initial strm->next_out */
-    unsigned char FAR *end;     /* while out < end, enough space available */
-#ifdef INFLATE_STRICT
-    unsigned dmax;              /* maximum distance from zlib header */
-#endif
-    unsigned wsize;             /* window size or zero if not using window */
-    unsigned whave;             /* valid bytes in the window */
-    unsigned wnext;             /* window write index */
-    unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */
-    unsigned long hold;         /* local strm->hold */
-    unsigned bits;              /* local strm->bits */
-    code const FAR *lcode;      /* local strm->lencode */
-    code const FAR *dcode;      /* local strm->distcode */
-    unsigned lmask;             /* mask for first level of length codes */
-    unsigned dmask;             /* mask for first level of distance codes */
-    code here;                  /* retrieved table entry */
-    unsigned op;                /* code bits, operation, extra bits, or */
-                                /*  window position, window bytes to copy */
-    unsigned len;               /* match length, unused bytes */
-    unsigned dist;              /* match distance */
-    unsigned char FAR *from;    /* where to copy match from */
-
-    /* copy state to local variables */
-    state = (struct inflate_state FAR *)strm->state;
-    in = strm->next_in - OFF;
-    last = in + (strm->avail_in - 5);
-    out = strm->next_out - OFF;
-    beg = out - (start - strm->avail_out);
-    end = out + (strm->avail_out - 257);
-#ifdef INFLATE_STRICT
-    dmax = state->dmax;
-#endif
-    wsize = state->wsize;
-    whave = state->whave;
-    wnext = state->wnext;
-    window = state->window;
-    hold = state->hold;
-    bits = state->bits;
-    lcode = state->lencode;
-    dcode = state->distcode;
-    lmask = (1U << state->lenbits) - 1;
-    dmask = (1U << state->distbits) - 1;
-
-    /* decode literals and length/distances until end-of-block or not enough
-       input data or output space */
-    do {
-        if (bits < 15) {
-            hold += (unsigned long)(PUP(in)) << bits;
-            bits += 8;
-            hold += (unsigned long)(PUP(in)) << bits;
-            bits += 8;
-        }
-        here = lcode[hold & lmask];
-      dolen:
-        op = (unsigned)(here.bits);
-        hold >>= op;
-        bits -= op;
-        op = (unsigned)(here.op);
-        if (op == 0) {                          /* literal */
-            Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
-                    "inflate:         literal '%c'\n" :
-                    "inflate:         literal 0x%02x\n", here.val));
-            PUP(out) = (unsigned char)(here.val);
-        }
-        else if (op & 16) {                     /* length base */
-            len = (unsigned)(here.val);
-            op &= 15;                           /* number of extra bits */
-            if (op) {
-                if (bits < op) {
-                    hold += (unsigned long)(PUP(in)) << bits;
-                    bits += 8;
-                }
-                len += (unsigned)hold & ((1U << op) - 1);
-                hold >>= op;
-                bits -= op;
-            }
-            Tracevv((stderr, "inflate:         length %u\n", len));
-            if (bits < 15) {
-                hold += (unsigned long)(PUP(in)) << bits;
-                bits += 8;
-                hold += (unsigned long)(PUP(in)) << bits;
-                bits += 8;
-            }
-            here = dcode[hold & dmask];
-          dodist:
-            op = (unsigned)(here.bits);
-            hold >>= op;
-            bits -= op;
-            op = (unsigned)(here.op);
-            if (op & 16) {                      /* distance base */
-                dist = (unsigned)(here.val);
-                op &= 15;                       /* number of extra bits */
-                if (bits < op) {
-                    hold += (unsigned long)(PUP(in)) << bits;
-                    bits += 8;
-                    if (bits < op) {
-                        hold += (unsigned long)(PUP(in)) << bits;
-                        bits += 8;
-                    }
-                }
-                dist += (unsigned)hold & ((1U << op) - 1);
-#ifdef INFLATE_STRICT
-                if (dist > dmax) {
-                    strm->msg = (char *)"invalid distance too far back";
-                    state->mode = BAD;
-                    break;
-                }
-#endif
-                hold >>= op;
-                bits -= op;
-                Tracevv((stderr, "inflate:         distance %u\n", dist));
-                op = (unsigned)(out - beg);     /* max distance in output */
-                if (dist > op) {                /* see if copy from window */
-                    op = dist - op;             /* distance back in window */
-                    if (op > whave) {
-                        if (state->sane) {
-                            strm->msg =
-                                (char *)"invalid distance too far back";
-                            state->mode = BAD;
-                            break;
-                        }
-#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
-                        if (len <= op - whave) {
-                            do {
-                                PUP(out) = 0;
-                            } while (--len);
-                            continue;
-                        }
-                        len -= op - whave;
-                        do {
-                            PUP(out) = 0;
-                        } while (--op > whave);
-                        if (op == 0) {
-                            from = out - dist;
-                            do {
-                                PUP(out) = PUP(from);
-                            } while (--len);
-                            continue;
-                        }
-#endif
-                    }
-                    from = window - OFF;
-                    if (wnext == 0) {           /* very common case */
-                        from += wsize - op;
-                        if (op < len) {         /* some from window */
-                            len -= op;
-                            do {
-                                PUP(out) = PUP(from);
-                            } while (--op);
-                            from = out - dist;  /* rest from output */
-                        }
-                    }
-                    else if (wnext < op) {      /* wrap around window */
-                        from += wsize + wnext - op;
-                        op -= wnext;
-                        if (op < len) {         /* some from end of window */
-                            len -= op;
-                            do {
-                                PUP(out) = PUP(from);
-                            } while (--op);
-                            from = window - OFF;
-                            if (wnext < len) {  /* some from start of window */
-                                op = wnext;
-                                len -= op;
-                                do {
-                                    PUP(out) = PUP(from);
-                                } while (--op);
-                                from = out - dist;      /* rest from output */
-                            }
-                        }
-                    }
-                    else {                      /* contiguous in window */
-                        from += wnext - op;
-                        if (op < len) {         /* some from window */
-                            len -= op;
-                            do {
-                                PUP(out) = PUP(from);
-                            } while (--op);
-                            from = out - dist;  /* rest from output */
-                        }
-                    }
-                    while (len > 2) {
-                        PUP(out) = PUP(from);
-                        PUP(out) = PUP(from);
-                        PUP(out) = PUP(from);
-                        len -= 3;
-                    }
-                    if (len) {
-                        PUP(out) = PUP(from);
-                        if (len > 1)
-                            PUP(out) = PUP(from);
-                    }
-                }
-                else {
-                    from = out - dist;          /* copy direct from output */
-                    do {                        /* minimum length is three */
-                        PUP(out) = PUP(from);
-                        PUP(out) = PUP(from);
-                        PUP(out) = PUP(from);
-                        len -= 3;
-                    } while (len > 2);
-                    if (len) {
-                        PUP(out) = PUP(from);
-                        if (len > 1)
-                            PUP(out) = PUP(from);
-                    }
-                }
-            }
-            else if ((op & 64) == 0) {          /* 2nd level distance code */
-                here = dcode[here.val + (hold & ((1U << op) - 1))];
-                goto dodist;
-            }
-            else {
-                strm->msg = (char *)"invalid distance code";
-                state->mode = BAD;
-                break;
-            }
-        }
-        else if ((op & 64) == 0) {              /* 2nd level length code */
-            here = lcode[here.val + (hold & ((1U << op) - 1))];
-            goto dolen;
-        }
-        else if (op & 32) {                     /* end-of-block */
-            Tracevv((stderr, "inflate:         end of block\n"));
-            state->mode = TYPE;
-            break;
-        }
-        else {
-            strm->msg = (char *)"invalid literal/length code";
-            state->mode = BAD;
-            break;
-        }
-    } while (in < last && out < end);
-
-    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
-    len = bits >> 3;
-    in -= len;
-    bits -= len << 3;
-    hold &= (1U << bits) - 1;
-
-    /* update state and return */
-    strm->next_in = in + OFF;
-    strm->next_out = out + OFF;
-    strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
-    strm->avail_out = (unsigned)(out < end ?
-                                 257 + (end - out) : 257 - (out - end));
-    state->hold = hold;
-    state->bits = bits;
-    return;
-}
-
-/*
-   inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
-   - Using bit fields for code structure
-   - Different op definition to avoid & for extra bits (do & for table bits)
-   - Three separate decoding do-loops for direct, window, and wnext == 0
-   - Special case for distance > 1 copies to do overlapped load and store copy
-   - Explicit branch predictions (based on measured branch probabilities)
-   - Deferring match copy and interspersed it with decoding subsequent codes
-   - Swapping literal/length else
-   - Swapping window/direct else
-   - Larger unrolled copy loops (three is about right)
-   - Moving len -= 3 statement into middle of loop
- */
-
-#endif /* !ASMINF */
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/inffast.h	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,35 +0,0 @@
-/*
- * 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.
- */
-
-/* inffast.h -- header to use inffast.c
- * Copyright (C) 1995-2003, 2010 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/* WARNING: this file should *not* be used by applications. It is
-   part of the implementation of the compression library and is
-   subject to change. Applications should only use zlib.h.
- */
-
-void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start));
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/inffixed.h	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,118 +0,0 @@
-/*
- * 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.
- */
-
-    /* inffixed.h -- table for decoding fixed codes
-     * Generated automatically by makefixed().
-     */
-
-    /* WARNING: this file should *not* be used by applications.
-       It is part of the implementation of this library and is
-       subject to change. Applications should only use zlib.h.
-     */
-
-    static const code lenfix[512] = {
-        {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
-        {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
-        {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
-        {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
-        {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
-        {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
-        {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
-        {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
-        {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
-        {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
-        {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
-        {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
-        {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
-        {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
-        {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
-        {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
-        {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
-        {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
-        {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
-        {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
-        {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
-        {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
-        {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
-        {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
-        {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
-        {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
-        {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
-        {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
-        {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
-        {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
-        {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
-        {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
-        {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
-        {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
-        {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
-        {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
-        {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
-        {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
-        {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
-        {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
-        {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
-        {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
-        {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
-        {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
-        {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
-        {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
-        {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
-        {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
-        {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
-        {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
-        {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
-        {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
-        {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
-        {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
-        {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
-        {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
-        {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
-        {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
-        {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
-        {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
-        {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
-        {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
-        {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
-        {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
-        {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
-        {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
-        {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
-        {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
-        {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
-        {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
-        {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
-        {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
-        {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
-        {0,9,255}
-    };
-
-    static const code distfix[32] = {
-        {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
-        {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
-        {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
-        {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
-        {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
-        {22,5,193},{64,5,0}
-    };
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/inflate.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1536 +0,0 @@
-/*
- * 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.
- */
-
-/* inflate.c -- zlib decompression
- * Copyright (C) 1995-2012 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/*
- * Change history:
- *
- * 1.2.beta0    24 Nov 2002
- * - First version -- complete rewrite of inflate to simplify code, avoid
- *   creation of window when not needed, minimize use of window when it is
- *   needed, make inffast.c even faster, implement gzip decoding, and to
- *   improve code readability and style over the previous zlib inflate code
- *
- * 1.2.beta1    25 Nov 2002
- * - Use pointers for available input and output checking in inffast.c
- * - Remove input and output counters in inffast.c
- * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
- * - Remove unnecessary second byte pull from length extra in inffast.c
- * - Unroll direct copy to three copies per loop in inffast.c
- *
- * 1.2.beta2    4 Dec 2002
- * - Change external routine names to reduce potential conflicts
- * - Correct filename to inffixed.h for fixed tables in inflate.c
- * - Make hbuf[] unsigned char to match parameter type in inflate.c
- * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
- *   to avoid negation problem on Alphas (64 bit) in inflate.c
- *
- * 1.2.beta3    22 Dec 2002
- * - Add comments on state->bits assertion in inffast.c
- * - Add comments on op field in inftrees.h
- * - Fix bug in reuse of allocated window after inflateReset()
- * - Remove bit fields--back to byte structure for speed
- * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
- * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
- * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
- * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
- * - Use local copies of stream next and avail values, as well as local bit
- *   buffer and bit count in inflate()--for speed when inflate_fast() not used
- *
- * 1.2.beta4    1 Jan 2003
- * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
- * - Move a comment on output buffer sizes from inffast.c to inflate.c
- * - Add comments in inffast.c to introduce the inflate_fast() routine
- * - Rearrange window copies in inflate_fast() for speed and simplification
- * - Unroll last copy for window match in inflate_fast()
- * - Use local copies of window variables in inflate_fast() for speed
- * - Pull out common wnext == 0 case for speed in inflate_fast()
- * - Make op and len in inflate_fast() unsigned for consistency
- * - Add FAR to lcode and dcode declarations in inflate_fast()
- * - Simplified bad distance check in inflate_fast()
- * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
- *   source file infback.c to provide a call-back interface to inflate for
- *   programs like gzip and unzip -- uses window as output buffer to avoid
- *   window copying
- *
- * 1.2.beta5    1 Jan 2003
- * - Improved inflateBack() interface to allow the caller to provide initial
- *   input in strm.
- * - Fixed stored blocks bug in inflateBack()
- *
- * 1.2.beta6    4 Jan 2003
- * - Added comments in inffast.c on effectiveness of POSTINC
- * - Typecasting all around to reduce compiler warnings
- * - Changed loops from while (1) or do {} while (1) to for (;;), again to
- *   make compilers happy
- * - Changed type of window in inflateBackInit() to unsigned char *
- *
- * 1.2.beta7    27 Jan 2003
- * - Changed many types to unsigned or unsigned short to avoid warnings
- * - Added inflateCopy() function
- *
- * 1.2.0        9 Mar 2003
- * - Changed inflateBack() interface to provide separate opaque descriptors
- *   for the in() and out() functions
- * - Changed inflateBack() argument and in_func typedef to swap the length
- *   and buffer address return values for the input function
- * - Check next_in and next_out for Z_NULL on entry to inflate()
- *
- * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
- */
-
-#include "zutil.h"
-#include "inftrees.h"
-#include "inflate.h"
-#include "inffast.h"
-
-#ifdef MAKEFIXED
-#  ifndef BUILDFIXED
-#    define BUILDFIXED
-#  endif
-#endif
-
-/* function prototypes */
-local void fixedtables OF((struct inflate_state FAR *state));
-local int updatewindow OF((z_streamp strm, const unsigned char FAR *end,
-                           unsigned copy));
-#ifdef BUILDFIXED
-   void makefixed OF((void));
-#endif
-local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf,
-                              unsigned len));
-
-int ZEXPORT inflateResetKeep(strm)
-z_streamp strm;
-{
-    struct inflate_state FAR *state;
-
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)strm->state;
-    strm->total_in = strm->total_out = state->total = 0;
-    strm->msg = Z_NULL;
-    if (state->wrap)        /* to support ill-conceived Java test suite */
-        strm->adler = state->wrap & 1;
-    state->mode = HEAD;
-    state->last = 0;
-    state->havedict = 0;
-    state->dmax = 32768U;
-    state->head = Z_NULL;
-    state->hold = 0;
-    state->bits = 0;
-    state->lencode = state->distcode = state->next = state->codes;
-    state->sane = 1;
-    state->back = -1;
-    Tracev((stderr, "inflate: reset\n"));
-    return Z_OK;
-}
-
-int ZEXPORT inflateReset(strm)
-z_streamp strm;
-{
-    struct inflate_state FAR *state;
-
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)strm->state;
-    state->wsize = 0;
-    state->whave = 0;
-    state->wnext = 0;
-    return inflateResetKeep(strm);
-}
-
-int ZEXPORT inflateReset2(strm, windowBits)
-z_streamp strm;
-int windowBits;
-{
-    int wrap;
-    struct inflate_state FAR *state;
-
-    /* get the state */
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)strm->state;
-
-    /* extract wrap request from windowBits parameter */
-    if (windowBits < 0) {
-        wrap = 0;
-        windowBits = -windowBits;
-    }
-    else {
-        wrap = (windowBits >> 4) + 1;
-#ifdef GUNZIP
-        if (windowBits < 48)
-            windowBits &= 15;
-#endif
-    }
-
-    /* set number of window bits, free window if different */
-    if (windowBits && (windowBits < 8 || windowBits > 15))
-        return Z_STREAM_ERROR;
-    if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
-        ZFREE(strm, state->window);
-        state->window = Z_NULL;
-    }
-
-    /* update state and reset the rest of it */
-    state->wrap = wrap;
-    state->wbits = (unsigned)windowBits;
-    return inflateReset(strm);
-}
-
-int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
-z_streamp strm;
-int windowBits;
-const char *version;
-int stream_size;
-{
-    int ret;
-    struct inflate_state FAR *state;
-
-    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
-        stream_size != (int)(sizeof(z_stream)))
-        return Z_VERSION_ERROR;
-    if (strm == Z_NULL) return Z_STREAM_ERROR;
-    strm->msg = Z_NULL;                 /* in case we return an error */
-    if (strm->zalloc == (alloc_func)0) {
-#ifdef Z_SOLO
-        return Z_STREAM_ERROR;
-#else
-        strm->zalloc = zcalloc;
-        strm->opaque = (voidpf)0;
-#endif
-    }
-    if (strm->zfree == (free_func)0)
-#ifdef Z_SOLO
-        return Z_STREAM_ERROR;
-#else
-        strm->zfree = zcfree;
-#endif
-    state = (struct inflate_state FAR *)
-            ZALLOC(strm, 1, sizeof(struct inflate_state));
-    if (state == Z_NULL) return Z_MEM_ERROR;
-    Tracev((stderr, "inflate: allocated\n"));
-    strm->state = (struct internal_state FAR *)state;
-    state->window = Z_NULL;
-    ret = inflateReset2(strm, windowBits);
-    if (ret != Z_OK) {
-        ZFREE(strm, state);
-        strm->state = Z_NULL;
-    }
-    return ret;
-}
-
-int ZEXPORT inflateInit_(strm, version, stream_size)
-z_streamp strm;
-const char *version;
-int stream_size;
-{
-    return inflateInit2_(strm, DEF_WBITS, version, stream_size);
-}
-
-int ZEXPORT inflatePrime(strm, bits, value)
-z_streamp strm;
-int bits;
-int value;
-{
-    struct inflate_state FAR *state;
-
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)strm->state;
-    if (bits < 0) {
-        state->hold = 0;
-        state->bits = 0;
-        return Z_OK;
-    }
-    if (bits > 16 || state->bits + bits > 32) return Z_STREAM_ERROR;
-    value &= (1L << bits) - 1;
-    state->hold += value << state->bits;
-    state->bits += bits;
-    return Z_OK;
-}
-
-/*
-   Return state with length and distance decoding tables and index sizes set to
-   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
-   If BUILDFIXED is defined, then instead this routine builds the tables the
-   first time it's called, and returns those tables the first time and
-   thereafter.  This reduces the size of the code by about 2K bytes, in
-   exchange for a little execution time.  However, BUILDFIXED should not be
-   used for threaded applications, since the rewriting of the tables and virgin
-   may not be thread-safe.
- */
-local void fixedtables(state)
-struct inflate_state FAR *state;
-{
-#ifdef BUILDFIXED
-    static int virgin = 1;
-    static code *lenfix, *distfix;
-    static code fixed[544];
-
-    /* build fixed huffman tables if first call (may not be thread safe) */
-    if (virgin) {
-        unsigned sym, bits;
-        static code *next;
-
-        /* literal/length table */
-        sym = 0;
-        while (sym < 144) state->lens[sym++] = 8;
-        while (sym < 256) state->lens[sym++] = 9;
-        while (sym < 280) state->lens[sym++] = 7;
-        while (sym < 288) state->lens[sym++] = 8;
-        next = fixed;
-        lenfix = next;
-        bits = 9;
-        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
-
-        /* distance table */
-        sym = 0;
-        while (sym < 32) state->lens[sym++] = 5;
-        distfix = next;
-        bits = 5;
-        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
-
-        /* do this just once */
-        virgin = 0;
-    }
-#else /* !BUILDFIXED */
-#   include "inffixed.h"
-#endif /* BUILDFIXED */
-    state->lencode = lenfix;
-    state->lenbits = 9;
-    state->distcode = distfix;
-    state->distbits = 5;
-}
-
-#ifdef MAKEFIXED
-#include <stdio.h>
-
-/*
-   Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also
-   defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes
-   those tables to stdout, which would be piped to inffixed.h.  A small program
-   can simply call makefixed to do this:
-
-    void makefixed(void);
-
-    int main(void)
-    {
-        makefixed();
-        return 0;
-    }
-
-   Then that can be linked with zlib built with MAKEFIXED defined and run:
-
-    a.out > inffixed.h
- */
-void makefixed()
-{
-    unsigned low, size;
-    struct inflate_state state;
-
-    fixedtables(&state);
-    puts("    /* inffixed.h -- table for decoding fixed codes");
-    puts("     * Generated automatically by makefixed().");
-    puts("     */");
-    puts("");
-    puts("    /* WARNING: this file should *not* be used by applications.");
-    puts("       It is part of the implementation of this library and is");
-    puts("       subject to change. Applications should only use zlib.h.");
-    puts("     */");
-    puts("");
-    size = 1U << 9;
-    printf("    static const code lenfix[%u] = {", size);
-    low = 0;
-    for (;;) {
-        if ((low % 7) == 0) printf("\n        ");
-        printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
-               state.lencode[low].bits, state.lencode[low].val);
-        if (++low == size) break;
-        putchar(',');
-    }
-    puts("\n    };");
-    size = 1U << 5;
-    printf("\n    static const code distfix[%u] = {", size);
-    low = 0;
-    for (;;) {
-        if ((low % 6) == 0) printf("\n        ");
-        printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
-               state.distcode[low].val);
-        if (++low == size) break;
-        putchar(',');
-    }
-    puts("\n    };");
-}
-#endif /* MAKEFIXED */
-
-/*
-   Update the window with the last wsize (normally 32K) bytes written before
-   returning.  If window does not exist yet, create it.  This is only called
-   when a window is already in use, or when output has been written during this
-   inflate call, but the end of the deflate stream has not been reached yet.
-   It is also called to create a window for dictionary data when a dictionary
-   is loaded.
-
-   Providing output buffers larger than 32K to inflate() should provide a speed
-   advantage, since only the last 32K of output is copied to the sliding window
-   upon return from inflate(), and since all distances after the first 32K of
-   output will fall in the output data, making match copies simpler and faster.
-   The advantage may be dependent on the size of the processor's data caches.
- */
-local int updatewindow(strm, end, copy)
-z_streamp strm;
-const Bytef *end;
-unsigned copy;
-{
-    struct inflate_state FAR *state;
-    unsigned dist;
-
-    state = (struct inflate_state FAR *)strm->state;
-
-    /* if it hasn't been done already, allocate space for the window */
-    if (state->window == Z_NULL) {
-        state->window = (unsigned char FAR *)
-                        ZALLOC(strm, 1U << state->wbits,
-                               sizeof(unsigned char));
-        if (state->window == Z_NULL) return 1;
-    }
-
-    /* if window not in use yet, initialize */
-    if (state->wsize == 0) {
-        state->wsize = 1U << state->wbits;
-        state->wnext = 0;
-        state->whave = 0;
-    }
-
-    /* copy state->wsize or less output bytes into the circular window */
-    if (copy >= state->wsize) {
-        zmemcpy(state->window, end - state->wsize, state->wsize);
-        state->wnext = 0;
-        state->whave = state->wsize;
-    }
-    else {
-        dist = state->wsize - state->wnext;
-        if (dist > copy) dist = copy;
-        zmemcpy(state->window + state->wnext, end - copy, dist);
-        copy -= dist;
-        if (copy) {
-            zmemcpy(state->window, end - copy, copy);
-            state->wnext = copy;
-            state->whave = state->wsize;
-        }
-        else {
-            state->wnext += dist;
-            if (state->wnext == state->wsize) state->wnext = 0;
-            if (state->whave < state->wsize) state->whave += dist;
-        }
-    }
-    return 0;
-}
-
-/* Macros for inflate(): */
-
-/* check function to use adler32() for zlib or crc32() for gzip */
-#ifdef GUNZIP
-#  define UPDATE(check, buf, len) \
-    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
-#else
-#  define UPDATE(check, buf, len) adler32(check, buf, len)
-#endif
-
-/* check macros for header crc */
-#ifdef GUNZIP
-#  define CRC2(check, word) \
-    do { \
-        hbuf[0] = (unsigned char)(word); \
-        hbuf[1] = (unsigned char)((word) >> 8); \
-        check = crc32(check, hbuf, 2); \
-    } while (0)
-
-#  define CRC4(check, word) \
-    do { \
-        hbuf[0] = (unsigned char)(word); \
-        hbuf[1] = (unsigned char)((word) >> 8); \
-        hbuf[2] = (unsigned char)((word) >> 16); \
-        hbuf[3] = (unsigned char)((word) >> 24); \
-        check = crc32(check, hbuf, 4); \
-    } while (0)
-#endif
-
-/* Load registers with state in inflate() for speed */
-#define LOAD() \
-    do { \
-        put = strm->next_out; \
-        left = strm->avail_out; \
-        next = strm->next_in; \
-        have = strm->avail_in; \
-        hold = state->hold; \
-        bits = state->bits; \
-    } while (0)
-
-/* Restore state from registers in inflate() */
-#define RESTORE() \
-    do { \
-        strm->next_out = put; \
-        strm->avail_out = left; \
-        strm->next_in = next; \
-        strm->avail_in = have; \
-        state->hold = hold; \
-        state->bits = bits; \
-    } while (0)
-
-/* Clear the input bit accumulator */
-#define INITBITS() \
-    do { \
-        hold = 0; \
-        bits = 0; \
-    } while (0)
-
-/* Get a byte of input into the bit accumulator, or return from inflate()
-   if there is no input available. */
-#define PULLBYTE() \
-    do { \
-        if (have == 0) goto inf_leave; \
-        have--; \
-        hold += (unsigned long)(*next++) << bits; \
-        bits += 8; \
-    } while (0)
-
-/* Assure that there are at least n bits in the bit accumulator.  If there is
-   not enough available input to do that, then return from inflate(). */
-#define NEEDBITS(n) \
-    do { \
-        while (bits < (unsigned)(n)) \
-            PULLBYTE(); \
-    } while (0)
-
-/* Return the low n bits of the bit accumulator (n < 16) */
-#define BITS(n) \
-    ((unsigned)hold & ((1U << (n)) - 1))
-
-/* Remove n bits from the bit accumulator */
-#define DROPBITS(n) \
-    do { \
-        hold >>= (n); \
-        bits -= (unsigned)(n); \
-    } while (0)
-
-/* Remove zero to seven bits as needed to go to a byte boundary */
-#define BYTEBITS() \
-    do { \
-        hold >>= bits & 7; \
-        bits -= bits & 7; \
-    } while (0)
-
-/*
-   inflate() uses a state machine to process as much input data and generate as
-   much output data as possible before returning.  The state machine is
-   structured roughly as follows:
-
-    for (;;) switch (state) {
-    ...
-    case STATEn:
-        if (not enough input data or output space to make progress)
-            return;
-        ... make progress ...
-        state = STATEm;
-        break;
-    ...
-    }
-
-   so when inflate() is called again, the same case is attempted again, and
-   if the appropriate resources are provided, the machine proceeds to the
-   next state.  The NEEDBITS() macro is usually the way the state evaluates
-   whether it can proceed or should return.  NEEDBITS() does the return if
-   the requested bits are not available.  The typical use of the BITS macros
-   is:
-
-        NEEDBITS(n);
-        ... do something with BITS(n) ...
-        DROPBITS(n);
-
-   where NEEDBITS(n) either returns from inflate() if there isn't enough
-   input left to load n bits into the accumulator, or it continues.  BITS(n)
-   gives the low n bits in the accumulator.  When done, DROPBITS(n) drops
-   the low n bits off the accumulator.  INITBITS() clears the accumulator
-   and sets the number of available bits to zero.  BYTEBITS() discards just
-   enough bits to put the accumulator on a byte boundary.  After BYTEBITS()
-   and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
-
-   NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
-   if there is no input available.  The decoding of variable length codes uses
-   PULLBYTE() directly in order to pull just enough bytes to decode the next
-   code, and no more.
-
-   Some states loop until they get enough input, making sure that enough
-   state information is maintained to continue the loop where it left off
-   if NEEDBITS() returns in the loop.  For example, want, need, and keep
-   would all have to actually be part of the saved state in case NEEDBITS()
-   returns:
-
-    case STATEw:
-        while (want < need) {
-            NEEDBITS(n);
-            keep[want++] = BITS(n);
-            DROPBITS(n);
-        }
-        state = STATEx;
-    case STATEx:
-
-   As shown above, if the next state is also the next case, then the break
-   is omitted.
-
-   A state may also return if there is not enough output space available to
-   complete that state.  Those states are copying stored data, writing a
-   literal byte, and copying a matching string.
-
-   When returning, a "goto inf_leave" is used to update the total counters,
-   update the check value, and determine whether any progress has been made
-   during that inflate() call in order to return the proper return code.
-   Progress is defined as a change in either strm->avail_in or strm->avail_out.
-   When there is a window, goto inf_leave will update the window with the last
-   output written.  If a goto inf_leave occurs in the middle of decompression
-   and there is no window currently, goto inf_leave will create one and copy
-   output to the window for the next call of inflate().
-
-   In this implementation, the flush parameter of inflate() only affects the
-   return code (per zlib.h).  inflate() always writes as much as possible to
-   strm->next_out, given the space available and the provided input--the effect
-   documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers
-   the allocation of and copying into a sliding window until necessary, which
-   provides the effect documented in zlib.h for Z_FINISH when the entire input
-   stream available.  So the only thing the flush parameter actually does is:
-   when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it
-   will return Z_BUF_ERROR if it has not reached the end of the stream.
- */
-
-int ZEXPORT inflate(strm, flush)
-z_streamp strm;
-int flush;
-{
-    struct inflate_state FAR *state;
-    z_const unsigned char FAR *next;    /* next input */
-    unsigned char FAR *put;     /* next output */
-    unsigned have, left;        /* available input and output */
-    unsigned long hold;         /* bit buffer */
-    unsigned bits;              /* bits in bit buffer */
-    unsigned in, out;           /* save starting available input and output */
-    unsigned copy;              /* number of stored or match bytes to copy */
-    unsigned char FAR *from;    /* where to copy match bytes from */
-    code here;                  /* current decoding table entry */
-    code last;                  /* parent table entry */
-    unsigned len;               /* length to copy for repeats, bits to drop */
-    int ret;                    /* return code */
-#ifdef GUNZIP
-    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
-#endif
-    static const unsigned short order[19] = /* permutation of code lengths */
-        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
-
-    if (strm == Z_NULL || strm->state == Z_NULL || strm->next_out == Z_NULL ||
-        (strm->next_in == Z_NULL && strm->avail_in != 0))
-        return Z_STREAM_ERROR;
-
-    state = (struct inflate_state FAR *)strm->state;
-    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
-    LOAD();
-    in = have;
-    out = left;
-    ret = Z_OK;
-    for (;;)
-        switch (state->mode) {
-        case HEAD:
-            if (state->wrap == 0) {
-                state->mode = TYPEDO;
-                break;
-            }
-            NEEDBITS(16);
-#ifdef GUNZIP
-            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
-                state->check = crc32(0L, Z_NULL, 0);
-                CRC2(state->check, hold);
-                INITBITS();
-                state->mode = FLAGS;
-                break;
-            }
-            state->flags = 0;           /* expect zlib header */
-            if (state->head != Z_NULL)
-                state->head->done = -1;
-            if (!(state->wrap & 1) ||   /* check if zlib header allowed */
-#else
-            if (
-#endif
-                ((BITS(8) << 8) + (hold >> 8)) % 31) {
-                strm->msg = (char *)"incorrect header check";
-                state->mode = BAD;
-                break;
-            }
-            if (BITS(4) != Z_DEFLATED) {
-                strm->msg = (char *)"unknown compression method";
-                state->mode = BAD;
-                break;
-            }
-            DROPBITS(4);
-            len = BITS(4) + 8;
-            if (state->wbits == 0)
-                state->wbits = len;
-            else if (len > state->wbits) {
-                strm->msg = (char *)"invalid window size";
-                state->mode = BAD;
-                break;
-            }
-            state->dmax = 1U << len;
-            Tracev((stderr, "inflate:   zlib header ok\n"));
-            strm->adler = state->check = adler32(0L, Z_NULL, 0);
-            state->mode = hold & 0x200 ? DICTID : TYPE;
-            INITBITS();
-            break;
-#ifdef GUNZIP
-        case FLAGS:
-            NEEDBITS(16);
-            state->flags = (int)(hold);
-            if ((state->flags & 0xff) != Z_DEFLATED) {
-                strm->msg = (char *)"unknown compression method";
-                state->mode = BAD;
-                break;
-            }
-            if (state->flags & 0xe000) {
-                strm->msg = (char *)"unknown header flags set";
-                state->mode = BAD;
-                break;
-            }
-            if (state->head != Z_NULL)
-                state->head->text = (int)((hold >> 8) & 1);
-            if (state->flags & 0x0200) CRC2(state->check, hold);
-            INITBITS();
-            state->mode = TIME;
-        case TIME:
-            NEEDBITS(32);
-            if (state->head != Z_NULL)
-                state->head->time = hold;
-            if (state->flags & 0x0200) CRC4(state->check, hold);
-            INITBITS();
-            state->mode = OS;
-        case OS:
-            NEEDBITS(16);
-            if (state->head != Z_NULL) {
-                state->head->xflags = (int)(hold & 0xff);
-                state->head->os = (int)(hold >> 8);
-            }
-            if (state->flags & 0x0200) CRC2(state->check, hold);
-            INITBITS();
-            state->mode = EXLEN;
-        case EXLEN:
-            if (state->flags & 0x0400) {
-                NEEDBITS(16);
-                state->length = (unsigned)(hold);
-                if (state->head != Z_NULL)
-                    state->head->extra_len = (unsigned)hold;
-                if (state->flags & 0x0200) CRC2(state->check, hold);
-                INITBITS();
-            }
-            else if (state->head != Z_NULL)
-                state->head->extra = Z_NULL;
-            state->mode = EXTRA;
-        case EXTRA:
-            if (state->flags & 0x0400) {
-                copy = state->length;
-                if (copy > have) copy = have;
-                if (copy) {
-                    if (state->head != Z_NULL &&
-                        state->head->extra != Z_NULL) {
-                        len = state->head->extra_len - state->length;
-                        zmemcpy(state->head->extra + len, next,
-                                len + copy > state->head->extra_max ?
-                                state->head->extra_max - len : copy);
-                    }
-                    if (state->flags & 0x0200)
-                        state->check = crc32(state->check, next, copy);
-                    have -= copy;
-                    next += copy;
-                    state->length -= copy;
-                }
-                if (state->length) goto inf_leave;
-            }
-            state->length = 0;
-            state->mode = NAME;
-        case NAME:
-            if (state->flags & 0x0800) {
-                if (have == 0) goto inf_leave;
-                copy = 0;
-                do {
-                    len = (unsigned)(next[copy++]);
-                    if (state->head != Z_NULL &&
-                            state->head->name != Z_NULL &&
-                            state->length < state->head->name_max)
-                        state->head->name[state->length++] = len;
-                } while (len && copy < have);
-                if (state->flags & 0x0200)
-                    state->check = crc32(state->check, next, copy);
-                have -= copy;
-                next += copy;
-                if (len) goto inf_leave;
-            }
-            else if (state->head != Z_NULL)
-                state->head->name = Z_NULL;
-            state->length = 0;
-            state->mode = COMMENT;
-        case COMMENT:
-            if (state->flags & 0x1000) {
-                if (have == 0) goto inf_leave;
-                copy = 0;
-                do {
-                    len = (unsigned)(next[copy++]);
-                    if (state->head != Z_NULL &&
-                            state->head->comment != Z_NULL &&
-                            state->length < state->head->comm_max)
-                        state->head->comment[state->length++] = len;
-                } while (len && copy < have);
-                if (state->flags & 0x0200)
-                    state->check = crc32(state->check, next, copy);
-                have -= copy;
-                next += copy;
-                if (len) goto inf_leave;
-            }
-            else if (state->head != Z_NULL)
-                state->head->comment = Z_NULL;
-            state->mode = HCRC;
-        case HCRC:
-            if (state->flags & 0x0200) {
-                NEEDBITS(16);
-                if (hold != (state->check & 0xffff)) {
-                    strm->msg = (char *)"header crc mismatch";
-                    state->mode = BAD;
-                    break;
-                }
-                INITBITS();
-            }
-            if (state->head != Z_NULL) {
-                state->head->hcrc = (int)((state->flags >> 9) & 1);
-                state->head->done = 1;
-            }
-            strm->adler = state->check = crc32(0L, Z_NULL, 0);
-            state->mode = TYPE;
-            break;
-#endif
-        case DICTID:
-            NEEDBITS(32);
-            strm->adler = state->check = ZSWAP32(hold);
-            INITBITS();
-            state->mode = DICT;
-        case DICT:
-            if (state->havedict == 0) {
-                RESTORE();
-                return Z_NEED_DICT;
-            }
-            strm->adler = state->check = adler32(0L, Z_NULL, 0);
-            state->mode = TYPE;
-        case TYPE:
-            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
-        case TYPEDO:
-            if (state->last) {
-                BYTEBITS();
-                state->mode = CHECK;
-                break;
-            }
-            NEEDBITS(3);
-            state->last = BITS(1);
-            DROPBITS(1);
-            switch (BITS(2)) {
-            case 0:                             /* stored block */
-                Tracev((stderr, "inflate:     stored block%s\n",
-                        state->last ? " (last)" : ""));
-                state->mode = STORED;
-                break;
-            case 1:                             /* fixed block */
-                fixedtables(state);
-                Tracev((stderr, "inflate:     fixed codes block%s\n",
-                        state->last ? " (last)" : ""));
-                state->mode = LEN_;             /* decode codes */
-                if (flush == Z_TREES) {
-                    DROPBITS(2);
-                    goto inf_leave;
-                }
-                break;
-            case 2:                             /* dynamic block */
-                Tracev((stderr, "inflate:     dynamic codes block%s\n",
-                        state->last ? " (last)" : ""));
-                state->mode = TABLE;
-                break;
-            case 3:
-                strm->msg = (char *)"invalid block type";
-                state->mode = BAD;
-            }
-            DROPBITS(2);
-            break;
-        case STORED:
-            BYTEBITS();                         /* go to byte boundary */
-            NEEDBITS(32);
-            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
-                strm->msg = (char *)"invalid stored block lengths";
-                state->mode = BAD;
-                break;
-            }
-            state->length = (unsigned)hold & 0xffff;
-            Tracev((stderr, "inflate:       stored length %u\n",
-                    state->length));
-            INITBITS();
-            state->mode = COPY_;
-            if (flush == Z_TREES) goto inf_leave;
-        case COPY_:
-            state->mode = COPY;
-        case COPY:
-            copy = state->length;
-            if (copy) {
-                if (copy > have) copy = have;
-                if (copy > left) copy = left;
-                if (copy == 0) goto inf_leave;
-                zmemcpy(put, next, copy);
-                have -= copy;
-                next += copy;
-                left -= copy;
-                put += copy;
-                state->length -= copy;
-                break;
-            }
-            Tracev((stderr, "inflate:       stored end\n"));
-            state->mode = TYPE;
-            break;
-        case TABLE:
-            NEEDBITS(14);
-            state->nlen = BITS(5) + 257;
-            DROPBITS(5);
-            state->ndist = BITS(5) + 1;
-            DROPBITS(5);
-            state->ncode = BITS(4) + 4;
-            DROPBITS(4);
-#ifndef PKZIP_BUG_WORKAROUND
-            if (state->nlen > 286 || state->ndist > 30) {
-                strm->msg = (char *)"too many length or distance symbols";
-                state->mode = BAD;
-                break;
-            }
-#endif
-            Tracev((stderr, "inflate:       table sizes ok\n"));
-            state->have = 0;
-            state->mode = LENLENS;
-        case LENLENS:
-            while (state->have < state->ncode) {
-                NEEDBITS(3);
-                state->lens[order[state->have++]] = (unsigned short)BITS(3);
-                DROPBITS(3);
-            }
-            while (state->have < 19)
-                state->lens[order[state->have++]] = 0;
-            state->next = state->codes;
-            state->lencode = (const code FAR *)(state->next);
-            state->lenbits = 7;
-            ret = inflate_table(CODES, state->lens, 19, &(state->next),
-                                &(state->lenbits), state->work);
-            if (ret) {
-                strm->msg = (char *)"invalid code lengths set";
-                state->mode = BAD;
-                break;
-            }
-            Tracev((stderr, "inflate:       code lengths ok\n"));
-            state->have = 0;
-            state->mode = CODELENS;
-        case CODELENS:
-            while (state->have < state->nlen + state->ndist) {
-                for (;;) {
-                    here = state->lencode[BITS(state->lenbits)];
-                    if ((unsigned)(here.bits) <= bits) break;
-                    PULLBYTE();
-                }
-                if (here.val < 16) {
-                    DROPBITS(here.bits);
-                    state->lens[state->have++] = here.val;
-                }
-                else {
-                    if (here.val == 16) {
-                        NEEDBITS(here.bits + 2);
-                        DROPBITS(here.bits);
-                        if (state->have == 0) {
-                            strm->msg = (char *)"invalid bit length repeat";
-                            state->mode = BAD;
-                            break;
-                        }
-                        len = state->lens[state->have - 1];
-                        copy = 3 + BITS(2);
-                        DROPBITS(2);
-                    }
-                    else if (here.val == 17) {
-                        NEEDBITS(here.bits + 3);
-                        DROPBITS(here.bits);
-                        len = 0;
-                        copy = 3 + BITS(3);
-                        DROPBITS(3);
-                    }
-                    else {
-                        NEEDBITS(here.bits + 7);
-                        DROPBITS(here.bits);
-                        len = 0;
-                        copy = 11 + BITS(7);
-                        DROPBITS(7);
-                    }
-                    if (state->have + copy > state->nlen + state->ndist) {
-                        strm->msg = (char *)"invalid bit length repeat";
-                        state->mode = BAD;
-                        break;
-                    }
-                    while (copy--)
-                        state->lens[state->have++] = (unsigned short)len;
-                }
-            }
-
-            /* handle error breaks in while */
-            if (state->mode == BAD) break;
-
-            /* check for end-of-block code (better have one) */
-            if (state->lens[256] == 0) {
-                strm->msg = (char *)"invalid code -- missing end-of-block";
-                state->mode = BAD;
-                break;
-            }
-
-            /* build code tables -- note: do not change the lenbits or distbits
-               values here (9 and 6) without reading the comments in inftrees.h
-               concerning the ENOUGH constants, which depend on those values */
-            state->next = state->codes;
-            state->lencode = (const code FAR *)(state->next);
-            state->lenbits = 9;
-            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
-                                &(state->lenbits), state->work);
-            if (ret) {
-                strm->msg = (char *)"invalid literal/lengths set";
-                state->mode = BAD;
-                break;
-            }
-            state->distcode = (const code FAR *)(state->next);
-            state->distbits = 6;
-            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
-                            &(state->next), &(state->distbits), state->work);
-            if (ret) {
-                strm->msg = (char *)"invalid distances set";
-                state->mode = BAD;
-                break;
-            }
-            Tracev((stderr, "inflate:       codes ok\n"));
-            state->mode = LEN_;
-            if (flush == Z_TREES) goto inf_leave;
-        case LEN_:
-            state->mode = LEN;
-        case LEN:
-            if (have >= 6 && left >= 258) {
-                RESTORE();
-                inflate_fast(strm, out);
-                LOAD();
-                if (state->mode == TYPE)
-                    state->back = -1;
-                break;
-            }
-            state->back = 0;
-            for (;;) {
-                here = state->lencode[BITS(state->lenbits)];
-                if ((unsigned)(here.bits) <= bits) break;
-                PULLBYTE();
-            }
-            if (here.op && (here.op & 0xf0) == 0) {
-                last = here;
-                for (;;) {
-                    here = state->lencode[last.val +
-                            (BITS(last.bits + last.op) >> last.bits)];
-                    if ((unsigned)(last.bits + here.bits) <= bits) break;
-                    PULLBYTE();
-                }
-                DROPBITS(last.bits);
-                state->back += last.bits;
-            }
-            DROPBITS(here.bits);
-            state->back += here.bits;
-            state->length = (unsigned)here.val;
-            if ((int)(here.op) == 0) {
-                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
-                        "inflate:         literal '%c'\n" :
-                        "inflate:         literal 0x%02x\n", here.val));
-                state->mode = LIT;
-                break;
-            }
-            if (here.op & 32) {
-                Tracevv((stderr, "inflate:         end of block\n"));
-                state->back = -1;
-                state->mode = TYPE;
-                break;
-            }
-            if (here.op & 64) {
-                strm->msg = (char *)"invalid literal/length code";
-                state->mode = BAD;
-                break;
-            }
-            state->extra = (unsigned)(here.op) & 15;
-            state->mode = LENEXT;
-        case LENEXT:
-            if (state->extra) {
-                NEEDBITS(state->extra);
-                state->length += BITS(state->extra);
-                DROPBITS(state->extra);
-                state->back += state->extra;
-            }
-            Tracevv((stderr, "inflate:         length %u\n", state->length));
-            state->was = state->length;
-            state->mode = DIST;
-        case DIST:
-            for (;;) {
-                here = state->distcode[BITS(state->distbits)];
-                if ((unsigned)(here.bits) <= bits) break;
-                PULLBYTE();
-            }
-            if ((here.op & 0xf0) == 0) {
-                last = here;
-                for (;;) {
-                    here = state->distcode[last.val +
-                            (BITS(last.bits + last.op) >> last.bits)];
-                    if ((unsigned)(last.bits + here.bits) <= bits) break;
-                    PULLBYTE();
-                }
-                DROPBITS(last.bits);
-                state->back += last.bits;
-            }
-            DROPBITS(here.bits);
-            state->back += here.bits;
-            if (here.op & 64) {
-                strm->msg = (char *)"invalid distance code";
-                state->mode = BAD;
-                break;
-            }
-            state->offset = (unsigned)here.val;
-            state->extra = (unsigned)(here.op) & 15;
-            state->mode = DISTEXT;
-        case DISTEXT:
-            if (state->extra) {
-                NEEDBITS(state->extra);
-                state->offset += BITS(state->extra);
-                DROPBITS(state->extra);
-                state->back += state->extra;
-            }
-#ifdef INFLATE_STRICT
-            if (state->offset > state->dmax) {
-                strm->msg = (char *)"invalid distance too far back";
-                state->mode = BAD;
-                break;
-            }
-#endif
-            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
-            state->mode = MATCH;
-        case MATCH:
-            if (left == 0) goto inf_leave;
-            copy = out - left;
-            if (state->offset > copy) {         /* copy from window */
-                copy = state->offset - copy;
-                if (copy > state->whave) {
-                    if (state->sane) {
-                        strm->msg = (char *)"invalid distance too far back";
-                        state->mode = BAD;
-                        break;
-                    }
-#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
-                    Trace((stderr, "inflate.c too far\n"));
-                    copy -= state->whave;
-                    if (copy > state->length) copy = state->length;
-                    if (copy > left) copy = left;
-                    left -= copy;
-                    state->length -= copy;
-                    do {
-                        *put++ = 0;
-                    } while (--copy);
-                    if (state->length == 0) state->mode = LEN;
-                    break;
-#endif
-                }
-                if (copy > state->wnext) {
-                    copy -= state->wnext;
-                    from = state->window + (state->wsize - copy);
-                }
-                else
-                    from = state->window + (state->wnext - copy);
-                if (copy > state->length) copy = state->length;
-            }
-            else {                              /* copy from output */
-                from = put - state->offset;
-                copy = state->length;
-            }
-            if (copy > left) copy = left;
-            left -= copy;
-            state->length -= copy;
-            do {
-                *put++ = *from++;
-            } while (--copy);
-            if (state->length == 0) state->mode = LEN;
-            break;
-        case LIT:
-            if (left == 0) goto inf_leave;
-            *put++ = (unsigned char)(state->length);
-            left--;
-            state->mode = LEN;
-            break;
-        case CHECK:
-            if (state->wrap) {
-                NEEDBITS(32);
-                out -= left;
-                strm->total_out += out;
-                state->total += out;
-                if (out)
-                    strm->adler = state->check =
-                        UPDATE(state->check, put - out, out);
-                out = left;
-                if ((
-#ifdef GUNZIP
-                     state->flags ? hold :
-#endif
-                     ZSWAP32(hold)) != state->check) {
-                    strm->msg = (char *)"incorrect data check";
-                    state->mode = BAD;
-                    break;
-                }
-                INITBITS();
-                Tracev((stderr, "inflate:   check matches trailer\n"));
-            }
-#ifdef GUNZIP
-            state->mode = LENGTH;
-        case LENGTH:
-            if (state->wrap && state->flags) {
-                NEEDBITS(32);
-                if (hold != (state->total & 0xffffffffUL)) {
-                    strm->msg = (char *)"incorrect length check";
-                    state->mode = BAD;
-                    break;
-                }
-                INITBITS();
-                Tracev((stderr, "inflate:   length matches trailer\n"));
-            }
-#endif
-            state->mode = DONE;
-        case DONE:
-            ret = Z_STREAM_END;
-            goto inf_leave;
-        case BAD:
-            ret = Z_DATA_ERROR;
-            goto inf_leave;
-        case MEM:
-            return Z_MEM_ERROR;
-        case SYNC:
-        default:
-            return Z_STREAM_ERROR;
-        }
-
-    /*
-       Return from inflate(), updating the total counts and the check value.
-       If there was no progress during the inflate() call, return a buffer
-       error.  Call updatewindow() to create and/or update the window state.
-       Note: a memory error from inflate() is non-recoverable.
-     */
-  inf_leave:
-    RESTORE();
-    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&
-            (state->mode < CHECK || flush != Z_FINISH)))
-        if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {
-            state->mode = MEM;
-            return Z_MEM_ERROR;
-        }
-    in -= strm->avail_in;
-    out -= strm->avail_out;
-    strm->total_in += in;
-    strm->total_out += out;
-    state->total += out;
-    if (state->wrap && out)
-        strm->adler = state->check =
-            UPDATE(state->check, strm->next_out - out, out);
-    strm->data_type = state->bits + (state->last ? 64 : 0) +
-                      (state->mode == TYPE ? 128 : 0) +
-                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
-    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
-        ret = Z_BUF_ERROR;
-    return ret;
-}
-
-int ZEXPORT inflateEnd(strm)
-z_streamp strm;
-{
-    struct inflate_state FAR *state;
-    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
-        return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)strm->state;
-    if (state->window != Z_NULL) ZFREE(strm, state->window);
-    ZFREE(strm, strm->state);
-    strm->state = Z_NULL;
-    Tracev((stderr, "inflate: end\n"));
-    return Z_OK;
-}
-
-int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength)
-z_streamp strm;
-Bytef *dictionary;
-uInt *dictLength;
-{
-    struct inflate_state FAR *state;
-
-    /* check state */
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)strm->state;
-
-    /* copy dictionary */
-    if (state->whave && dictionary != Z_NULL) {
-        zmemcpy(dictionary, state->window + state->wnext,
-                state->whave - state->wnext);
-        zmemcpy(dictionary + state->whave - state->wnext,
-                state->window, state->wnext);
-    }
-    if (dictLength != Z_NULL)
-        *dictLength = state->whave;
-    return Z_OK;
-}
-
-int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
-z_streamp strm;
-const Bytef *dictionary;
-uInt dictLength;
-{
-    struct inflate_state FAR *state;
-    unsigned long dictid;
-    int ret;
-
-    /* check state */
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)strm->state;
-    if (state->wrap != 0 && state->mode != DICT)
-        return Z_STREAM_ERROR;
-
-    /* check for correct dictionary identifier */
-    if (state->mode == DICT) {
-        dictid = adler32(0L, Z_NULL, 0);
-        dictid = adler32(dictid, dictionary, dictLength);
-        if (dictid != state->check)
-            return Z_DATA_ERROR;
-    }
-
-    /* copy dictionary to window using updatewindow(), which will amend the
-       existing dictionary if appropriate */
-    ret = updatewindow(strm, dictionary + dictLength, dictLength);
-    if (ret) {
-        state->mode = MEM;
-        return Z_MEM_ERROR;
-    }
-    state->havedict = 1;
-    Tracev((stderr, "inflate:   dictionary set\n"));
-    return Z_OK;
-}
-
-int ZEXPORT inflateGetHeader(strm, head)
-z_streamp strm;
-gz_headerp head;
-{
-    struct inflate_state FAR *state;
-
-    /* check state */
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)strm->state;
-    if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
-
-    /* save header structure */
-    state->head = head;
-    head->done = 0;
-    return Z_OK;
-}
-
-/*
-   Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
-   or when out of input.  When called, *have is the number of pattern bytes
-   found in order so far, in 0..3.  On return *have is updated to the new
-   state.  If on return *have equals four, then the pattern was found and the
-   return value is how many bytes were read including the last byte of the
-   pattern.  If *have is less than four, then the pattern has not been found
-   yet and the return value is len.  In the latter case, syncsearch() can be
-   called again with more data and the *have state.  *have is initialized to
-   zero for the first call.
- */
-local unsigned syncsearch(have, buf, len)
-unsigned FAR *have;
-const unsigned char FAR *buf;
-unsigned len;
-{
-    unsigned got;
-    unsigned next;
-
-    got = *have;
-    next = 0;
-    while (next < len && got < 4) {
-        if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
-            got++;
-        else if (buf[next])
-            got = 0;
-        else
-            got = 4 - got;
-        next++;
-    }
-    *have = got;
-    return next;
-}
-
-int ZEXPORT inflateSync(strm)
-z_streamp strm;
-{
-    unsigned len;               /* number of bytes to look at or looked at */
-    unsigned long in, out;      /* temporary to save total_in and total_out */
-    unsigned char buf[4];       /* to restore bit buffer to byte string */
-    struct inflate_state FAR *state;
-
-    /* check parameters */
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)strm->state;
-    if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
-
-    /* if first time, start search in bit buffer */
-    if (state->mode != SYNC) {
-        state->mode = SYNC;
-        state->hold <<= state->bits & 7;
-        state->bits -= state->bits & 7;
-        len = 0;
-        while (state->bits >= 8) {
-            buf[len++] = (unsigned char)(state->hold);
-            state->hold >>= 8;
-            state->bits -= 8;
-        }
-        state->have = 0;
-        syncsearch(&(state->have), buf, len);
-    }
-
-    /* search available input */
-    len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
-    strm->avail_in -= len;
-    strm->next_in += len;
-    strm->total_in += len;
-
-    /* return no joy or set up to restart inflate() on a new block */
-    if (state->have != 4) return Z_DATA_ERROR;
-    in = strm->total_in;  out = strm->total_out;
-    inflateReset(strm);
-    strm->total_in = in;  strm->total_out = out;
-    state->mode = TYPE;
-    return Z_OK;
-}
-
-/*
-   Returns true if inflate is currently at the end of a block generated by
-   Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
-   implementation to provide an additional safety check. PPP uses
-   Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
-   block. When decompressing, PPP checks that at the end of input packet,
-   inflate is waiting for these length bytes.
- */
-int ZEXPORT inflateSyncPoint(strm)
-z_streamp strm;
-{
-    struct inflate_state FAR *state;
-
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)strm->state;
-    return state->mode == STORED && state->bits == 0;
-}
-
-int ZEXPORT inflateCopy(dest, source)
-z_streamp dest;
-z_streamp source;
-{
-    struct inflate_state FAR *state;
-    struct inflate_state FAR *copy;
-    unsigned char FAR *window;
-    unsigned wsize;
-
-    /* check input */
-    if (dest == Z_NULL || source == Z_NULL || source->state == Z_NULL ||
-        source->zalloc == (alloc_func)0 || source->zfree == (free_func)0)
-        return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)source->state;
-
-    /* allocate space */
-    copy = (struct inflate_state FAR *)
-           ZALLOC(source, 1, sizeof(struct inflate_state));
-    if (copy == Z_NULL) return Z_MEM_ERROR;
-    window = Z_NULL;
-    if (state->window != Z_NULL) {
-        window = (unsigned char FAR *)
-                 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
-        if (window == Z_NULL) {
-            ZFREE(source, copy);
-            return Z_MEM_ERROR;
-        }
-    }
-
-    /* copy state */
-    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
-    zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));
-    if (state->lencode >= state->codes &&
-        state->lencode <= state->codes + ENOUGH - 1) {
-        copy->lencode = copy->codes + (state->lencode - state->codes);
-        copy->distcode = copy->codes + (state->distcode - state->codes);
-    }
-    copy->next = copy->codes + (state->next - state->codes);
-    if (window != Z_NULL) {
-        wsize = 1U << state->wbits;
-        zmemcpy(window, state->window, wsize);
-    }
-    copy->window = window;
-    dest->state = (struct internal_state FAR *)copy;
-    return Z_OK;
-}
-
-int ZEXPORT inflateUndermine(strm, subvert)
-z_streamp strm;
-int subvert;
-{
-    struct inflate_state FAR *state;
-
-    if (strm == Z_NULL || strm->state == Z_NULL) return Z_STREAM_ERROR;
-    state = (struct inflate_state FAR *)strm->state;
-    state->sane = !subvert;
-#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
-    return Z_OK;
-#else
-    state->sane = 1;
-    return Z_DATA_ERROR;
-#endif
-}
-
-long ZEXPORT inflateMark(strm)
-z_streamp strm;
-{
-    struct inflate_state FAR *state;
-
-    if (strm == Z_NULL || strm->state == Z_NULL) return -1L << 16;
-    state = (struct inflate_state FAR *)strm->state;
-    return ((long)(state->back) << 16) +
-        (state->mode == COPY ? state->length :
-            (state->mode == MATCH ? state->was - state->length : 0));
-}
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/inflate.h	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,146 +0,0 @@
-/*
- * 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.
- */
-
-/* inflate.h -- internal inflate state definition
- * Copyright (C) 1995-2009 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/* WARNING: this file should *not* be used by applications. It is
-   part of the implementation of the compression library and is
-   subject to change. Applications should only use zlib.h.
- */
-
-/* define NO_GZIP when compiling if you want to disable gzip header and
-   trailer decoding by inflate().  NO_GZIP would be used to avoid linking in
-   the crc code when it is not needed.  For shared libraries, gzip decoding
-   should be left enabled. */
-#ifndef NO_GZIP
-#  define GUNZIP
-#endif
-
-/* Possible inflate modes between inflate() calls */
-typedef enum {
-    HEAD,       /* i: waiting for magic header */
-    FLAGS,      /* i: waiting for method and flags (gzip) */
-    TIME,       /* i: waiting for modification time (gzip) */
-    OS,         /* i: waiting for extra flags and operating system (gzip) */
-    EXLEN,      /* i: waiting for extra length (gzip) */
-    EXTRA,      /* i: waiting for extra bytes (gzip) */
-    NAME,       /* i: waiting for end of file name (gzip) */
-    COMMENT,    /* i: waiting for end of comment (gzip) */
-    HCRC,       /* i: waiting for header crc (gzip) */
-    DICTID,     /* i: waiting for dictionary check value */
-    DICT,       /* waiting for inflateSetDictionary() call */
-        TYPE,       /* i: waiting for type bits, including last-flag bit */
-        TYPEDO,     /* i: same, but skip check to exit inflate on new block */
-        STORED,     /* i: waiting for stored size (length and complement) */
-        COPY_,      /* i/o: same as COPY below, but only first time in */
-        COPY,       /* i/o: waiting for input or output to copy stored block */
-        TABLE,      /* i: waiting for dynamic block table lengths */
-        LENLENS,    /* i: waiting for code length code lengths */
-        CODELENS,   /* i: waiting for length/lit and distance code lengths */
-            LEN_,       /* i: same as LEN below, but only first time in */
-            LEN,        /* i: waiting for length/lit/eob code */
-            LENEXT,     /* i: waiting for length extra bits */
-            DIST,       /* i: waiting for distance code */
-            DISTEXT,    /* i: waiting for distance extra bits */
-            MATCH,      /* o: waiting for output space to copy string */
-            LIT,        /* o: waiting for output space to write literal */
-    CHECK,      /* i: waiting for 32-bit check value */
-    LENGTH,     /* i: waiting for 32-bit length (gzip) */
-    DONE,       /* finished check, done -- remain here until reset */
-    BAD,        /* got a data error -- remain here until reset */
-    MEM,        /* got an inflate() memory error -- remain here until reset */
-    SYNC        /* looking for synchronization bytes to restart inflate() */
-} inflate_mode;
-
-/*
-    State transitions between above modes -
-
-    (most modes can go to BAD or MEM on error -- not shown for clarity)
-
-    Process header:
-        HEAD -> (gzip) or (zlib) or (raw)
-        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
-                  HCRC -> TYPE
-        (zlib) -> DICTID or TYPE
-        DICTID -> DICT -> TYPE
-        (raw) -> TYPEDO
-    Read deflate blocks:
-            TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
-            STORED -> COPY_ -> COPY -> TYPE
-            TABLE -> LENLENS -> CODELENS -> LEN_
-            LEN_ -> LEN
-    Read deflate codes in fixed or dynamic block:
-                LEN -> LENEXT or LIT or TYPE
-                LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
-                LIT -> LEN
-    Process trailer:
-        CHECK -> LENGTH -> DONE
- */
-
-/* state maintained between inflate() calls.  Approximately 10K bytes. */
-struct inflate_state {
-    inflate_mode mode;          /* current inflate mode */
-    int last;                   /* true if processing last block */
-    int wrap;                   /* bit 0 true for zlib, bit 1 true for gzip */
-    int havedict;               /* true if dictionary provided */
-    int flags;                  /* gzip header method and flags (0 if zlib) */
-    unsigned dmax;              /* zlib header max distance (INFLATE_STRICT) */
-    unsigned long check;        /* protected copy of check value */
-    unsigned long total;        /* protected copy of output count */
-    gz_headerp head;            /* where to save gzip header information */
-        /* sliding window */
-    unsigned wbits;             /* log base 2 of requested window size */
-    unsigned wsize;             /* window size or zero if not using window */
-    unsigned whave;             /* valid bytes in the window */
-    unsigned wnext;             /* window write index */
-    unsigned char FAR *window;  /* allocated sliding window, if needed */
-        /* bit accumulator */
-    unsigned long hold;         /* input bit accumulator */
-    unsigned bits;              /* number of bits in "in" */
-        /* for string and stored block copying */
-    unsigned length;            /* literal or length of data to copy */
-    unsigned offset;            /* distance back to copy string from */
-        /* for table and code decoding */
-    unsigned extra;             /* extra bits needed */
-        /* fixed and dynamic code tables */
-    code const FAR *lencode;    /* starting table for length/literal codes */
-    code const FAR *distcode;   /* starting table for distance codes */
-    unsigned lenbits;           /* index bits for lencode */
-    unsigned distbits;          /* index bits for distcode */
-        /* dynamic table building */
-    unsigned ncode;             /* number of code length code lengths */
-    unsigned nlen;              /* number of length code lengths */
-    unsigned ndist;             /* number of distance code lengths */
-    unsigned have;              /* number of code lengths in lens[] */
-    code FAR *next;             /* next available space in codes[] */
-    unsigned short lens[320];   /* temporary storage for code lengths */
-    unsigned short work[288];   /* work area for code table building */
-    code codes[ENOUGH];         /* space for code tables */
-    int sane;                   /* if false, allow invalid distance too far */
-    int back;                   /* bits back of last unprocessed length/lit */
-    unsigned was;               /* initial length of match */
-};
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/inftrees.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,330 +0,0 @@
-/*
- * 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.
- */
-
-/* inftrees.c -- generate Huffman trees for efficient decoding
- * Copyright (C) 1995-2013 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-#include "zutil.h"
-#include "inftrees.h"
-
-#define MAXBITS 15
-
-const char inflate_copyright[] =
-   " inflate 1.2.8 Copyright 1995-2013 Mark Adler ";
-/*
-  If you use the zlib library in a product, an acknowledgment is welcome
-  in the documentation of your product. If for some reason you cannot
-  include such an acknowledgment, I would appreciate that you keep this
-  copyright string in the executable of your product.
- */
-
-/*
-   Build a set of tables to decode the provided canonical Huffman code.
-   The code lengths are lens[0..codes-1].  The result starts at *table,
-   whose indices are 0..2^bits-1.  work is a writable array of at least
-   lens shorts, which is used as a work area.  type is the type of code
-   to be generated, CODES, LENS, or DISTS.  On return, zero is success,
-   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
-   on return points to the next available entry's address.  bits is the
-   requested root table index bits, and on return it is the actual root
-   table index bits.  It will differ if the request is greater than the
-   longest code or if it is less than the shortest code.
- */
-int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)
-codetype type;
-unsigned short FAR *lens;
-unsigned codes;
-code FAR * FAR *table;
-unsigned FAR *bits;
-unsigned short FAR *work;
-{
-    unsigned len;               /* a code's length in bits */
-    unsigned sym;               /* index of code symbols */
-    unsigned min, max;          /* minimum and maximum code lengths */
-    unsigned root;              /* number of index bits for root table */
-    unsigned curr;              /* number of index bits for current table */
-    unsigned drop;              /* code bits to drop for sub-table */
-    int left;                   /* number of prefix codes available */
-    unsigned used;              /* code entries in table used */
-    unsigned huff;              /* Huffman code */
-    unsigned incr;              /* for incrementing code, index */
-    unsigned fill;              /* index for replicating entries */
-    unsigned low;               /* low bits for current root entry */
-    unsigned mask;              /* mask for low root bits */
-    code here;                  /* table entry for duplication */
-    code FAR *next;             /* next available space in table */
-    const unsigned short FAR *base;     /* base value table to use */
-    const unsigned short FAR *extra;    /* extra bits table to use */
-    int end;                    /* use base and extra for symbol > end */
-    unsigned short count[MAXBITS+1];    /* number of codes of each length */
-    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
-    static const unsigned short lbase[31] = { /* Length codes 257..285 base */
-        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
-        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
-    static const unsigned short lext[31] = { /* Length codes 257..285 extra */
-        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
-        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78};
-    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
-        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
-        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
-        8193, 12289, 16385, 24577, 0, 0};
-    static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
-        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
-        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
-        28, 28, 29, 29, 64, 64};
-
-    /*
-       Process a set of code lengths to create a canonical Huffman code.  The
-       code lengths are lens[0..codes-1].  Each length corresponds to the
-       symbols 0..codes-1.  The Huffman code is generated by first sorting the
-       symbols by length from short to long, and retaining the symbol order
-       for codes with equal lengths.  Then the code starts with all zero bits
-       for the first code of the shortest length, and the codes are integer
-       increments for the same length, and zeros are appended as the length
-       increases.  For the deflate format, these bits are stored backwards
-       from their more natural integer increment ordering, and so when the
-       decoding tables are built in the large loop below, the integer codes
-       are incremented backwards.
-
-       This routine assumes, but does not check, that all of the entries in
-       lens[] are in the range 0..MAXBITS.  The caller must assure this.
-       1..MAXBITS is interpreted as that code length.  zero means that that
-       symbol does not occur in this code.
-
-       The codes are sorted by computing a count of codes for each length,
-       creating from that a table of starting indices for each length in the
-       sorted table, and then entering the symbols in order in the sorted
-       table.  The sorted table is work[], with that space being provided by
-       the caller.
-
-       The length counts are used for other purposes as well, i.e. finding
-       the minimum and maximum length codes, determining if there are any
-       codes at all, checking for a valid set of lengths, and looking ahead
-       at length counts to determine sub-table sizes when building the
-       decoding tables.
-     */
-
-    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
-    for (len = 0; len <= MAXBITS; len++)
-        count[len] = 0;
-    for (sym = 0; sym < codes; sym++)
-        count[lens[sym]]++;
-
-    /* bound code lengths, force root to be within code lengths */
-    root = *bits;
-    for (max = MAXBITS; max >= 1; max--)
-        if (count[max] != 0) break;
-    if (root > max) root = max;
-    if (max == 0) {                     /* no symbols to code at all */
-        here.op = (unsigned char)64;    /* invalid code marker */
-        here.bits = (unsigned char)1;
-        here.val = (unsigned short)0;
-        *(*table)++ = here;             /* make a table to force an error */
-        *(*table)++ = here;
-        *bits = 1;
-        return 0;     /* no symbols, but wait for decoding to report error */
-    }
-    for (min = 1; min < max; min++)
-        if (count[min] != 0) break;
-    if (root < min) root = min;
-
-    /* check for an over-subscribed or incomplete set of lengths */
-    left = 1;
-    for (len = 1; len <= MAXBITS; len++) {
-        left <<= 1;
-        left -= count[len];
-        if (left < 0) return -1;        /* over-subscribed */
-    }
-    if (left > 0 && (type == CODES || max != 1))
-        return -1;                      /* incomplete set */
-
-    /* generate offsets into symbol table for each length for sorting */
-    offs[1] = 0;
-    for (len = 1; len < MAXBITS; len++)
-        offs[len + 1] = offs[len] + count[len];
-
-    /* sort symbols by length, by symbol order within each length */
-    for (sym = 0; sym < codes; sym++)
-        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
-
-    /*
-       Create and fill in decoding tables.  In this loop, the table being
-       filled is at next and has curr index bits.  The code being used is huff
-       with length len.  That code is converted to an index by dropping drop
-       bits off of the bottom.  For codes where len is less than drop + curr,
-       those top drop + curr - len bits are incremented through all values to
-       fill the table with replicated entries.
-
-       root is the number of index bits for the root table.  When len exceeds
-       root, sub-tables are created pointed to by the root entry with an index
-       of the low root bits of huff.  This is saved in low to check for when a
-       new sub-table should be started.  drop is zero when the root table is
-       being filled, and drop is root when sub-tables are being filled.
-
-       When a new sub-table is needed, it is necessary to look ahead in the
-       code lengths to determine what size sub-table is needed.  The length
-       counts are used for this, and so count[] is decremented as codes are
-       entered in the tables.
-
-       used keeps track of how many table entries have been allocated from the
-       provided *table space.  It is checked for LENS and DIST tables against
-       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
-       the initial root table size constants.  See the comments in inftrees.h
-       for more information.
-
-       sym increments through all symbols, and the loop terminates when
-       all codes of length max, i.e. all codes, have been processed.  This
-       routine permits incomplete codes, so another loop after this one fills
-       in the rest of the decoding tables with invalid code markers.
-     */
-
-    /* set up for code type */
-    switch (type) {
-    case CODES:
-        base = extra = work;    /* dummy value--not used */
-        end = 19;
-        break;
-    case LENS:
-        base = lbase;
-        base -= 257;
-        extra = lext;
-        extra -= 257;
-        end = 256;
-        break;
-    default:            /* DISTS */
-        base = dbase;
-        extra = dext;
-        end = -1;
-    }
-
-    /* initialize state for loop */
-    huff = 0;                   /* starting code */
-    sym = 0;                    /* starting code symbol */
-    len = min;                  /* starting code length */
-    next = *table;              /* current table to fill in */
-    curr = root;                /* current table index bits */
-    drop = 0;                   /* current bits to drop from code for index */
-    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
-    used = 1U << root;          /* use root table entries */
-    mask = used - 1;            /* mask for comparing low */
-
-    /* check available table space */
-    if ((type == LENS && used > ENOUGH_LENS) ||
-        (type == DISTS && used > ENOUGH_DISTS))
-        return 1;
-
-    /* process all codes and make table entries */
-    for (;;) {
-        /* create table entry */
-        here.bits = (unsigned char)(len - drop);
-        if ((int)(work[sym]) < end) {
-            here.op = (unsigned char)0;
-            here.val = work[sym];
-        }
-        else if ((int)(work[sym]) > end) {
-            here.op = (unsigned char)(extra[work[sym]]);
-            here.val = base[work[sym]];
-        }
-        else {
-            here.op = (unsigned char)(32 + 64);         /* end of block */
-            here.val = 0;
-        }
-
-        /* replicate for those indices with low len bits equal to huff */
-        incr = 1U << (len - drop);
-        fill = 1U << curr;
-        min = fill;                 /* save offset to next table */
-        do {
-            fill -= incr;
-            next[(huff >> drop) + fill] = here;
-        } while (fill != 0);
-
-        /* backwards increment the len-bit code huff */
-        incr = 1U << (len - 1);
-        while (huff & incr)
-            incr >>= 1;
-        if (incr != 0) {
-            huff &= incr - 1;
-            huff += incr;
-        }
-        else
-            huff = 0;
-
-        /* go to next symbol, update count, len */
-        sym++;
-        if (--(count[len]) == 0) {
-            if (len == max) break;
-            len = lens[work[sym]];
-        }
-
-        /* create new sub-table if needed */
-        if (len > root && (huff & mask) != low) {
-            /* if first time, transition to sub-tables */
-            if (drop == 0)
-                drop = root;
-
-            /* increment past last table */
-            next += min;            /* here min is 1 << curr */
-
-            /* determine length of next table */
-            curr = len - drop;
-            left = (int)(1 << curr);
-            while (curr + drop < max) {
-                left -= count[curr + drop];
-                if (left <= 0) break;
-                curr++;
-                left <<= 1;
-            }
-
-            /* check for enough space */
-            used += 1U << curr;
-            if ((type == LENS && used > ENOUGH_LENS) ||
-                (type == DISTS && used > ENOUGH_DISTS))
-                return 1;
-
-            /* point entry in root table to sub-table */
-            low = huff & mask;
-            (*table)[low].op = (unsigned char)curr;
-            (*table)[low].bits = (unsigned char)root;
-            (*table)[low].val = (unsigned short)(next - *table);
-        }
-    }
-
-    /* fill in remaining table entry if code is incomplete (guaranteed to have
-       at most one remaining entry, since if the code is incomplete, the
-       maximum code length that was allowed to get this far is one bit) */
-    if (huff != 0) {
-        here.op = (unsigned char)64;            /* invalid code marker */
-        here.bits = (unsigned char)(len - drop);
-        here.val = (unsigned short)0;
-        next[huff] = here;
-    }
-
-    /* set return parameters */
-    *table += used;
-    *bits = root;
-    return 0;
-}
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/inftrees.h	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,86 +0,0 @@
-/*
- * 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.
- */
-
-/* inftrees.h -- header to use inftrees.c
- * Copyright (C) 1995-2005, 2010 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/* WARNING: this file should *not* be used by applications. It is
-   part of the implementation of the compression library and is
-   subject to change. Applications should only use zlib.h.
- */
-
-/* Structure for decoding tables.  Each entry provides either the
-   information needed to do the operation requested by the code that
-   indexed that table entry, or it provides a pointer to another
-   table that indexes more bits of the code.  op indicates whether
-   the entry is a pointer to another table, a literal, a length or
-   distance, an end-of-block, or an invalid code.  For a table
-   pointer, the low four bits of op is the number of index bits of
-   that table.  For a length or distance, the low four bits of op
-   is the number of extra bits to get after the code.  bits is
-   the number of bits in this code or part of the code to drop off
-   of the bit buffer.  val is the actual byte to output in the case
-   of a literal, the base length or distance, or the offset from
-   the current table to the next table.  Each entry is four bytes. */
-typedef struct {
-    unsigned char op;           /* operation, extra bits, table bits */
-    unsigned char bits;         /* bits in this part of the code */
-    unsigned short val;         /* offset in table or code value */
-} code;
-
-/* op values as set by inflate_table():
-    00000000 - literal
-    0000tttt - table link, tttt != 0 is the number of table index bits
-    0001eeee - length or distance, eeee is the number of extra bits
-    01100000 - end of block
-    01000000 - invalid code
- */
-
-/* Maximum size of the dynamic table.  The maximum number of code structures is
-   1444, which is the sum of 852 for literal/length codes and 592 for distance
-   codes.  These values were found by exhaustive searches using the program
-   examples/enough.c found in the zlib distribtution.  The arguments to that
-   program are the number of symbols, the initial root table size, and the
-   maximum bit length of a code.  "enough 286 9 15" for literal/length codes
-   returns returns 852, and "enough 30 6 15" for distance codes returns 592.
-   The initial root table size (9 or 6) is found in the fifth argument of the
-   inflate_table() calls in inflate.c and infback.c.  If the root table size is
-   changed, then these maximum sizes would be need to be recalculated and
-   updated. */
-#define ENOUGH_LENS 852
-#define ENOUGH_DISTS 592
-#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
-
-/* Type of code to build for inflate_table() */
-typedef enum {
-    CODES,
-    LENS,
-    DISTS
-} codetype;
-
-int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,
-                             unsigned codes, code FAR * FAR *table,
-                             unsigned FAR *bits, unsigned short FAR *work));
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/patches/ChangeLog_java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-(1)renamed
-   adler32.c -> zadler32.c
-   zcrc32c -> zcrc32.c
-
-(2)added _LP64 to make uLong a 32-bit int on 64-bit platform
-   zconf.h:
-   uLong -> 32-bit int
-
-(3)updated crc32.c/crc32()
-   unsigned long      -> uLong
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/trees.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1250 +0,0 @@
-/*
- * 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.
- */
-
-/* trees.c -- output deflated data using Huffman coding
- * Copyright (C) 1995-2012 Jean-loup Gailly
- * detect_data_type() function provided freely by Cosmin Truta, 2006
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/*
- *  ALGORITHM
- *
- *      The "deflation" process uses several Huffman trees. The more
- *      common source values are represented by shorter bit sequences.
- *
- *      Each code tree is stored in a compressed form which is itself
- * a Huffman encoding of the lengths of all the code strings (in
- * ascending order by source values).  The actual code strings are
- * reconstructed from the lengths in the inflate process, as described
- * in the deflate specification.
- *
- *  REFERENCES
- *
- *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
- *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
- *
- *      Storer, James A.
- *          Data Compression:  Methods and Theory, pp. 49-50.
- *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
- *
- *      Sedgewick, R.
- *          Algorithms, p290.
- *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
- */
-
-/* @(#) $Id$ */
-
-/* #define GEN_TREES_H */
-
-#include "deflate.h"
-
-#ifdef DEBUG
-#  include <ctype.h>
-#endif
-
-/* ===========================================================================
- * Constants
- */
-
-#define MAX_BL_BITS 7
-/* Bit length codes must not exceed MAX_BL_BITS bits */
-
-#define END_BLOCK 256
-/* end of block literal code */
-
-#define REP_3_6      16
-/* repeat previous bit length 3-6 times (2 bits of repeat count) */
-
-#define REPZ_3_10    17
-/* repeat a zero length 3-10 times  (3 bits of repeat count) */
-
-#define REPZ_11_138  18
-/* repeat a zero length 11-138 times  (7 bits of repeat count) */
-
-local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
-   = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
-
-local const int extra_dbits[D_CODES] /* extra bits for each distance code */
-   = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
-
-local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
-   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
-
-local const uch bl_order[BL_CODES]
-   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
-/* The lengths of the bit length codes are sent in order of decreasing
- * probability, to avoid transmitting the lengths for unused bit length codes.
- */
-
-/* ===========================================================================
- * Local data. These are initialized only once.
- */
-
-#define DIST_CODE_LEN  512 /* see definition of array dist_code below */
-
-#if defined(GEN_TREES_H) || !defined(STDC)
-/* non ANSI compilers may not accept trees.h */
-
-local ct_data static_ltree[L_CODES+2];
-/* The static literal tree. Since the bit lengths are imposed, there is no
- * need for the L_CODES extra codes used during heap construction. However
- * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
- * below).
- */
-
-local ct_data static_dtree[D_CODES];
-/* The static distance tree. (Actually a trivial tree since all codes use
- * 5 bits.)
- */
-
-uch _dist_code[DIST_CODE_LEN];
-/* Distance codes. The first 256 values correspond to the distances
- * 3 .. 258, the last 256 values correspond to the top 8 bits of
- * the 15 bit distances.
- */
-
-uch _length_code[MAX_MATCH-MIN_MATCH+1];
-/* length code for each normalized match length (0 == MIN_MATCH) */
-
-local int base_length[LENGTH_CODES];
-/* First normalized length for each code (0 = MIN_MATCH) */
-
-local int base_dist[D_CODES];
-/* First normalized distance for each code (0 = distance of 1) */
-
-#else
-#  include "trees.h"
-#endif /* GEN_TREES_H */
-
-struct static_tree_desc_s {
-    const ct_data *static_tree;  /* static tree or NULL */
-    const intf *extra_bits;      /* extra bits for each code or NULL */
-    int     extra_base;          /* base index for extra_bits */
-    int     elems;               /* max number of elements in the tree */
-    int     max_length;          /* max bit length for the codes */
-};
-
-local static_tree_desc  static_l_desc =
-{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
-
-local static_tree_desc  static_d_desc =
-{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
-
-local static_tree_desc  static_bl_desc =
-{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
-
-/* ===========================================================================
- * Local (static) routines in this file.
- */
-
-local void tr_static_init OF((void));
-local void init_block     OF((deflate_state *s));
-local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
-local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
-local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
-local void build_tree     OF((deflate_state *s, tree_desc *desc));
-local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
-local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
-local int  build_bl_tree  OF((deflate_state *s));
-local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
-                              int blcodes));
-local void compress_block OF((deflate_state *s, const ct_data *ltree,
-                              const ct_data *dtree));
-local int  detect_data_type OF((deflate_state *s));
-local unsigned bi_reverse OF((unsigned value, int length));
-local void bi_windup      OF((deflate_state *s));
-local void bi_flush       OF((deflate_state *s));
-local void copy_block     OF((deflate_state *s, charf *buf, unsigned len,
-                              int header));
-
-#ifdef GEN_TREES_H
-local void gen_trees_header OF((void));
-#endif
-
-#ifndef DEBUG
-#  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
-   /* Send a code of the given tree. c and tree must not have side effects */
-
-#else /* DEBUG */
-#  define send_code(s, c, tree) \
-     { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
-       send_bits(s, tree[c].Code, tree[c].Len); }
-#endif
-
-/* ===========================================================================
- * Output a short LSB first on the stream.
- * IN assertion: there is enough room in pendingBuf.
- */
-#define put_short(s, w) { \
-    put_byte(s, (uch)((w) & 0xff)); \
-    put_byte(s, (uch)((ush)(w) >> 8)); \
-}
-
-/* ===========================================================================
- * Send a value on a given number of bits.
- * IN assertion: length <= 16 and value fits in length bits.
- */
-#ifdef DEBUG
-local void send_bits      OF((deflate_state *s, int value, int length));
-
-local void send_bits(s, value, length)
-    deflate_state *s;
-    int value;  /* value to send */
-    int length; /* number of bits */
-{
-    Tracevv((stderr," l %2d v %4x ", length, value));
-    Assert(length > 0 && length <= 15, "invalid length");
-    s->bits_sent += (ulg)length;
-
-    /* If not enough room in bi_buf, use (valid) bits from bi_buf and
-     * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
-     * unused bits in value.
-     */
-    if (s->bi_valid > (int)Buf_size - length) {
-        s->bi_buf |= (ush)value << s->bi_valid;
-        put_short(s, s->bi_buf);
-        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
-        s->bi_valid += length - Buf_size;
-    } else {
-        s->bi_buf |= (ush)value << s->bi_valid;
-        s->bi_valid += length;
-    }
-}
-#else /* !DEBUG */
-
-#define send_bits(s, value, length) \
-{ int len = length;\
-  if (s->bi_valid > (int)Buf_size - len) {\
-    int val = value;\
-    s->bi_buf |= (ush)val << s->bi_valid;\
-    put_short(s, s->bi_buf);\
-    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
-    s->bi_valid += len - Buf_size;\
-  } else {\
-    s->bi_buf |= (ush)(value) << s->bi_valid;\
-    s->bi_valid += len;\
-  }\
-}
-#endif /* DEBUG */
-
-
-/* the arguments must not have side effects */
-
-/* ===========================================================================
- * Initialize the various 'constant' tables.
- */
-local void tr_static_init()
-{
-#if defined(GEN_TREES_H) || !defined(STDC)
-    static int static_init_done = 0;
-    int n;        /* iterates over tree elements */
-    int bits;     /* bit counter */
-    int length;   /* length value */
-    int code;     /* code value */
-    int dist;     /* distance index */
-    ush bl_count[MAX_BITS+1];
-    /* number of codes at each bit length for an optimal tree */
-
-    if (static_init_done) return;
-
-    /* For some embedded targets, global variables are not initialized: */
-#ifdef NO_INIT_GLOBAL_POINTERS
-    static_l_desc.static_tree = static_ltree;
-    static_l_desc.extra_bits = extra_lbits;
-    static_d_desc.static_tree = static_dtree;
-    static_d_desc.extra_bits = extra_dbits;
-    static_bl_desc.extra_bits = extra_blbits;
-#endif
-
-    /* Initialize the mapping length (0..255) -> length code (0..28) */
-    length = 0;
-    for (code = 0; code < LENGTH_CODES-1; code++) {
-        base_length[code] = length;
-        for (n = 0; n < (1<<extra_lbits[code]); n++) {
-            _length_code[length++] = (uch)code;
-        }
-    }
-    Assert (length == 256, "tr_static_init: length != 256");
-    /* Note that the length 255 (match length 258) can be represented
-     * in two different ways: code 284 + 5 bits or code 285, so we
-     * overwrite length_code[255] to use the best encoding:
-     */
-    _length_code[length-1] = (uch)code;
-
-    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
-    dist = 0;
-    for (code = 0 ; code < 16; code++) {
-        base_dist[code] = dist;
-        for (n = 0; n < (1<<extra_dbits[code]); n++) {
-            _dist_code[dist++] = (uch)code;
-        }
-    }
-    Assert (dist == 256, "tr_static_init: dist != 256");
-    dist >>= 7; /* from now on, all distances are divided by 128 */
-    for ( ; code < D_CODES; code++) {
-        base_dist[code] = dist << 7;
-        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
-            _dist_code[256 + dist++] = (uch)code;
-        }
-    }
-    Assert (dist == 256, "tr_static_init: 256+dist != 512");
-
-    /* Construct the codes of the static literal tree */
-    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
-    n = 0;
-    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
-    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
-    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
-    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
-    /* Codes 286 and 287 do not exist, but we must include them in the
-     * tree construction to get a canonical Huffman tree (longest code
-     * all ones)
-     */
-    gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
-
-    /* The static distance tree is trivial: */
-    for (n = 0; n < D_CODES; n++) {
-        static_dtree[n].Len = 5;
-        static_dtree[n].Code = bi_reverse((unsigned)n, 5);
-    }
-    static_init_done = 1;
-
-#  ifdef GEN_TREES_H
-    gen_trees_header();
-#  endif
-#endif /* defined(GEN_TREES_H) || !defined(STDC) */
-}
-
-/* ===========================================================================
- * Genererate the file trees.h describing the static trees.
- */
-#ifdef GEN_TREES_H
-#  ifndef DEBUG
-#    include <stdio.h>
-#  endif
-
-#  define SEPARATOR(i, last, width) \
-      ((i) == (last)? "\n};\n\n" :    \
-       ((i) % (width) == (width)-1 ? ",\n" : ", "))
-
-void gen_trees_header()
-{
-    FILE *header = fopen("trees.h", "w");
-    int i;
-
-    Assert (header != NULL, "Can't open trees.h");
-    fprintf(header,
-            "/* header created automatically with -DGEN_TREES_H */\n\n");
-
-    fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
-    for (i = 0; i < L_CODES+2; i++) {
-        fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
-                static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
-    }
-
-    fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
-    for (i = 0; i < D_CODES; i++) {
-        fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
-                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
-    }
-
-    fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
-    for (i = 0; i < DIST_CODE_LEN; i++) {
-        fprintf(header, "%2u%s", _dist_code[i],
-                SEPARATOR(i, DIST_CODE_LEN-1, 20));
-    }
-
-    fprintf(header,
-        "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
-    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
-        fprintf(header, "%2u%s", _length_code[i],
-                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
-    }
-
-    fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
-    for (i = 0; i < LENGTH_CODES; i++) {
-        fprintf(header, "%1u%s", base_length[i],
-                SEPARATOR(i, LENGTH_CODES-1, 20));
-    }
-
-    fprintf(header, "local const int base_dist[D_CODES] = {\n");
-    for (i = 0; i < D_CODES; i++) {
-        fprintf(header, "%5u%s", base_dist[i],
-                SEPARATOR(i, D_CODES-1, 10));
-    }
-
-    fclose(header);
-}
-#endif /* GEN_TREES_H */
-
-/* ===========================================================================
- * Initialize the tree data structures for a new zlib stream.
- */
-void ZLIB_INTERNAL _tr_init(s)
-    deflate_state *s;
-{
-    tr_static_init();
-
-    s->l_desc.dyn_tree = s->dyn_ltree;
-    s->l_desc.stat_desc = &static_l_desc;
-
-    s->d_desc.dyn_tree = s->dyn_dtree;
-    s->d_desc.stat_desc = &static_d_desc;
-
-    s->bl_desc.dyn_tree = s->bl_tree;
-    s->bl_desc.stat_desc = &static_bl_desc;
-
-    s->bi_buf = 0;
-    s->bi_valid = 0;
-#ifdef DEBUG
-    s->compressed_len = 0L;
-    s->bits_sent = 0L;
-#endif
-
-    /* Initialize the first block of the first file: */
-    init_block(s);
-}
-
-/* ===========================================================================
- * Initialize a new block.
- */
-local void init_block(s)
-    deflate_state *s;
-{
-    int n; /* iterates over tree elements */
-
-    /* Initialize the trees. */
-    for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
-    for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
-    for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
-
-    s->dyn_ltree[END_BLOCK].Freq = 1;
-    s->opt_len = s->static_len = 0L;
-    s->last_lit = s->matches = 0;
-}
-
-#define SMALLEST 1
-/* Index within the heap array of least frequent node in the Huffman tree */
-
-
-/* ===========================================================================
- * Remove the smallest element from the heap and recreate the heap with
- * one less element. Updates heap and heap_len.
- */
-#define pqremove(s, tree, top) \
-{\
-    top = s->heap[SMALLEST]; \
-    s->heap[SMALLEST] = s->heap[s->heap_len--]; \
-    pqdownheap(s, tree, SMALLEST); \
-}
-
-/* ===========================================================================
- * Compares to subtrees, using the tree depth as tie breaker when
- * the subtrees have equal frequency. This minimizes the worst case length.
- */
-#define smaller(tree, n, m, depth) \
-   (tree[n].Freq < tree[m].Freq || \
-   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
-
-/* ===========================================================================
- * Restore the heap property by moving down the tree starting at node k,
- * exchanging a node with the smallest of its two sons if necessary, stopping
- * when the heap property is re-established (each father smaller than its
- * two sons).
- */
-local void pqdownheap(s, tree, k)
-    deflate_state *s;
-    ct_data *tree;  /* the tree to restore */
-    int k;               /* node to move down */
-{
-    int v = s->heap[k];
-    int j = k << 1;  /* left son of k */
-    while (j <= s->heap_len) {
-        /* Set j to the smallest of the two sons: */
-        if (j < s->heap_len &&
-            smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
-            j++;
-        }
-        /* Exit if v is smaller than both sons */
-        if (smaller(tree, v, s->heap[j], s->depth)) break;
-
-        /* Exchange v with the smallest son */
-        s->heap[k] = s->heap[j];  k = j;
-
-        /* And continue down the tree, setting j to the left son of k */
-        j <<= 1;
-    }
-    s->heap[k] = v;
-}
-
-/* ===========================================================================
- * Compute the optimal bit lengths for a tree and update the total bit length
- * for the current block.
- * IN assertion: the fields freq and dad are set, heap[heap_max] and
- *    above are the tree nodes sorted by increasing frequency.
- * OUT assertions: the field len is set to the optimal bit length, the
- *     array bl_count contains the frequencies for each bit length.
- *     The length opt_len is updated; static_len is also updated if stree is
- *     not null.
- */
-local void gen_bitlen(s, desc)
-    deflate_state *s;
-    tree_desc *desc;    /* the tree descriptor */
-{
-    ct_data *tree        = desc->dyn_tree;
-    int max_code         = desc->max_code;
-    const ct_data *stree = desc->stat_desc->static_tree;
-    const intf *extra    = desc->stat_desc->extra_bits;
-    int base             = desc->stat_desc->extra_base;
-    int max_length       = desc->stat_desc->max_length;
-    int h;              /* heap index */
-    int n, m;           /* iterate over the tree elements */
-    int bits;           /* bit length */
-    int xbits;          /* extra bits */
-    ush f;              /* frequency */
-    int overflow = 0;   /* number of elements with bit length too large */
-
-    for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
-
-    /* In a first pass, compute the optimal bit lengths (which may
-     * overflow in the case of the bit length tree).
-     */
-    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
-
-    for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
-        n = s->heap[h];
-        bits = tree[tree[n].Dad].Len + 1;
-        if (bits > max_length) bits = max_length, overflow++;
-        tree[n].Len = (ush)bits;
-        /* We overwrite tree[n].Dad which is no longer needed */
-
-        if (n > max_code) continue; /* not a leaf node */
-
-        s->bl_count[bits]++;
-        xbits = 0;
-        if (n >= base) xbits = extra[n-base];
-        f = tree[n].Freq;
-        s->opt_len += (ulg)f * (bits + xbits);
-        if (stree) s->static_len += (ulg)f * (stree[n].Len + xbits);
-    }
-    if (overflow == 0) return;
-
-    Trace((stderr,"\nbit length overflow\n"));
-    /* This happens for example on obj2 and pic of the Calgary corpus */
-
-    /* Find the first bit length which could increase: */
-    do {
-        bits = max_length-1;
-        while (s->bl_count[bits] == 0) bits--;
-        s->bl_count[bits]--;      /* move one leaf down the tree */
-        s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
-        s->bl_count[max_length]--;
-        /* The brother of the overflow item also moves one step up,
-         * but this does not affect bl_count[max_length]
-         */
-        overflow -= 2;
-    } while (overflow > 0);
-
-    /* Now recompute all bit lengths, scanning in increasing frequency.
-     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
-     * lengths instead of fixing only the wrong ones. This idea is taken
-     * from 'ar' written by Haruhiko Okumura.)
-     */
-    for (bits = max_length; bits != 0; bits--) {
-        n = s->bl_count[bits];
-        while (n != 0) {
-            m = s->heap[--h];
-            if (m > max_code) continue;
-            if ((unsigned) tree[m].Len != (unsigned) bits) {
-                Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
-                s->opt_len += ((long)bits - (long)tree[m].Len)
-                              *(long)tree[m].Freq;
-                tree[m].Len = (ush)bits;
-            }
-            n--;
-        }
-    }
-}
-
-/* ===========================================================================
- * Generate the codes for a given tree and bit counts (which need not be
- * optimal).
- * IN assertion: the array bl_count contains the bit length statistics for
- * the given tree and the field len is set for all tree elements.
- * OUT assertion: the field code is set for all tree elements of non
- *     zero code length.
- */
-local void gen_codes (tree, max_code, bl_count)
-    ct_data *tree;             /* the tree to decorate */
-    int max_code;              /* largest code with non zero frequency */
-    ushf *bl_count;            /* number of codes at each bit length */
-{
-    ush next_code[MAX_BITS+1]; /* next code value for each bit length */
-    ush code = 0;              /* running code value */
-    int bits;                  /* bit index */
-    int n;                     /* code index */
-
-    /* The distribution counts are first used to generate the code values
-     * without bit reversal.
-     */
-    for (bits = 1; bits <= MAX_BITS; bits++) {
-        next_code[bits] = code = (code + bl_count[bits-1]) << 1;
-    }
-    /* Check that the bit counts in bl_count are consistent. The last code
-     * must be all ones.
-     */
-    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
-            "inconsistent bit counts");
-    Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
-
-    for (n = 0;  n <= max_code; n++) {
-        int len = tree[n].Len;
-        if (len == 0) continue;
-        /* Now reverse the bits */
-        tree[n].Code = bi_reverse(next_code[len]++, len);
-
-        Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
-             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
-    }
-}
-
-/* ===========================================================================
- * Construct one Huffman tree and assigns the code bit strings and lengths.
- * Update the total bit length for the current block.
- * IN assertion: the field freq is set for all tree elements.
- * OUT assertions: the fields len and code are set to the optimal bit length
- *     and corresponding code. The length opt_len is updated; static_len is
- *     also updated if stree is not null. The field max_code is set.
- */
-local void build_tree(s, desc)
-    deflate_state *s;
-    tree_desc *desc; /* the tree descriptor */
-{
-    ct_data *tree         = desc->dyn_tree;
-    const ct_data *stree  = desc->stat_desc->static_tree;
-    int elems             = desc->stat_desc->elems;
-    int n, m;          /* iterate over heap elements */
-    int max_code = -1; /* largest code with non zero frequency */
-    int node;          /* new node being created */
-
-    /* Construct the initial heap, with least frequent element in
-     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
-     * heap[0] is not used.
-     */
-    s->heap_len = 0, s->heap_max = HEAP_SIZE;
-
-    for (n = 0; n < elems; n++) {
-        if (tree[n].Freq != 0) {
-            s->heap[++(s->heap_len)] = max_code = n;
-            s->depth[n] = 0;
-        } else {
-            tree[n].Len = 0;
-        }
-    }
-
-    /* The pkzip format requires that at least one distance code exists,
-     * and that at least one bit should be sent even if there is only one
-     * possible code. So to avoid special checks later on we force at least
-     * two codes of non zero frequency.
-     */
-    while (s->heap_len < 2) {
-        node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
-        tree[node].Freq = 1;
-        s->depth[node] = 0;
-        s->opt_len--; if (stree) s->static_len -= stree[node].Len;
-        /* node is 0 or 1 so it does not have extra bits */
-    }
-    desc->max_code = max_code;
-
-    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
-     * establish sub-heaps of increasing lengths:
-     */
-    for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
-
-    /* Construct the Huffman tree by repeatedly combining the least two
-     * frequent nodes.
-     */
-    node = elems;              /* next internal node of the tree */
-    do {
-        pqremove(s, tree, n);  /* n = node of least frequency */
-        m = s->heap[SMALLEST]; /* m = node of next least frequency */
-
-        s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
-        s->heap[--(s->heap_max)] = m;
-
-        /* Create a new node father of n and m */
-        tree[node].Freq = tree[n].Freq + tree[m].Freq;
-        s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
-                                s->depth[n] : s->depth[m]) + 1);
-        tree[n].Dad = tree[m].Dad = (ush)node;
-#ifdef DUMP_BL_TREE
-        if (tree == s->bl_tree) {
-            fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
-                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
-        }
-#endif
-        /* and insert the new node in the heap */
-        s->heap[SMALLEST] = node++;
-        pqdownheap(s, tree, SMALLEST);
-
-    } while (s->heap_len >= 2);
-
-    s->heap[--(s->heap_max)] = s->heap[SMALLEST];
-
-    /* At this point, the fields freq and dad are set. We can now
-     * generate the bit lengths.
-     */
-    gen_bitlen(s, (tree_desc *)desc);
-
-    /* The field len is now set, we can generate the bit codes */
-    gen_codes ((ct_data *)tree, max_code, s->bl_count);
-}
-
-/* ===========================================================================
- * Scan a literal or distance tree to determine the frequencies of the codes
- * in the bit length tree.
- */
-local void scan_tree (s, tree, max_code)
-    deflate_state *s;
-    ct_data *tree;   /* the tree to be scanned */
-    int max_code;    /* and its largest code of non zero frequency */
-{
-    int n;                     /* iterates over all tree elements */
-    int prevlen = -1;          /* last emitted length */
-    int curlen;                /* length of current code */
-    int nextlen = tree[0].Len; /* length of next code */
-    int count = 0;             /* repeat count of the current code */
-    int max_count = 7;         /* max repeat count */
-    int min_count = 4;         /* min repeat count */
-
-    if (nextlen == 0) max_count = 138, min_count = 3;
-    tree[max_code+1].Len = (ush)0xffff; /* guard */
-
-    for (n = 0; n <= max_code; n++) {
-        curlen = nextlen; nextlen = tree[n+1].Len;
-        if (++count < max_count && curlen == nextlen) {
-            continue;
-        } else if (count < min_count) {
-            s->bl_tree[curlen].Freq += count;
-        } else if (curlen != 0) {
-            if (curlen != prevlen) s->bl_tree[curlen].Freq++;
-            s->bl_tree[REP_3_6].Freq++;
-        } else if (count <= 10) {
-            s->bl_tree[REPZ_3_10].Freq++;
-        } else {
-            s->bl_tree[REPZ_11_138].Freq++;
-        }
-        count = 0; prevlen = curlen;
-        if (nextlen == 0) {
-            max_count = 138, min_count = 3;
-        } else if (curlen == nextlen) {
-            max_count = 6, min_count = 3;
-        } else {
-            max_count = 7, min_count = 4;
-        }
-    }
-}
-
-/* ===========================================================================
- * Send a literal or distance tree in compressed form, using the codes in
- * bl_tree.
- */
-local void send_tree (s, tree, max_code)
-    deflate_state *s;
-    ct_data *tree; /* the tree to be scanned */
-    int max_code;       /* and its largest code of non zero frequency */
-{
-    int n;                     /* iterates over all tree elements */
-    int prevlen = -1;          /* last emitted length */
-    int curlen;                /* length of current code */
-    int nextlen = tree[0].Len; /* length of next code */
-    int count = 0;             /* repeat count of the current code */
-    int max_count = 7;         /* max repeat count */
-    int min_count = 4;         /* min repeat count */
-
-    /* tree[max_code+1].Len = -1; */  /* guard already set */
-    if (nextlen == 0) max_count = 138, min_count = 3;
-
-    for (n = 0; n <= max_code; n++) {
-        curlen = nextlen; nextlen = tree[n+1].Len;
-        if (++count < max_count && curlen == nextlen) {
-            continue;
-        } else if (count < min_count) {
-            do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
-
-        } else if (curlen != 0) {
-            if (curlen != prevlen) {
-                send_code(s, curlen, s->bl_tree); count--;
-            }
-            Assert(count >= 3 && count <= 6, " 3_6?");
-            send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
-
-        } else if (count <= 10) {
-            send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
-
-        } else {
-            send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
-        }
-        count = 0; prevlen = curlen;
-        if (nextlen == 0) {
-            max_count = 138, min_count = 3;
-        } else if (curlen == nextlen) {
-            max_count = 6, min_count = 3;
-        } else {
-            max_count = 7, min_count = 4;
-        }
-    }
-}
-
-/* ===========================================================================
- * Construct the Huffman tree for the bit lengths and return the index in
- * bl_order of the last bit length code to send.
- */
-local int build_bl_tree(s)
-    deflate_state *s;
-{
-    int max_blindex;  /* index of last bit length code of non zero freq */
-
-    /* Determine the bit length frequencies for literal and distance trees */
-    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
-    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
-
-    /* Build the bit length tree: */
-    build_tree(s, (tree_desc *)(&(s->bl_desc)));
-    /* opt_len now includes the length of the tree representations, except
-     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
-     */
-
-    /* Determine the number of bit length codes to send. The pkzip format
-     * requires that at least 4 bit length codes be sent. (appnote.txt says
-     * 3 but the actual value used is 4.)
-     */
-    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
-        if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
-    }
-    /* Update opt_len to include the bit length tree and counts */
-    s->opt_len += 3*(max_blindex+1) + 5+5+4;
-    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
-            s->opt_len, s->static_len));
-
-    return max_blindex;
-}
-
-/* ===========================================================================
- * Send the header for a block using dynamic Huffman trees: the counts, the
- * lengths of the bit length codes, the literal tree and the distance tree.
- * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
- */
-local void send_all_trees(s, lcodes, dcodes, blcodes)
-    deflate_state *s;
-    int lcodes, dcodes, blcodes; /* number of codes for each tree */
-{
-    int rank;                    /* index in bl_order */
-
-    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
-    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
-            "too many codes");
-    Tracev((stderr, "\nbl counts: "));
-    send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
-    send_bits(s, dcodes-1,   5);
-    send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
-    for (rank = 0; rank < blcodes; rank++) {
-        Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
-        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
-    }
-    Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
-
-    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
-    Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
-
-    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
-    Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
-}
-
-/* ===========================================================================
- * Send a stored block
- */
-void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
-    deflate_state *s;
-    charf *buf;       /* input block */
-    ulg stored_len;   /* length of input block */
-    int last;         /* one if this is the last block for a file */
-{
-    send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
-#ifdef DEBUG
-    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
-    s->compressed_len += (stored_len + 4) << 3;
-#endif
-    copy_block(s, buf, (unsigned)stored_len, 1); /* with header */
-}
-
-/* ===========================================================================
- * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
- */
-void ZLIB_INTERNAL _tr_flush_bits(s)
-    deflate_state *s;
-{
-    bi_flush(s);
-}
-
-/* ===========================================================================
- * Send one empty static block to give enough lookahead for inflate.
- * This takes 10 bits, of which 7 may remain in the bit buffer.
- */
-void ZLIB_INTERNAL _tr_align(s)
-    deflate_state *s;
-{
-    send_bits(s, STATIC_TREES<<1, 3);
-    send_code(s, END_BLOCK, static_ltree);
-#ifdef DEBUG
-    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
-#endif
-    bi_flush(s);
-}
-
-/* ===========================================================================
- * Determine the best encoding for the current block: dynamic trees, static
- * trees or store, and output the encoded block to the zip file.
- */
-void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
-    deflate_state *s;
-    charf *buf;       /* input block, or NULL if too old */
-    ulg stored_len;   /* length of input block */
-    int last;         /* one if this is the last block for a file */
-{
-    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
-    int max_blindex = 0;  /* index of last bit length code of non zero freq */
-
-    /* Build the Huffman trees unless a stored block is forced */
-    if (s->level > 0) {
-
-        /* Check if the file is binary or text */
-        if (s->strm->data_type == Z_UNKNOWN)
-            s->strm->data_type = detect_data_type(s);
-
-        /* Construct the literal and distance trees */
-        build_tree(s, (tree_desc *)(&(s->l_desc)));
-        Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
-                s->static_len));
-
-        build_tree(s, (tree_desc *)(&(s->d_desc)));
-        Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
-                s->static_len));
-        /* At this point, opt_len and static_len are the total bit lengths of
-         * the compressed block data, excluding the tree representations.
-         */
-
-        /* Build the bit length tree for the above two trees, and get the index
-         * in bl_order of the last bit length code to send.
-         */
-        max_blindex = build_bl_tree(s);
-
-        /* Determine the best encoding. Compute the block lengths in bytes. */
-        opt_lenb = (s->opt_len+3+7)>>3;
-        static_lenb = (s->static_len+3+7)>>3;
-
-        Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
-                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
-                s->last_lit));
-
-        if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
-
-    } else {
-        Assert(buf != (char*)0, "lost buf");
-        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
-    }
-
-#ifdef FORCE_STORED
-    if (buf != (char*)0) { /* force stored block */
-#else
-    if (stored_len+4 <= opt_lenb && buf != (char*)0) {
-                       /* 4: two words for the lengths */
-#endif
-        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
-         * Otherwise we can't have processed more than WSIZE input bytes since
-         * the last block flush, because compression would have been
-         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
-         * transform a block into a stored block.
-         */
-        _tr_stored_block(s, buf, stored_len, last);
-
-#ifdef FORCE_STATIC
-    } else if (static_lenb >= 0) { /* force static trees */
-#else
-    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
-#endif
-        send_bits(s, (STATIC_TREES<<1)+last, 3);
-        compress_block(s, (const ct_data *)static_ltree,
-                       (const ct_data *)static_dtree);
-#ifdef DEBUG
-        s->compressed_len += 3 + s->static_len;
-#endif
-    } else {
-        send_bits(s, (DYN_TREES<<1)+last, 3);
-        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
-                       max_blindex+1);
-        compress_block(s, (const ct_data *)s->dyn_ltree,
-                       (const ct_data *)s->dyn_dtree);
-#ifdef DEBUG
-        s->compressed_len += 3 + s->opt_len;
-#endif
-    }
-    Assert (s->compressed_len == s->bits_sent, "bad compressed size");
-    /* The above check is made mod 2^32, for files larger than 512 MB
-     * and uLong implemented on 32 bits.
-     */
-    init_block(s);
-
-    if (last) {
-        bi_windup(s);
-#ifdef DEBUG
-        s->compressed_len += 7;  /* align on byte boundary */
-#endif
-    }
-    Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
-           s->compressed_len-7*last));
-}
-
-/* ===========================================================================
- * Save the match info and tally the frequency counts. Return true if
- * the current block must be flushed.
- */
-int ZLIB_INTERNAL _tr_tally (s, dist, lc)
-    deflate_state *s;
-    unsigned dist;  /* distance of matched string */
-    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
-{
-    s->d_buf[s->last_lit] = (ush)dist;
-    s->l_buf[s->last_lit++] = (uch)lc;
-    if (dist == 0) {
-        /* lc is the unmatched char */
-        s->dyn_ltree[lc].Freq++;
-    } else {
-        s->matches++;
-        /* Here, lc is the match length - MIN_MATCH */
-        dist--;             /* dist = match distance - 1 */
-        Assert((ush)dist < (ush)MAX_DIST(s) &&
-               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
-               (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
-
-        s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
-        s->dyn_dtree[d_code(dist)].Freq++;
-    }
-
-#ifdef TRUNCATE_BLOCK
-    /* Try to guess if it is profitable to stop the current block here */
-    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
-        /* Compute an upper bound for the compressed length */
-        ulg out_length = (ulg)s->last_lit*8L;
-        ulg in_length = (ulg)((long)s->strstart - s->block_start);
-        int dcode;
-        for (dcode = 0; dcode < D_CODES; dcode++) {
-            out_length += (ulg)s->dyn_dtree[dcode].Freq *
-                (5L+extra_dbits[dcode]);
-        }
-        out_length >>= 3;
-        Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
-               s->last_lit, in_length, out_length,
-               100L - out_length*100L/in_length));
-        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
-    }
-#endif
-    return (s->last_lit == s->lit_bufsize-1);
-    /* We avoid equality with lit_bufsize because of wraparound at 64K
-     * on 16 bit machines and because stored blocks are restricted to
-     * 64K-1 bytes.
-     */
-}
-
-/* ===========================================================================
- * Send the block data compressed using the given Huffman trees
- */
-local void compress_block(s, ltree, dtree)
-    deflate_state *s;
-    const ct_data *ltree; /* literal tree */
-    const ct_data *dtree; /* distance tree */
-{
-    unsigned dist;      /* distance of matched string */
-    int lc;             /* match length or unmatched char (if dist == 0) */
-    unsigned lx = 0;    /* running index in l_buf */
-    unsigned code;      /* the code to send */
-    int extra;          /* number of extra bits to send */
-
-    if (s->last_lit != 0) do {
-        dist = s->d_buf[lx];
-        lc = s->l_buf[lx++];
-        if (dist == 0) {
-            send_code(s, lc, ltree); /* send a literal byte */
-            Tracecv(isgraph(lc), (stderr," '%c' ", lc));
-        } else {
-            /* Here, lc is the match length - MIN_MATCH */
-            code = _length_code[lc];
-            send_code(s, code+LITERALS+1, ltree); /* send the length code */
-            extra = extra_lbits[code];
-            if (extra != 0) {
-                lc -= base_length[code];
-                send_bits(s, lc, extra);       /* send the extra length bits */
-            }
-            dist--; /* dist is now the match distance - 1 */
-            code = d_code(dist);
-            Assert (code < D_CODES, "bad d_code");
-
-            send_code(s, code, dtree);       /* send the distance code */
-            extra = extra_dbits[code];
-            if (extra != 0) {
-                dist -= base_dist[code];
-                send_bits(s, dist, extra);   /* send the extra distance bits */
-            }
-        } /* literal or match pair ? */
-
-        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
-        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
-               "pendingBuf overflow");
-
-    } while (lx < s->last_lit);
-
-    send_code(s, END_BLOCK, ltree);
-}
-
-/* ===========================================================================
- * Check if the data type is TEXT or BINARY, using the following algorithm:
- * - TEXT if the two conditions below are satisfied:
- *    a) There are no non-portable control characters belonging to the
- *       "black list" (0..6, 14..25, 28..31).
- *    b) There is at least one printable character belonging to the
- *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
- * - BINARY otherwise.
- * - The following partially-portable control characters form a
- *   "gray list" that is ignored in this detection algorithm:
- *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
- * IN assertion: the fields Freq of dyn_ltree are set.
- */
-local int detect_data_type(s)
-    deflate_state *s;
-{
-    /* black_mask is the bit mask of black-listed bytes
-     * set bits 0..6, 14..25, and 28..31
-     * 0xf3ffc07f = binary 11110011111111111100000001111111
-     */
-    unsigned long black_mask = 0xf3ffc07fUL;
-    int n;
-
-    /* Check for non-textual ("black-listed") bytes. */
-    for (n = 0; n <= 31; n++, black_mask >>= 1)
-        if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
-            return Z_BINARY;
-
-    /* Check for textual ("white-listed") bytes. */
-    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
-            || s->dyn_ltree[13].Freq != 0)
-        return Z_TEXT;
-    for (n = 32; n < LITERALS; n++)
-        if (s->dyn_ltree[n].Freq != 0)
-            return Z_TEXT;
-
-    /* There are no "black-listed" or "white-listed" bytes:
-     * this stream either is empty or has tolerated ("gray-listed") bytes only.
-     */
-    return Z_BINARY;
-}
-
-/* ===========================================================================
- * Reverse the first len bits of a code, using straightforward code (a faster
- * method would use a table)
- * IN assertion: 1 <= len <= 15
- */
-local unsigned bi_reverse(code, len)
-    unsigned code; /* the value to invert */
-    int len;       /* its bit length */
-{
-    register unsigned res = 0;
-    do {
-        res |= code & 1;
-        code >>= 1, res <<= 1;
-    } while (--len > 0);
-    return res >> 1;
-}
-
-/* ===========================================================================
- * Flush the bit buffer, keeping at most 7 bits in it.
- */
-local void bi_flush(s)
-    deflate_state *s;
-{
-    if (s->bi_valid == 16) {
-        put_short(s, s->bi_buf);
-        s->bi_buf = 0;
-        s->bi_valid = 0;
-    } else if (s->bi_valid >= 8) {
-        put_byte(s, (Byte)s->bi_buf);
-        s->bi_buf >>= 8;
-        s->bi_valid -= 8;
-    }
-}
-
-/* ===========================================================================
- * Flush the bit buffer and align the output on a byte boundary
- */
-local void bi_windup(s)
-    deflate_state *s;
-{
-    if (s->bi_valid > 8) {
-        put_short(s, s->bi_buf);
-    } else if (s->bi_valid > 0) {
-        put_byte(s, (Byte)s->bi_buf);
-    }
-    s->bi_buf = 0;
-    s->bi_valid = 0;
-#ifdef DEBUG
-    s->bits_sent = (s->bits_sent+7) & ~7;
-#endif
-}
-
-/* ===========================================================================
- * Copy a stored block, storing first the length and its
- * one's complement if requested.
- */
-local void copy_block(s, buf, len, header)
-    deflate_state *s;
-    charf    *buf;    /* the input data */
-    unsigned len;     /* its length */
-    int      header;  /* true if block header must be written */
-{
-    bi_windup(s);        /* align on byte boundary */
-
-    if (header) {
-        put_short(s, (ush)len);
-        put_short(s, (ush)~len);
-#ifdef DEBUG
-        s->bits_sent += 2*16;
-#endif
-    }
-#ifdef DEBUG
-    s->bits_sent += (ulg)len<<3;
-#endif
-    while (len--) {
-        put_byte(s, *buf++);
-    }
-}
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/trees.h	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,152 +0,0 @@
-/*
- * 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.
- */
-
-/* header created automatically with -DGEN_TREES_H */
-
-local const ct_data static_ltree[L_CODES+2] = {
-{{ 12},{  8}}, {{140},{  8}}, {{ 76},{  8}}, {{204},{  8}}, {{ 44},{  8}},
-{{172},{  8}}, {{108},{  8}}, {{236},{  8}}, {{ 28},{  8}}, {{156},{  8}},
-{{ 92},{  8}}, {{220},{  8}}, {{ 60},{  8}}, {{188},{  8}}, {{124},{  8}},
-{{252},{  8}}, {{  2},{  8}}, {{130},{  8}}, {{ 66},{  8}}, {{194},{  8}},
-{{ 34},{  8}}, {{162},{  8}}, {{ 98},{  8}}, {{226},{  8}}, {{ 18},{  8}},
-{{146},{  8}}, {{ 82},{  8}}, {{210},{  8}}, {{ 50},{  8}}, {{178},{  8}},
-{{114},{  8}}, {{242},{  8}}, {{ 10},{  8}}, {{138},{  8}}, {{ 74},{  8}},
-{{202},{  8}}, {{ 42},{  8}}, {{170},{  8}}, {{106},{  8}}, {{234},{  8}},
-{{ 26},{  8}}, {{154},{  8}}, {{ 90},{  8}}, {{218},{  8}}, {{ 58},{  8}},
-{{186},{  8}}, {{122},{  8}}, {{250},{  8}}, {{  6},{  8}}, {{134},{  8}},
-{{ 70},{  8}}, {{198},{  8}}, {{ 38},{  8}}, {{166},{  8}}, {{102},{  8}},
-{{230},{  8}}, {{ 22},{  8}}, {{150},{  8}}, {{ 86},{  8}}, {{214},{  8}},
-{{ 54},{  8}}, {{182},{  8}}, {{118},{  8}}, {{246},{  8}}, {{ 14},{  8}},
-{{142},{  8}}, {{ 78},{  8}}, {{206},{  8}}, {{ 46},{  8}}, {{174},{  8}},
-{{110},{  8}}, {{238},{  8}}, {{ 30},{  8}}, {{158},{  8}}, {{ 94},{  8}},
-{{222},{  8}}, {{ 62},{  8}}, {{190},{  8}}, {{126},{  8}}, {{254},{  8}},
-{{  1},{  8}}, {{129},{  8}}, {{ 65},{  8}}, {{193},{  8}}, {{ 33},{  8}},
-{{161},{  8}}, {{ 97},{  8}}, {{225},{  8}}, {{ 17},{  8}}, {{145},{  8}},
-{{ 81},{  8}}, {{209},{  8}}, {{ 49},{  8}}, {{177},{  8}}, {{113},{  8}},
-{{241},{  8}}, {{  9},{  8}}, {{137},{  8}}, {{ 73},{  8}}, {{201},{  8}},
-{{ 41},{  8}}, {{169},{  8}}, {{105},{  8}}, {{233},{  8}}, {{ 25},{  8}},
-{{153},{  8}}, {{ 89},{  8}}, {{217},{  8}}, {{ 57},{  8}}, {{185},{  8}},
-{{121},{  8}}, {{249},{  8}}, {{  5},{  8}}, {{133},{  8}}, {{ 69},{  8}},
-{{197},{  8}}, {{ 37},{  8}}, {{165},{  8}}, {{101},{  8}}, {{229},{  8}},
-{{ 21},{  8}}, {{149},{  8}}, {{ 85},{  8}}, {{213},{  8}}, {{ 53},{  8}},
-{{181},{  8}}, {{117},{  8}}, {{245},{  8}}, {{ 13},{  8}}, {{141},{  8}},
-{{ 77},{  8}}, {{205},{  8}}, {{ 45},{  8}}, {{173},{  8}}, {{109},{  8}},
-{{237},{  8}}, {{ 29},{  8}}, {{157},{  8}}, {{ 93},{  8}}, {{221},{  8}},
-{{ 61},{  8}}, {{189},{  8}}, {{125},{  8}}, {{253},{  8}}, {{ 19},{  9}},
-{{275},{  9}}, {{147},{  9}}, {{403},{  9}}, {{ 83},{  9}}, {{339},{  9}},
-{{211},{  9}}, {{467},{  9}}, {{ 51},{  9}}, {{307},{  9}}, {{179},{  9}},
-{{435},{  9}}, {{115},{  9}}, {{371},{  9}}, {{243},{  9}}, {{499},{  9}},
-{{ 11},{  9}}, {{267},{  9}}, {{139},{  9}}, {{395},{  9}}, {{ 75},{  9}},
-{{331},{  9}}, {{203},{  9}}, {{459},{  9}}, {{ 43},{  9}}, {{299},{  9}},
-{{171},{  9}}, {{427},{  9}}, {{107},{  9}}, {{363},{  9}}, {{235},{  9}},
-{{491},{  9}}, {{ 27},{  9}}, {{283},{  9}}, {{155},{  9}}, {{411},{  9}},
-{{ 91},{  9}}, {{347},{  9}}, {{219},{  9}}, {{475},{  9}}, {{ 59},{  9}},
-{{315},{  9}}, {{187},{  9}}, {{443},{  9}}, {{123},{  9}}, {{379},{  9}},
-{{251},{  9}}, {{507},{  9}}, {{  7},{  9}}, {{263},{  9}}, {{135},{  9}},
-{{391},{  9}}, {{ 71},{  9}}, {{327},{  9}}, {{199},{  9}}, {{455},{  9}},
-{{ 39},{  9}}, {{295},{  9}}, {{167},{  9}}, {{423},{  9}}, {{103},{  9}},
-{{359},{  9}}, {{231},{  9}}, {{487},{  9}}, {{ 23},{  9}}, {{279},{  9}},
-{{151},{  9}}, {{407},{  9}}, {{ 87},{  9}}, {{343},{  9}}, {{215},{  9}},
-{{471},{  9}}, {{ 55},{  9}}, {{311},{  9}}, {{183},{  9}}, {{439},{  9}},
-{{119},{  9}}, {{375},{  9}}, {{247},{  9}}, {{503},{  9}}, {{ 15},{  9}},
-{{271},{  9}}, {{143},{  9}}, {{399},{  9}}, {{ 79},{  9}}, {{335},{  9}},
-{{207},{  9}}, {{463},{  9}}, {{ 47},{  9}}, {{303},{  9}}, {{175},{  9}},
-{{431},{  9}}, {{111},{  9}}, {{367},{  9}}, {{239},{  9}}, {{495},{  9}},
-{{ 31},{  9}}, {{287},{  9}}, {{159},{  9}}, {{415},{  9}}, {{ 95},{  9}},
-{{351},{  9}}, {{223},{  9}}, {{479},{  9}}, {{ 63},{  9}}, {{319},{  9}},
-{{191},{  9}}, {{447},{  9}}, {{127},{  9}}, {{383},{  9}}, {{255},{  9}},
-{{511},{  9}}, {{  0},{  7}}, {{ 64},{  7}}, {{ 32},{  7}}, {{ 96},{  7}},
-{{ 16},{  7}}, {{ 80},{  7}}, {{ 48},{  7}}, {{112},{  7}}, {{  8},{  7}},
-{{ 72},{  7}}, {{ 40},{  7}}, {{104},{  7}}, {{ 24},{  7}}, {{ 88},{  7}},
-{{ 56},{  7}}, {{120},{  7}}, {{  4},{  7}}, {{ 68},{  7}}, {{ 36},{  7}},
-{{100},{  7}}, {{ 20},{  7}}, {{ 84},{  7}}, {{ 52},{  7}}, {{116},{  7}},
-{{  3},{  8}}, {{131},{  8}}, {{ 67},{  8}}, {{195},{  8}}, {{ 35},{  8}},
-{{163},{  8}}, {{ 99},{  8}}, {{227},{  8}}
-};
-
-local const ct_data static_dtree[D_CODES] = {
-{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
-{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
-{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
-{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
-{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
-{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
-};
-
-const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {
- 0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,
- 8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,
-10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
-11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
-12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
-13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
-13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
-14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
-15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
-15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,  0,  0, 16, 17,
-18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
-23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
-26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
-26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
-27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
-27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
-28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
-28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
-28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
-29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
-29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
-29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
-};
-
-const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {
- 0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,
-13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
-17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
-19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
-21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
-22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
-23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
-25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
-25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
-26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
-26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
-27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
-};
-
-local const int base_length[LENGTH_CODES] = {
-0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
-64, 80, 96, 112, 128, 160, 192, 224, 0
-};
-
-local const int base_dist[D_CODES] = {
-    0,     1,     2,     3,     4,     6,     8,    12,    16,    24,
-   32,    48,    64,    96,   128,   192,   256,   384,   512,   768,
- 1024,  1536,  2048,  3072,  4096,  6144,  8192, 12288, 16384, 24576
-};
-
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/uncompr.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,83 +0,0 @@
-/*
- * 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.
- */
-
-/* uncompr.c -- decompress a memory buffer
- * Copyright (C) 1995-2003, 2010 Jean-loup Gailly.
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/* @(#) $Id$ */
-
-#define ZLIB_INTERNAL
-#include "zlib.h"
-
-/* ===========================================================================
-     Decompresses the source buffer into the destination buffer.  sourceLen is
-   the byte length of the source buffer. Upon entry, destLen is the total
-   size of the destination buffer, which must be large enough to hold the
-   entire uncompressed data. (The size of the uncompressed data must have
-   been saved previously by the compressor and transmitted to the decompressor
-   by some mechanism outside the scope of this compression library.)
-   Upon exit, destLen is the actual size of the compressed buffer.
-
-     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
-   enough memory, Z_BUF_ERROR if there was not enough room in the output
-   buffer, or Z_DATA_ERROR if the input data was corrupted.
-*/
-int ZEXPORT uncompress (dest, destLen, source, sourceLen)
-    Bytef *dest;
-    uLongf *destLen;
-    const Bytef *source;
-    uLong sourceLen;
-{
-    z_stream stream;
-    int err;
-
-    stream.next_in = (z_const Bytef *)source;
-    stream.avail_in = (uInt)sourceLen;
-    /* Check for source > 64K on 16-bit machine: */
-    if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR;
-
-    stream.next_out = dest;
-    stream.avail_out = (uInt)*destLen;
-    if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR;
-
-    stream.zalloc = (alloc_func)0;
-    stream.zfree = (free_func)0;
-
-    err = inflateInit(&stream);
-    if (err != Z_OK) return err;
-
-    err = inflate(&stream, Z_FINISH);
-    if (err != Z_STREAM_END) {
-        inflateEnd(&stream);
-        if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0))
-            return Z_DATA_ERROR;
-        return err;
-    }
-    *destLen = stream.total_out;
-
-    err = inflateEnd(&stream);
-    return err;
-}
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/zadler32.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,203 +0,0 @@
-/*
- * 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.
- */
-
-/* adler32.c -- compute the Adler-32 checksum of a data stream
- * Copyright (C) 1995-2011 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/* @(#) $Id$ */
-
-#include "zutil.h"
-
-#define local static
-
-local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2));
-
-#define BASE 65521      /* largest prime smaller than 65536 */
-#define NMAX 5552
-/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
-
-#define DO1(buf,i)  {adler += (buf)[i]; sum2 += adler;}
-#define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);
-#define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);
-#define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);
-#define DO16(buf)   DO8(buf,0); DO8(buf,8);
-
-/* use NO_DIVIDE if your processor does not do division in hardware --
-   try it both ways to see which is faster */
-#ifdef NO_DIVIDE
-/* note that this assumes BASE is 65521, where 65536 % 65521 == 15
-   (thank you to John Reiser for pointing this out) */
-#  define CHOP(a) \
-    do { \
-        unsigned long tmp = a >> 16; \
-        a &= 0xffffUL; \
-        a += (tmp << 4) - tmp; \
-    } while (0)
-#  define MOD28(a) \
-    do { \
-        CHOP(a); \
-        if (a >= BASE) a -= BASE; \
-    } while (0)
-#  define MOD(a) \
-    do { \
-        CHOP(a); \
-        MOD28(a); \
-    } while (0)
-#  define MOD63(a) \
-    do { /* this assumes a is not negative */ \
-        z_off64_t tmp = a >> 32; \
-        a &= 0xffffffffL; \
-        a += (tmp << 8) - (tmp << 5) + tmp; \
-        tmp = a >> 16; \
-        a &= 0xffffL; \
-        a += (tmp << 4) - tmp; \
-        tmp = a >> 16; \
-        a &= 0xffffL; \
-        a += (tmp << 4) - tmp; \
-        if (a >= BASE) a -= BASE; \
-    } while (0)
-#else
-#  define MOD(a) a %= BASE
-#  define MOD28(a) a %= BASE
-#  define MOD63(a) a %= BASE
-#endif
-
-/* ========================================================================= */
-uLong ZEXPORT adler32(adler, buf, len)
-    uLong adler;
-    const Bytef *buf;
-    uInt len;
-{
-    unsigned long sum2;
-    unsigned n;
-
-    /* split Adler-32 into component sums */
-    sum2 = (adler >> 16) & 0xffff;
-    adler &= 0xffff;
-
-    /* in case user likes doing a byte at a time, keep it fast */
-    if (len == 1) {
-        adler += buf[0];
-        if (adler >= BASE)
-            adler -= BASE;
-        sum2 += adler;
-        if (sum2 >= BASE)
-            sum2 -= BASE;
-        return adler | (sum2 << 16);
-    }
-
-    /* initial Adler-32 value (deferred check for len == 1 speed) */
-    if (buf == Z_NULL)
-        return 1L;
-
-    /* in case short lengths are provided, keep it somewhat fast */
-    if (len < 16) {
-        while (len--) {
-            adler += *buf++;
-            sum2 += adler;
-        }
-        if (adler >= BASE)
-            adler -= BASE;
-        MOD28(sum2);            /* only added so many BASE's */
-        return adler | (sum2 << 16);
-    }
-
-    /* do length NMAX blocks -- requires just one modulo operation */
-    while (len >= NMAX) {
-        len -= NMAX;
-        n = NMAX / 16;          /* NMAX is divisible by 16 */
-        do {
-            DO16(buf);          /* 16 sums unrolled */
-            buf += 16;
-        } while (--n);
-        MOD(adler);
-        MOD(sum2);
-    }
-
-    /* do remaining bytes (less than NMAX, still just one modulo) */
-    if (len) {                  /* avoid modulos if none remaining */
-        while (len >= 16) {
-            len -= 16;
-            DO16(buf);
-            buf += 16;
-        }
-        while (len--) {
-            adler += *buf++;
-            sum2 += adler;
-        }
-        MOD(adler);
-        MOD(sum2);
-    }
-
-    /* return recombined sums */
-    return adler | (sum2 << 16);
-}
-
-/* ========================================================================= */
-local uLong adler32_combine_(adler1, adler2, len2)
-    uLong adler1;
-    uLong adler2;
-    z_off64_t len2;
-{
-    unsigned long sum1;
-    unsigned long sum2;
-    unsigned rem;
-
-    /* for negative len, return invalid adler32 as a clue for debugging */
-    if (len2 < 0)
-        return 0xffffffffUL;
-
-    /* the derivation of this formula is left as an exercise for the reader */
-    MOD63(len2);                /* assumes len2 >= 0 */
-    rem = (unsigned)len2;
-    sum1 = adler1 & 0xffff;
-    sum2 = rem * sum1;
-    MOD(sum2);
-    sum1 += (adler2 & 0xffff) + BASE - 1;
-    sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
-    if (sum1 >= BASE) sum1 -= BASE;
-    if (sum1 >= BASE) sum1 -= BASE;
-    if (sum2 >= (BASE << 1)) sum2 -= (BASE << 1);
-    if (sum2 >= BASE) sum2 -= BASE;
-    return sum1 | (sum2 << 16);
-}
-
-/* ========================================================================= */
-uLong ZEXPORT adler32_combine(adler1, adler2, len2)
-    uLong adler1;
-    uLong adler2;
-    z_off_t len2;
-{
-    return adler32_combine_(adler1, adler2, len2);
-}
-
-uLong ZEXPORT adler32_combine64(adler1, adler2, len2)
-    uLong adler1;
-    uLong adler2;
-    z_off64_t len2;
-{
-    return adler32_combine_(adler1, adler2, len2);
-}
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/zconf.h	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,543 +0,0 @@
-/*
- * 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.
- */
-
-/* zconf.h -- configuration of the zlib compression library
- * Copyright (C) 1995-2013 Jean-loup Gailly.
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/* @(#) $Id$ */
-
-#ifndef ZCONF_H
-#define ZCONF_H
-
-/* for _LP64 */
-#include <sys/types.h>
-
-/*
- * If you *really* need a unique prefix for all types and library functions,
- * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
- * Even better than compiling with -DZ_PREFIX would be to use configure to set
- * this permanently in zconf.h using "./configure --zprefix".
- */
-#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
-#  define Z_PREFIX_SET
-
-/* all linked symbols */
-#  define _dist_code            z__dist_code
-#  define _length_code          z__length_code
-#  define _tr_align             z__tr_align
-#  define _tr_flush_bits        z__tr_flush_bits
-#  define _tr_flush_block       z__tr_flush_block
-#  define _tr_init              z__tr_init
-#  define _tr_stored_block      z__tr_stored_block
-#  define _tr_tally             z__tr_tally
-#  define adler32               z_adler32
-#  define adler32_combine       z_adler32_combine
-#  define adler32_combine64     z_adler32_combine64
-#  ifndef Z_SOLO
-#    define compress              z_compress
-#    define compress2             z_compress2
-#    define compressBound         z_compressBound
-#  endif
-#  define crc32                 z_crc32
-#  define crc32_combine         z_crc32_combine
-#  define crc32_combine64       z_crc32_combine64
-#  define deflate               z_deflate
-#  define deflateBound          z_deflateBound
-#  define deflateCopy           z_deflateCopy
-#  define deflateEnd            z_deflateEnd
-#  define deflateInit2_         z_deflateInit2_
-#  define deflateInit_          z_deflateInit_
-#  define deflateParams         z_deflateParams
-#  define deflatePending        z_deflatePending
-#  define deflatePrime          z_deflatePrime
-#  define deflateReset          z_deflateReset
-#  define deflateResetKeep      z_deflateResetKeep
-#  define deflateSetDictionary  z_deflateSetDictionary
-#  define deflateSetHeader      z_deflateSetHeader
-#  define deflateTune           z_deflateTune
-#  define deflate_copyright     z_deflate_copyright
-#  define get_crc_table         z_get_crc_table
-#  ifndef Z_SOLO
-#    define gz_error              z_gz_error
-#    define gz_intmax             z_gz_intmax
-#    define gz_strwinerror        z_gz_strwinerror
-#    define gzbuffer              z_gzbuffer
-#    define gzclearerr            z_gzclearerr
-#    define gzclose               z_gzclose
-#    define gzclose_r             z_gzclose_r
-#    define gzclose_w             z_gzclose_w
-#    define gzdirect              z_gzdirect
-#    define gzdopen               z_gzdopen
-#    define gzeof                 z_gzeof
-#    define gzerror               z_gzerror
-#    define gzflush               z_gzflush
-#    define gzgetc                z_gzgetc
-#    define gzgetc_               z_gzgetc_
-#    define gzgets                z_gzgets
-#    define gzoffset              z_gzoffset
-#    define gzoffset64            z_gzoffset64
-#    define gzopen                z_gzopen
-#    define gzopen64              z_gzopen64
-#    ifdef _WIN32
-#      define gzopen_w              z_gzopen_w
-#    endif
-#    define gzprintf              z_gzprintf
-#    define gzvprintf             z_gzvprintf
-#    define gzputc                z_gzputc
-#    define gzputs                z_gzputs
-#    define gzread                z_gzread
-#    define gzrewind              z_gzrewind
-#    define gzseek                z_gzseek
-#    define gzseek64              z_gzseek64
-#    define gzsetparams           z_gzsetparams
-#    define gztell                z_gztell
-#    define gztell64              z_gztell64
-#    define gzungetc              z_gzungetc
-#    define gzwrite               z_gzwrite
-#  endif
-#  define inflate               z_inflate
-#  define inflateBack           z_inflateBack
-#  define inflateBackEnd        z_inflateBackEnd
-#  define inflateBackInit_      z_inflateBackInit_
-#  define inflateCopy           z_inflateCopy
-#  define inflateEnd            z_inflateEnd
-#  define inflateGetHeader      z_inflateGetHeader
-#  define inflateInit2_         z_inflateInit2_
-#  define inflateInit_          z_inflateInit_
-#  define inflateMark           z_inflateMark
-#  define inflatePrime          z_inflatePrime
-#  define inflateReset          z_inflateReset
-#  define inflateReset2         z_inflateReset2
-#  define inflateSetDictionary  z_inflateSetDictionary
-#  define inflateGetDictionary  z_inflateGetDictionary
-#  define inflateSync           z_inflateSync
-#  define inflateSyncPoint      z_inflateSyncPoint
-#  define inflateUndermine      z_inflateUndermine
-#  define inflateResetKeep      z_inflateResetKeep
-#  define inflate_copyright     z_inflate_copyright
-#  define inflate_fast          z_inflate_fast
-#  define inflate_table         z_inflate_table
-#  ifndef Z_SOLO
-#    define uncompress            z_uncompress
-#  endif
-#  define zError                z_zError
-#  ifndef Z_SOLO
-#    define zcalloc               z_zcalloc
-#    define zcfree                z_zcfree
-#  endif
-#  define zlibCompileFlags      z_zlibCompileFlags
-#  define zlibVersion           z_zlibVersion
-
-/* all zlib typedefs in zlib.h and zconf.h */
-#  define Byte                  z_Byte
-#  define Bytef                 z_Bytef
-#  define alloc_func            z_alloc_func
-#  define charf                 z_charf
-#  define free_func             z_free_func
-#  ifndef Z_SOLO
-#    define gzFile                z_gzFile
-#  endif
-#  define gz_header             z_gz_header
-#  define gz_headerp            z_gz_headerp
-#  define in_func               z_in_func
-#  define intf                  z_intf
-#  define out_func              z_out_func
-#  define uInt                  z_uInt
-#  define uIntf                 z_uIntf
-#  define uLong                 z_uLong
-#  define uLongf                z_uLongf
-#  define voidp                 z_voidp
-#  define voidpc                z_voidpc
-#  define voidpf                z_voidpf
-
-/* all zlib structs in zlib.h and zconf.h */
-#  define gz_header_s           z_gz_header_s
-#  define internal_state        z_internal_state
-
-#endif
-
-#if defined(__MSDOS__) && !defined(MSDOS)
-#  define MSDOS
-#endif
-#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
-#  define OS2
-#endif
-#if defined(_WINDOWS) && !defined(WINDOWS)
-#  define WINDOWS
-#endif
-#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
-#  ifndef WIN32
-#    define WIN32
-#  endif
-#endif
-#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
-#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
-#    ifndef SYS16BIT
-#      define SYS16BIT
-#    endif
-#  endif
-#endif
-
-/*
- * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
- * than 64k bytes at a time (needed on systems with 16-bit int).
- */
-#ifdef SYS16BIT
-#  define MAXSEG_64K
-#endif
-#ifdef MSDOS
-#  define UNALIGNED_OK
-#endif
-
-#ifdef __STDC_VERSION__
-#  ifndef STDC
-#    define STDC
-#  endif
-#  if __STDC_VERSION__ >= 199901L
-#    ifndef STDC99
-#      define STDC99
-#    endif
-#  endif
-#endif
-#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
-#  define STDC
-#endif
-#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
-#  define STDC
-#endif
-#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
-#  define STDC
-#endif
-#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
-#  define STDC
-#endif
-
-#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
-#  define STDC
-#endif
-
-#ifndef STDC
-#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
-#    define const       /* note: need a more gentle solution here */
-#  endif
-#endif
-
-#if defined(ZLIB_CONST) && !defined(z_const)
-#  define z_const const
-#else
-#  define z_const
-#endif
-
-/* Some Mac compilers merge all .h files incorrectly: */
-#if defined(__MWERKS__)||defined(applec)||defined(THINK_C)||defined(__SC__)
-#  define NO_DUMMY_DECL
-#endif
-
-/* Maximum value for memLevel in deflateInit2 */
-#ifndef MAX_MEM_LEVEL
-#  ifdef MAXSEG_64K
-#    define MAX_MEM_LEVEL 8
-#  else
-#    define MAX_MEM_LEVEL 9
-#  endif
-#endif
-
-/* Maximum value for windowBits in deflateInit2 and inflateInit2.
- * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
- * created by gzip. (Files created by minigzip can still be extracted by
- * gzip.)
- */
-#ifndef MAX_WBITS
-#  define MAX_WBITS   15 /* 32K LZ77 window */
-#endif
-
-/* The memory requirements for deflate are (in bytes):
-            (1 << (windowBits+2)) +  (1 << (memLevel+9))
- that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
- plus a few kilobytes for small objects. For example, if you want to reduce
- the default memory requirements from 256K to 128K, compile with
-     make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
- Of course this will generally degrade compression (there's no free lunch).
-
-   The memory requirements for inflate are (in bytes) 1 << windowBits
- that is, 32K for windowBits=15 (default value) plus a few kilobytes
- for small objects.
-*/
-
-                        /* Type declarations */
-
-#ifndef OF /* function prototypes */
-#  ifdef STDC
-#    define OF(args)  args
-#  else
-#    define OF(args)  ()
-#  endif
-#endif
-
-#ifndef Z_ARG /* function prototypes for stdarg */
-#  if defined(STDC) || defined(Z_HAVE_STDARG_H)
-#    define Z_ARG(args)  args
-#  else
-#    define Z_ARG(args)  ()
-#  endif
-#endif
-
-/* The following definitions for FAR are needed only for MSDOS mixed
- * model programming (small or medium model with some far allocations).
- * This was tested only with MSC; for other MSDOS compilers you may have
- * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
- * just define FAR to be empty.
- */
-#ifdef SYS16BIT
-#  if defined(M_I86SM) || defined(M_I86MM)
-     /* MSC small or medium model */
-#    define SMALL_MEDIUM
-#    ifdef _MSC_VER
-#      define FAR _far
-#    else
-#      define FAR far
-#    endif
-#  endif
-#  if (defined(__SMALL__) || defined(__MEDIUM__))
-     /* Turbo C small or medium model */
-#    define SMALL_MEDIUM
-#    ifdef __BORLANDC__
-#      define FAR _far
-#    else
-#      define FAR far
-#    endif
-#  endif
-#endif
-
-#if defined(WINDOWS) || defined(WIN32)
-   /* If building or using zlib as a DLL, define ZLIB_DLL.
-    * This is not mandatory, but it offers a little performance increase.
-    */
-#  ifdef ZLIB_DLL
-#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
-#      ifdef ZLIB_INTERNAL
-#        define ZEXTERN extern __declspec(dllexport)
-#      else
-#        define ZEXTERN extern __declspec(dllimport)
-#      endif
-#    endif
-#  endif  /* ZLIB_DLL */
-   /* If building or using zlib with the WINAPI/WINAPIV calling convention,
-    * define ZLIB_WINAPI.
-    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
-    */
-#  ifdef ZLIB_WINAPI
-#    ifdef FAR
-#      undef FAR
-#    endif
-#    include <windows.h>
-     /* No need for _export, use ZLIB.DEF instead. */
-     /* For complete Windows compatibility, use WINAPI, not __stdcall. */
-#    define ZEXPORT WINAPI
-#    ifdef WIN32
-#      define ZEXPORTVA WINAPIV
-#    else
-#      define ZEXPORTVA FAR CDECL
-#    endif
-#  endif
-#endif
-
-#if defined (__BEOS__)
-#  ifdef ZLIB_DLL
-#    ifdef ZLIB_INTERNAL
-#      define ZEXPORT   __declspec(dllexport)
-#      define ZEXPORTVA __declspec(dllexport)
-#    else
-#      define ZEXPORT   __declspec(dllimport)
-#      define ZEXPORTVA __declspec(dllimport)
-#    endif
-#  endif
-#endif
-
-#ifndef ZEXTERN
-#  define ZEXTERN extern
-#endif
-#ifndef ZEXPORT
-#  define ZEXPORT
-#endif
-#ifndef ZEXPORTVA
-#  define ZEXPORTVA
-#endif
-
-#ifndef FAR
-#  define FAR
-#endif
-
-#if !defined(__MACTYPES__)
-typedef unsigned char  Byte;  /* 8 bits */
-#endif
-typedef unsigned int   uInt;  /* 16 bits or more */
-
-#ifdef _LP64
-typedef unsigned int  uLong;  /* 32 bits or more */
-#else
-typedef unsigned long  uLong; /* 32 bits or more */
-#endif
-
-#ifdef SMALL_MEDIUM
-   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
-#  define Bytef Byte FAR
-#else
-   typedef Byte  FAR Bytef;
-#endif
-typedef char  FAR charf;
-typedef int   FAR intf;
-typedef uInt  FAR uIntf;
-typedef uLong FAR uLongf;
-
-#ifdef STDC
-   typedef void const *voidpc;
-   typedef void FAR   *voidpf;
-   typedef void       *voidp;
-#else
-   typedef Byte const *voidpc;
-   typedef Byte FAR   *voidpf;
-   typedef Byte       *voidp;
-#endif
-
-#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC)
-#  include <limits.h>
-#  if (UINT_MAX == 0xffffffffUL)
-#    define Z_U4 unsigned
-#  elif (ULONG_MAX == 0xffffffffUL)
-#    define Z_U4 unsigned long
-#  elif (USHRT_MAX == 0xffffffffUL)
-#    define Z_U4 unsigned short
-#  endif
-#endif
-
-#ifdef Z_U4
-   typedef Z_U4 z_crc_t;
-#else
-   typedef unsigned long z_crc_t;
-#endif
-
-#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
-#  define Z_HAVE_UNISTD_H
-#endif
-
-#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */
-#  define Z_HAVE_STDARG_H
-#endif
-
-#ifdef STDC
-#  ifndef Z_SOLO
-#    include <sys/types.h>      /* for off_t */
-#  endif
-#endif
-
-#if defined(STDC) || defined(Z_HAVE_STDARG_H)
-#  ifndef Z_SOLO
-#    include <stdarg.h>         /* for va_list */
-#  endif
-#endif
-
-#ifdef _WIN32
-#  ifndef Z_SOLO
-#    include <stddef.h>         /* for wchar_t */
-#  endif
-#endif
-
-/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
- * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
- * though the former does not conform to the LFS document), but considering
- * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
- * equivalently requesting no 64-bit operations
- */
-#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1
-#  undef _LARGEFILE64_SOURCE
-#endif
-
-#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H)
-#  define Z_HAVE_UNISTD_H
-#endif
-#ifndef Z_SOLO
-#  if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE)
-#    include <unistd.h>         /* for SEEK_*, off_t, and _LFS64_LARGEFILE */
-#    ifdef VMS
-#      include <unixio.h>       /* for off_t */
-#    endif
-#    ifndef z_off_t
-#      define z_off_t off_t
-#    endif
-#  endif
-#endif
-
-#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
-#  define Z_LFS64
-#endif
-
-#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
-#  define Z_LARGE64
-#endif
-
-#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64)
-#  define Z_WANT64
-#endif
-
-#if !defined(SEEK_SET) && !defined(Z_SOLO)
-#  define SEEK_SET        0       /* Seek from beginning of file.  */
-#  define SEEK_CUR        1       /* Seek from current position.  */
-#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
-#endif
-
-#ifndef z_off_t
-#  define z_off_t long
-#endif
-
-#if !defined(_WIN32) && defined(Z_LARGE64)
-#  define z_off64_t off64_t
-#else
-#  if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO)
-#    define z_off64_t __int64
-#  else
-#    define z_off64_t z_off_t
-#  endif
-#endif
-
-/* MVS linker does not support external names larger than 8 bytes */
-#if defined(__MVS__)
-  #pragma map(deflateInit_,"DEIN")
-  #pragma map(deflateInit2_,"DEIN2")
-  #pragma map(deflateEnd,"DEEND")
-  #pragma map(deflateBound,"DEBND")
-  #pragma map(inflateInit_,"ININ")
-  #pragma map(inflateInit2_,"ININ2")
-  #pragma map(inflateEnd,"INEND")
-  #pragma map(inflateSync,"INSY")
-  #pragma map(inflateSetDictionary,"INSEDI")
-  #pragma map(compressBound,"CMBND")
-  #pragma map(inflate_table,"INTABL")
-  #pragma map(inflate_fast,"INFA")
-  #pragma map(inflate_copyright,"INCOPY")
-#endif
-
-#endif /* ZCONF_H */
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/zcrc32.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,449 +0,0 @@
-/*
- * 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.
- */
-
-/* crc32.c -- compute the CRC-32 of a data stream
- * Copyright (C) 1995-2006, 2010, 2011, 2012 Mark Adler
- * For conditions of distribution and use, see copyright notice in zlib.h
- *
- * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
- * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
- * tables for updating the shift register in one step with three exclusive-ors
- * instead of four steps with four exclusive-ors.  This results in about a
- * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
- */
-
-/* @(#) $Id$ */
-
-/*
-  Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
-  protection on the static variables used to control the first-use generation
-  of the crc tables.  Therefore, if you #define DYNAMIC_CRC_TABLE, you should
-  first call get_crc_table() to initialize the tables before allowing more than
-  one thread to use crc32().
-
-  DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h.
- */
-
-#ifdef MAKECRCH
-#  include <stdio.h>
-#  ifndef DYNAMIC_CRC_TABLE
-#    define DYNAMIC_CRC_TABLE
-#  endif /* !DYNAMIC_CRC_TABLE */
-#endif /* MAKECRCH */
-
-#include "zutil.h"      /* for STDC and FAR definitions */
-
-#define local static
-
-/* Definitions for doing the crc four data bytes at a time. */
-#if !defined(NOBYFOUR) && defined(Z_U4)
-#  define BYFOUR
-#endif
-#ifdef BYFOUR
-   local unsigned long crc32_little OF((unsigned long,
-                        const unsigned char FAR *, unsigned));
-   local unsigned long crc32_big OF((unsigned long,
-                        const unsigned char FAR *, unsigned));
-#  define TBLS 8
-#else
-#  define TBLS 1
-#endif /* BYFOUR */
-
-/* Local functions for crc concatenation */
-local unsigned long gf2_matrix_times OF((unsigned long *mat,
-                                         unsigned long vec));
-local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
-local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2));
-
-
-#ifdef DYNAMIC_CRC_TABLE
-
-local volatile int crc_table_empty = 1;
-local z_crc_t FAR crc_table[TBLS][256];
-local void make_crc_table OF((void));
-#ifdef MAKECRCH
-   local void write_table OF((FILE *, const z_crc_t FAR *));
-#endif /* MAKECRCH */
-/*
-  Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
-  x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
-
-  Polynomials over GF(2) are represented in binary, one bit per coefficient,
-  with the lowest powers in the most significant bit.  Then adding polynomials
-  is just exclusive-or, and multiplying a polynomial by x is a right shift by
-  one.  If we call the above polynomial p, and represent a byte as the
-  polynomial q, also with the lowest power in the most significant bit (so the
-  byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
-  where a mod b means the remainder after dividing a by b.
-
-  This calculation is done using the shift-register method of multiplying and
-  taking the remainder.  The register is initialized to zero, and for each
-  incoming bit, x^32 is added mod p to the register if the bit is a one (where
-  x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
-  x (which is shifting right by one and adding x^32 mod p if the bit shifted
-  out is a one).  We start with the highest power (least significant bit) of
-  q and repeat for all eight bits of q.
-
-  The first table is simply the CRC of all possible eight bit values.  This is
-  all the information needed to generate CRCs on data a byte at a time for all
-  combinations of CRC register values and incoming bytes.  The remaining tables
-  allow for word-at-a-time CRC calculation for both big-endian and little-
-  endian machines, where a word is four bytes.
-*/
-local void make_crc_table()
-{
-    z_crc_t c;
-    int n, k;
-    z_crc_t poly;                       /* polynomial exclusive-or pattern */
-    /* terms of polynomial defining this crc (except x^32): */
-    static volatile int first = 1;      /* flag to limit concurrent making */
-    static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
-
-    /* See if another task is already doing this (not thread-safe, but better
-       than nothing -- significantly reduces duration of vulnerability in
-       case the advice about DYNAMIC_CRC_TABLE is ignored) */
-    if (first) {
-        first = 0;
-
-        /* make exclusive-or pattern from polynomial (0xedb88320UL) */
-        poly = 0;
-        for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++)
-            poly |= (z_crc_t)1 << (31 - p[n]);
-
-        /* generate a crc for every 8-bit value */
-        for (n = 0; n < 256; n++) {
-            c = (z_crc_t)n;
-            for (k = 0; k < 8; k++)
-                c = c & 1 ? poly ^ (c >> 1) : c >> 1;
-            crc_table[0][n] = c;
-        }
-
-#ifdef BYFOUR
-        /* generate crc for each value followed by one, two, and three zeros,
-           and then the byte reversal of those as well as the first table */
-        for (n = 0; n < 256; n++) {
-            c = crc_table[0][n];
-            crc_table[4][n] = ZSWAP32(c);
-            for (k = 1; k < 4; k++) {
-                c = crc_table[0][c & 0xff] ^ (c >> 8);
-                crc_table[k][n] = c;
-                crc_table[k + 4][n] = ZSWAP32(c);
-            }
-        }
-#endif /* BYFOUR */
-
-        crc_table_empty = 0;
-    }
-    else {      /* not first */
-        /* wait for the other guy to finish (not efficient, but rare) */
-        while (crc_table_empty)
-            ;
-    }
-
-#ifdef MAKECRCH
-    /* write out CRC tables to crc32.h */
-    {
-        FILE *out;
-
-        out = fopen("crc32.h", "w");
-        if (out == NULL) return;
-        fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
-        fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
-        fprintf(out, "local const z_crc_t FAR ");
-        fprintf(out, "crc_table[TBLS][256] =\n{\n  {\n");
-        write_table(out, crc_table[0]);
-#  ifdef BYFOUR
-        fprintf(out, "#ifdef BYFOUR\n");
-        for (k = 1; k < 8; k++) {
-            fprintf(out, "  },\n  {\n");
-            write_table(out, crc_table[k]);
-        }
-        fprintf(out, "#endif\n");
-#  endif /* BYFOUR */
-        fprintf(out, "  }\n};\n");
-        fclose(out);
-    }
-#endif /* MAKECRCH */
-}
-
-#ifdef MAKECRCH
-local void write_table(out, table)
-    FILE *out;
-    const z_crc_t FAR *table;
-{
-    int n;
-
-    for (n = 0; n < 256; n++)
-        fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : "    ",
-                (unsigned long)(table[n]),
-                n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
-}
-#endif /* MAKECRCH */
-
-#else /* !DYNAMIC_CRC_TABLE */
-/* ========================================================================
- * Tables of CRC-32s of all single-byte values, made by make_crc_table().
- */
-#include "crc32.h"
-#endif /* DYNAMIC_CRC_TABLE */
-
-/* =========================================================================
- * This function can be used by asm versions of crc32()
- */
-const z_crc_t FAR * ZEXPORT get_crc_table()
-{
-#ifdef DYNAMIC_CRC_TABLE
-    if (crc_table_empty)
-        make_crc_table();
-#endif /* DYNAMIC_CRC_TABLE */
-    return (const z_crc_t FAR *)crc_table;
-}
-
-/* ========================================================================= */
-#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
-#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
-
-/* ========================================================================= */
-uLong ZEXPORT crc32(crc, buf, len)
-    uLong crc;
-    const unsigned char FAR *buf;
-    uInt len;
-{
-    if (buf == Z_NULL) return 0UL;
-
-#ifdef DYNAMIC_CRC_TABLE
-    if (crc_table_empty)
-        make_crc_table();
-#endif /* DYNAMIC_CRC_TABLE */
-
-#ifdef BYFOUR
-    if (sizeof(void *) == sizeof(ptrdiff_t)) {
-        z_crc_t endian;
-
-        endian = 1;
-        if (*((unsigned char *)(&endian)))
-            return (uLong)crc32_little(crc, buf, len);
-        else
-            return (uLong)crc32_big(crc, buf, len);
-    }
-#endif /* BYFOUR */
-    crc = crc ^ 0xffffffffUL;
-    while (len >= 8) {
-        DO8;
-        len -= 8;
-    }
-    if (len) do {
-        DO1;
-    } while (--len);
-    return crc ^ 0xffffffffUL;
-}
-
-#ifdef BYFOUR
-
-/* ========================================================================= */
-#define DOLIT4 c ^= *buf4++; \
-        c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
-            crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
-#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
-
-/* ========================================================================= */
-local unsigned long crc32_little(crc, buf, len)
-    unsigned long crc;
-    const unsigned char FAR *buf;
-    unsigned len;
-{
-    register z_crc_t c;
-    register const z_crc_t FAR *buf4;
-
-    c = (z_crc_t)crc;
-    c = ~c;
-    while (len && ((ptrdiff_t)buf & 3)) {
-        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
-        len--;
-    }
-
-    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
-    while (len >= 32) {
-        DOLIT32;
-        len -= 32;
-    }
-    while (len >= 4) {
-        DOLIT4;
-        len -= 4;
-    }
-    buf = (const unsigned char FAR *)buf4;
-
-    if (len) do {
-        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
-    } while (--len);
-    c = ~c;
-    return (unsigned long)c;
-}
-
-/* ========================================================================= */
-#define DOBIG4 c ^= *++buf4; \
-        c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
-            crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
-#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
-
-/* ========================================================================= */
-local unsigned long crc32_big(crc, buf, len)
-    unsigned long crc;
-    const unsigned char FAR *buf;
-    unsigned len;
-{
-    register z_crc_t c;
-    register const z_crc_t FAR *buf4;
-
-    c = ZSWAP32((z_crc_t)crc);
-    c = ~c;
-    while (len && ((ptrdiff_t)buf & 3)) {
-        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
-        len--;
-    }
-
-    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
-    buf4--;
-    while (len >= 32) {
-        DOBIG32;
-        len -= 32;
-    }
-    while (len >= 4) {
-        DOBIG4;
-        len -= 4;
-    }
-    buf4++;
-    buf = (const unsigned char FAR *)buf4;
-
-    if (len) do {
-        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
-    } while (--len);
-    c = ~c;
-    return (unsigned long)(ZSWAP32(c));
-}
-
-#endif /* BYFOUR */
-
-#define GF2_DIM 32      /* dimension of GF(2) vectors (length of CRC) */
-
-/* ========================================================================= */
-local unsigned long gf2_matrix_times(mat, vec)
-    unsigned long *mat;
-    unsigned long vec;
-{
-    unsigned long sum;
-
-    sum = 0;
-    while (vec) {
-        if (vec & 1)
-            sum ^= *mat;
-        vec >>= 1;
-        mat++;
-    }
-    return sum;
-}
-
-/* ========================================================================= */
-local void gf2_matrix_square(square, mat)
-    unsigned long *square;
-    unsigned long *mat;
-{
-    int n;
-
-    for (n = 0; n < GF2_DIM; n++)
-        square[n] = gf2_matrix_times(mat, mat[n]);
-}
-
-/* ========================================================================= */
-local uLong crc32_combine_(crc1, crc2, len2)
-    uLong crc1;
-    uLong crc2;
-    z_off64_t len2;
-{
-    int n;
-    unsigned long row;
-    unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */
-    unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */
-
-    /* degenerate case (also disallow negative lengths) */
-    if (len2 <= 0)
-        return crc1;
-
-    /* put operator for one zero bit in odd */
-    odd[0] = 0xedb88320UL;          /* CRC-32 polynomial */
-    row = 1;
-    for (n = 1; n < GF2_DIM; n++) {
-        odd[n] = row;
-        row <<= 1;
-    }
-
-    /* put operator for two zero bits in even */
-    gf2_matrix_square(even, odd);
-
-    /* put operator for four zero bits in odd */
-    gf2_matrix_square(odd, even);
-
-    /* apply len2 zeros to crc1 (first square will put the operator for one
-       zero byte, eight zero bits, in even) */
-    do {
-        /* apply zeros operator for this bit of len2 */
-        gf2_matrix_square(even, odd);
-        if (len2 & 1)
-            crc1 = gf2_matrix_times(even, crc1);
-        len2 >>= 1;
-
-        /* if no more bits set, then done */
-        if (len2 == 0)
-            break;
-
-        /* another iteration of the loop with odd and even swapped */
-        gf2_matrix_square(odd, even);
-        if (len2 & 1)
-            crc1 = gf2_matrix_times(odd, crc1);
-        len2 >>= 1;
-
-        /* if no more bits set, then done */
-    } while (len2 != 0);
-
-    /* return combined crc */
-    crc1 ^= crc2;
-    return crc1;
-}
-
-/* ========================================================================= */
-uLong ZEXPORT crc32_combine(crc1, crc2, len2)
-    uLong crc1;
-    uLong crc2;
-    z_off_t len2;
-{
-    return crc32_combine_(crc1, crc2, len2);
-}
-
-uLong ZEXPORT crc32_combine64(crc1, crc2, len2)
-    uLong crc1;
-    uLong crc2;
-    z_off64_t len2;
-{
-    return crc32_combine_(crc1, crc2, len2);
-}
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/zlib.h	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,1792 +0,0 @@
-/*
- * 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.
- */
-
-/* zlib.h -- interface of the 'zlib' general purpose compression library
-  version 1.2.8, April 28th, 2013
-
-  Copyright (C) 1995-2013 Jean-loup Gailly and Mark Adler
-
-  This software is provided 'as-is', without any express or implied
-  warranty.  In no event will the authors be held liable for any damages
-  arising from the use of this software.
-
-  Permission is granted to anyone to use this software for any purpose,
-  including commercial applications, and to alter it and redistribute it
-  freely, subject to the following restrictions:
-
-  1. The origin of this software must not be misrepresented; you must not
-     claim that you wrote the original software. If you use this software
-     in a product, an acknowledgment in the product documentation would be
-     appreciated but is not required.
-  2. Altered source versions must be plainly marked as such, and must not be
-     misrepresented as being the original software.
-  3. This notice may not be removed or altered from any source distribution.
-
-  Jean-loup Gailly        Mark Adler
-  jloup@gzip.org          madler@alumni.caltech.edu
-
-
-  The data format used by the zlib library is described by RFCs (Request for
-  Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
-  (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
-*/
-
-#ifndef ZLIB_H
-#define ZLIB_H
-
-#include "zconf.h"
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#define ZLIB_VERSION "1.2.8"
-#define ZLIB_VERNUM 0x1280
-#define ZLIB_VER_MAJOR 1
-#define ZLIB_VER_MINOR 2
-#define ZLIB_VER_REVISION 8
-#define ZLIB_VER_SUBREVISION 0
-
-/*
-    The 'zlib' compression library provides in-memory compression and
-  decompression functions, including integrity checks of the uncompressed data.
-  This version of the library supports only one compression method (deflation)
-  but other algorithms will be added later and will have the same stream
-  interface.
-
-    Compression can be done in a single step if the buffers are large enough,
-  or can be done by repeated calls of the compression function.  In the latter
-  case, the application must provide more input and/or consume the output
-  (providing more output space) before each call.
-
-    The compressed data format used by default by the in-memory functions is
-  the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
-  around a deflate stream, which is itself documented in RFC 1951.
-
-    The library also supports reading and writing files in gzip (.gz) format
-  with an interface similar to that of stdio using the functions that start
-  with "gz".  The gzip format is different from the zlib format.  gzip is a
-  gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
-
-    This library can optionally read and write gzip streams in memory as well.
-
-    The zlib format was designed to be compact and fast for use in memory
-  and on communications channels.  The gzip format was designed for single-
-  file compression on file systems, has a larger header than zlib to maintain
-  directory information, and uses a different, slower check method than zlib.
-
-    The library does not install any signal handler.  The decoder checks
-  the consistency of the compressed data, so the library should never crash
-  even in case of corrupted input.
-*/
-
-typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
-typedef void   (*free_func)  OF((voidpf opaque, voidpf address));
-
-struct internal_state;
-
-typedef struct z_stream_s {
-    z_const Bytef *next_in;     /* next input byte */
-    uInt     avail_in;  /* number of bytes available at next_in */
-    uLong    total_in;  /* total number of input bytes read so far */
-
-    Bytef    *next_out; /* next output byte should be put there */
-    uInt     avail_out; /* remaining free space at next_out */
-    uLong    total_out; /* total number of bytes output so far */
-
-    z_const char *msg;  /* last error message, NULL if no error */
-    struct internal_state FAR *state; /* not visible by applications */
-
-    alloc_func zalloc;  /* used to allocate the internal state */
-    free_func  zfree;   /* used to free the internal state */
-    voidpf     opaque;  /* private data object passed to zalloc and zfree */
-
-    int     data_type;  /* best guess about the data type: binary or text */
-    uLong   adler;      /* adler32 value of the uncompressed data */
-    uLong   reserved;   /* reserved for future use */
-} z_stream;
-
-typedef z_stream FAR *z_streamp;
-
-/*
-     gzip header information passed to and from zlib routines.  See RFC 1952
-  for more details on the meanings of these fields.
-*/
-typedef struct gz_header_s {
-    int     text;       /* true if compressed data believed to be text */
-    uLong   time;       /* modification time */
-    int     xflags;     /* extra flags (not used when writing a gzip file) */
-    int     os;         /* operating system */
-    Bytef   *extra;     /* pointer to extra field or Z_NULL if none */
-    uInt    extra_len;  /* extra field length (valid if extra != Z_NULL) */
-    uInt    extra_max;  /* space at extra (only when reading header) */
-    Bytef   *name;      /* pointer to zero-terminated file name or Z_NULL */
-    uInt    name_max;   /* space at name (only when reading header) */
-    Bytef   *comment;   /* pointer to zero-terminated comment or Z_NULL */
-    uInt    comm_max;   /* space at comment (only when reading header) */
-    int     hcrc;       /* true if there was or will be a header crc */
-    int     done;       /* true when done reading gzip header (not used
-                           when writing a gzip file) */
-} gz_header;
-
-typedef gz_header FAR *gz_headerp;
-
-/*
-     The application must update next_in and avail_in when avail_in has dropped
-   to zero.  It must update next_out and avail_out when avail_out has dropped
-   to zero.  The application must initialize zalloc, zfree and opaque before
-   calling the init function.  All other fields are set by the compression
-   library and must not be updated by the application.
-
-     The opaque value provided by the application will be passed as the first
-   parameter for calls of zalloc and zfree.  This can be useful for custom
-   memory management.  The compression library attaches no meaning to the
-   opaque value.
-
-     zalloc must return Z_NULL if there is not enough memory for the object.
-   If zlib is used in a multi-threaded application, zalloc and zfree must be
-   thread safe.
-
-     On 16-bit systems, the functions zalloc and zfree must be able to allocate
-   exactly 65536 bytes, but will not be required to allocate more than this if
-   the symbol MAXSEG_64K is defined (see zconf.h).  WARNING: On MSDOS, pointers
-   returned by zalloc for objects of exactly 65536 bytes *must* have their
-   offset normalized to zero.  The default allocation function provided by this
-   library ensures this (see zutil.c).  To reduce memory requirements and avoid
-   any allocation of 64K objects, at the expense of compression ratio, compile
-   the library with -DMAX_WBITS=14 (see zconf.h).
-
-     The fields total_in and total_out can be used for statistics or progress
-   reports.  After compression, total_in holds the total size of the
-   uncompressed data and may be saved for use in the decompressor (particularly
-   if the decompressor wants to decompress everything in a single step).
-*/
-
-                        /* constants */
-
-#define Z_NO_FLUSH      0
-#define Z_PARTIAL_FLUSH 1
-#define Z_SYNC_FLUSH    2
-#define Z_FULL_FLUSH    3
-#define Z_FINISH        4
-#define Z_BLOCK         5
-#define Z_TREES         6
-/* Allowed flush values; see deflate() and inflate() below for details */
-
-#define Z_OK            0
-#define Z_STREAM_END    1
-#define Z_NEED_DICT     2
-#define Z_ERRNO        (-1)
-#define Z_STREAM_ERROR (-2)
-#define Z_DATA_ERROR   (-3)
-#define Z_MEM_ERROR    (-4)
-#define Z_BUF_ERROR    (-5)
-#define Z_VERSION_ERROR (-6)
-/* Return codes for the compression/decompression functions. Negative values
- * are errors, positive values are used for special but normal events.
- */
-
-#define Z_NO_COMPRESSION         0
-#define Z_BEST_SPEED             1
-#define Z_BEST_COMPRESSION       9
-#define Z_DEFAULT_COMPRESSION  (-1)
-/* compression levels */
-
-#define Z_FILTERED            1
-#define Z_HUFFMAN_ONLY        2
-#define Z_RLE                 3
-#define Z_FIXED               4
-#define Z_DEFAULT_STRATEGY    0
-/* compression strategy; see deflateInit2() below for details */
-
-#define Z_BINARY   0
-#define Z_TEXT     1
-#define Z_ASCII    Z_TEXT   /* for compatibility with 1.2.2 and earlier */
-#define Z_UNKNOWN  2
-/* Possible values of the data_type field (though see inflate()) */
-
-#define Z_DEFLATED   8
-/* The deflate compression method (the only one supported in this version) */
-
-#define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
-
-#define zlib_version zlibVersion()
-/* for compatibility with versions < 1.0.2 */
-
-
-                        /* basic functions */
-
-ZEXTERN const char * ZEXPORT zlibVersion OF((void));
-/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
-   If the first character differs, the library code actually used is not
-   compatible with the zlib.h header file used by the application.  This check
-   is automatically made by deflateInit and inflateInit.
- */
-
-/*
-ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
-
-     Initializes the internal stream state for compression.  The fields
-   zalloc, zfree and opaque must be initialized before by the caller.  If
-   zalloc and zfree are set to Z_NULL, deflateInit updates them to use default
-   allocation functions.
-
-     The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
-   1 gives best speed, 9 gives best compression, 0 gives no compression at all
-   (the input data is simply copied a block at a time).  Z_DEFAULT_COMPRESSION
-   requests a default compromise between speed and compression (currently
-   equivalent to level 6).
-
-     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
-   memory, Z_STREAM_ERROR if level is not a valid compression level, or
-   Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
-   with the version assumed by the caller (ZLIB_VERSION).  msg is set to null
-   if there is no error message.  deflateInit does not perform any compression:
-   this will be done by deflate().
-*/
-
-
-ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
-/*
-    deflate compresses as much data as possible, and stops when the input
-  buffer becomes empty or the output buffer becomes full.  It may introduce
-  some output latency (reading input without producing any output) except when
-  forced to flush.
-
-    The detailed semantics are as follows.  deflate performs one or both of the
-  following actions:
-
-  - Compress more input starting at next_in and update next_in and avail_in
-    accordingly.  If not all input can be processed (because there is not
-    enough room in the output buffer), next_in and avail_in are updated and
-    processing will resume at this point for the next call of deflate().
-
-  - Provide more output starting at next_out and update next_out and avail_out
-    accordingly.  This action is forced if the parameter flush is non zero.
-    Forcing flush frequently degrades the compression ratio, so this parameter
-    should be set only when necessary (in interactive applications).  Some
-    output may be provided even if flush is not set.
-
-    Before the call of deflate(), the application should ensure that at least
-  one of the actions is possible, by providing more input and/or consuming more
-  output, and updating avail_in or avail_out accordingly; avail_out should
-  never be zero before the call.  The application can consume the compressed
-  output when it wants, for example when the output buffer is full (avail_out
-  == 0), or after each call of deflate().  If deflate returns Z_OK and with
-  zero avail_out, it must be called again after making room in the output
-  buffer because there might be more output pending.
-
-    Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
-  decide how much data to accumulate before producing output, in order to
-  maximize compression.
-
-    If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
-  flushed to the output buffer and the output is aligned on a byte boundary, so
-  that the decompressor can get all input data available so far.  (In
-  particular avail_in is zero after the call if enough output space has been
-  provided before the call.) Flushing may degrade compression for some
-  compression algorithms and so it should be used only when necessary.  This
-  completes the current deflate block and follows it with an empty stored block
-  that is three bits plus filler bits to the next byte, followed by four bytes
-  (00 00 ff ff).
-
-    If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
-  output buffer, but the output is not aligned to a byte boundary.  All of the
-  input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
-  This completes the current deflate block and follows it with an empty fixed
-  codes block that is 10 bits long.  This assures that enough bytes are output
-  in order for the decompressor to finish the block before the empty fixed code
-  block.
-
-    If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
-  for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
-  seven bits of the current block are held to be written as the next byte after
-  the next deflate block is completed.  In this case, the decompressor may not
-  be provided enough bits at this point in order to complete decompression of
-  the data provided so far to the compressor.  It may need to wait for the next
-  block to be emitted.  This is for advanced applications that need to control
-  the emission of deflate blocks.
-
-    If flush is set to Z_FULL_FLUSH, all output is flushed as with
-  Z_SYNC_FLUSH, and the compression state is reset so that decompression can
-  restart from this point if previous compressed data has been damaged or if
-  random access is desired.  Using Z_FULL_FLUSH too often can seriously degrade
-  compression.
-
-    If deflate returns with avail_out == 0, this function must be called again
-  with the same value of the flush parameter and more output space (updated
-  avail_out), until the flush is complete (deflate returns with non-zero
-  avail_out).  In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
-  avail_out is greater than six to avoid repeated flush markers due to
-  avail_out == 0 on return.
-
-    If the parameter flush is set to Z_FINISH, pending input is processed,
-  pending output is flushed and deflate returns with Z_STREAM_END if there was
-  enough output space; if deflate returns with Z_OK, this function must be
-  called again with Z_FINISH and more output space (updated avail_out) but no
-  more input data, until it returns with Z_STREAM_END or an error.  After
-  deflate has returned Z_STREAM_END, the only possible operations on the stream
-  are deflateReset or deflateEnd.
-
-    Z_FINISH can be used immediately after deflateInit if all the compression
-  is to be done in a single step.  In this case, avail_out must be at least the
-  value returned by deflateBound (see below).  Then deflate is guaranteed to
-  return Z_STREAM_END.  If not enough output space is provided, deflate will
-  not return Z_STREAM_END, and it must be called again as described above.
-
-    deflate() sets strm->adler to the adler32 checksum of all input read
-  so far (that is, total_in bytes).
-
-    deflate() may update strm->data_type if it can make a good guess about
-  the input data type (Z_BINARY or Z_TEXT).  In doubt, the data is considered
-  binary.  This field is only for information purposes and does not affect the
-  compression algorithm in any manner.
-
-    deflate() returns Z_OK if some progress has been made (more input
-  processed or more output produced), Z_STREAM_END if all input has been
-  consumed and all output has been produced (only when flush is set to
-  Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
-  if next_in or next_out was Z_NULL), Z_BUF_ERROR if no progress is possible
-  (for example avail_in or avail_out was zero).  Note that Z_BUF_ERROR is not
-  fatal, and deflate() can be called again with more input and more output
-  space to continue compressing.
-*/
-
-
-ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
-/*
-     All dynamically allocated data structures for this stream are freed.
-   This function discards any unprocessed input and does not flush any pending
-   output.
-
-     deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
-   stream state was inconsistent, Z_DATA_ERROR if the stream was freed
-   prematurely (some input or output was discarded).  In the error case, msg
-   may be set but then points to a static string (which must not be
-   deallocated).
-*/
-
-
-/*
-ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
-
-     Initializes the internal stream state for decompression.  The fields
-   next_in, avail_in, zalloc, zfree and opaque must be initialized before by
-   the caller.  If next_in is not Z_NULL and avail_in is large enough (the
-   exact value depends on the compression method), inflateInit determines the
-   compression method from the zlib header and allocates all data structures
-   accordingly; otherwise the allocation will be deferred to the first call of
-   inflate.  If zalloc and zfree are set to Z_NULL, inflateInit updates them to
-   use default allocation functions.
-
-     inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
-   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
-   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
-   invalid, such as a null pointer to the structure.  msg is set to null if
-   there is no error message.  inflateInit does not perform any decompression
-   apart from possibly reading the zlib header if present: actual decompression
-   will be done by inflate().  (So next_in and avail_in may be modified, but
-   next_out and avail_out are unused and unchanged.) The current implementation
-   of inflateInit() does not process any header information -- that is deferred
-   until inflate() is called.
-*/
-
-
-ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
-/*
-    inflate decompresses as much data as possible, and stops when the input
-  buffer becomes empty or the output buffer becomes full.  It may introduce
-  some output latency (reading input without producing any output) except when
-  forced to flush.
-
-  The detailed semantics are as follows.  inflate performs one or both of the
-  following actions:
-
-  - Decompress more input starting at next_in and update next_in and avail_in
-    accordingly.  If not all input can be processed (because there is not
-    enough room in the output buffer), next_in is updated and processing will
-    resume at this point for the next call of inflate().
-
-  - Provide more output starting at next_out and update next_out and avail_out
-    accordingly.  inflate() provides as much output as possible, until there is
-    no more input data or no more space in the output buffer (see below about
-    the flush parameter).
-
-    Before the call of inflate(), the application should ensure that at least
-  one of the actions is possible, by providing more input and/or consuming more
-  output, and updating the next_* and avail_* values accordingly.  The
-  application can consume the uncompressed output when it wants, for example
-  when the output buffer is full (avail_out == 0), or after each call of
-  inflate().  If inflate returns Z_OK and with zero avail_out, it must be
-  called again after making room in the output buffer because there might be
-  more output pending.
-
-    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
-  Z_BLOCK, or Z_TREES.  Z_SYNC_FLUSH requests that inflate() flush as much
-  output as possible to the output buffer.  Z_BLOCK requests that inflate()
-  stop if and when it gets to the next deflate block boundary.  When decoding
-  the zlib or gzip format, this will cause inflate() to return immediately
-  after the header and before the first block.  When doing a raw inflate,
-  inflate() will go ahead and process the first block, and will return when it
-  gets to the end of that block, or when it runs out of data.
-
-    The Z_BLOCK option assists in appending to or combining deflate streams.
-  Also to assist in this, on return inflate() will set strm->data_type to the
-  number of unused bits in the last byte taken from strm->next_in, plus 64 if
-  inflate() is currently decoding the last block in the deflate stream, plus
-  128 if inflate() returned immediately after decoding an end-of-block code or
-  decoding the complete header up to just before the first byte of the deflate
-  stream.  The end-of-block will not be indicated until all of the uncompressed
-  data from that block has been written to strm->next_out.  The number of
-  unused bits may in general be greater than seven, except when bit 7 of
-  data_type is set, in which case the number of unused bits will be less than
-  eight.  data_type is set as noted here every time inflate() returns for all
-  flush options, and so can be used to determine the amount of currently
-  consumed input in bits.
-
-    The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
-  end of each deflate block header is reached, before any actual data in that
-  block is decoded.  This allows the caller to determine the length of the
-  deflate block header for later use in random access within a deflate block.
-  256 is added to the value of strm->data_type when inflate() returns
-  immediately after reaching the end of the deflate block header.
-
-    inflate() should normally be called until it returns Z_STREAM_END or an
-  error.  However if all decompression is to be performed in a single step (a
-  single call of inflate), the parameter flush should be set to Z_FINISH.  In
-  this case all pending input is processed and all pending output is flushed;
-  avail_out must be large enough to hold all of the uncompressed data for the
-  operation to complete.  (The size of the uncompressed data may have been
-  saved by the compressor for this purpose.) The use of Z_FINISH is not
-  required to perform an inflation in one step.  However it may be used to
-  inform inflate that a faster approach can be used for the single inflate()
-  call.  Z_FINISH also informs inflate to not maintain a sliding window if the
-  stream completes, which reduces inflate's memory footprint.  If the stream
-  does not complete, either because not all of the stream is provided or not
-  enough output space is provided, then a sliding window will be allocated and
-  inflate() can be called again to continue the operation as if Z_NO_FLUSH had
-  been used.
-
-     In this implementation, inflate() always flushes as much output as
-  possible to the output buffer, and always uses the faster approach on the
-  first call.  So the effects of the flush parameter in this implementation are
-  on the return value of inflate() as noted below, when inflate() returns early
-  when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of
-  memory for a sliding window when Z_FINISH is used.
-
-     If a preset dictionary is needed after this call (see inflateSetDictionary
-  below), inflate sets strm->adler to the Adler-32 checksum of the dictionary
-  chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
-  strm->adler to the Adler-32 checksum of all output produced so far (that is,
-  total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
-  below.  At the end of the stream, inflate() checks that its computed adler32
-  checksum is equal to that saved by the compressor and returns Z_STREAM_END
-  only if the checksum is correct.
-
-    inflate() can decompress and check either zlib-wrapped or gzip-wrapped
-  deflate data.  The header type is detected automatically, if requested when
-  initializing with inflateInit2().  Any information contained in the gzip
-  header is not retained, so applications that need that information should
-  instead use raw inflate, see inflateInit2() below, or inflateBack() and
-  perform their own processing of the gzip header and trailer.  When processing
-  gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
-  producted so far.  The CRC-32 is checked against the gzip trailer.
-
-    inflate() returns Z_OK if some progress has been made (more input processed
-  or more output produced), Z_STREAM_END if the end of the compressed data has
-  been reached and all uncompressed output has been produced, Z_NEED_DICT if a
-  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
-  corrupted (input stream not conforming to the zlib format or incorrect check
-  value), Z_STREAM_ERROR if the stream structure was inconsistent (for example
-  next_in or next_out was Z_NULL), Z_MEM_ERROR if there was not enough memory,
-  Z_BUF_ERROR if no progress is possible or if there was not enough room in the
-  output buffer when Z_FINISH is used.  Note that Z_BUF_ERROR is not fatal, and
-  inflate() can be called again with more input and more output space to
-  continue decompressing.  If Z_DATA_ERROR is returned, the application may
-  then call inflateSync() to look for a good compression block if a partial
-  recovery of the data is desired.
-*/
-
-
-ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
-/*
-     All dynamically allocated data structures for this stream are freed.
-   This function discards any unprocessed input and does not flush any pending
-   output.
-
-     inflateEnd returns Z_OK if success, Z_STREAM_ERROR if the stream state
-   was inconsistent.  In the error case, msg may be set but then points to a
-   static string (which must not be deallocated).
-*/
-
-
-                        /* Advanced functions */
-
-/*
-    The following functions are needed only in some special applications.
-*/
-
-/*
-ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
-                                     int  level,
-                                     int  method,
-                                     int  windowBits,
-                                     int  memLevel,
-                                     int  strategy));
-
-     This is another version of deflateInit with more compression options.  The
-   fields next_in, zalloc, zfree and opaque must be initialized before by the
-   caller.
-
-     The method parameter is the compression method.  It must be Z_DEFLATED in
-   this version of the library.
-
-     The windowBits parameter is the base two logarithm of the window size
-   (the size of the history buffer).  It should be in the range 8..15 for this
-   version of the library.  Larger values of this parameter result in better
-   compression at the expense of memory usage.  The default value is 15 if
-   deflateInit is used instead.
-
-     windowBits can also be -8..-15 for raw deflate.  In this case, -windowBits
-   determines the window size.  deflate() will then generate raw deflate data
-   with no zlib header or trailer, and will not compute an adler32 check value.
-
-     windowBits can also be greater than 15 for optional gzip encoding.  Add
-   16 to windowBits to write a simple gzip header and trailer around the
-   compressed data instead of a zlib wrapper.  The gzip header will have no
-   file name, no extra data, no comment, no modification time (set to zero), no
-   header crc, and the operating system will be set to 255 (unknown).  If a
-   gzip stream is being written, strm->adler is a crc32 instead of an adler32.
-
-     The memLevel parameter specifies how much memory should be allocated
-   for the internal compression state.  memLevel=1 uses minimum memory but is
-   slow and reduces compression ratio; memLevel=9 uses maximum memory for
-   optimal speed.  The default value is 8.  See zconf.h for total memory usage
-   as a function of windowBits and memLevel.
-
-     The strategy parameter is used to tune the compression algorithm.  Use the
-   value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
-   filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
-   string match), or Z_RLE to limit match distances to one (run-length
-   encoding).  Filtered data consists mostly of small values with a somewhat
-   random distribution.  In this case, the compression algorithm is tuned to
-   compress them better.  The effect of Z_FILTERED is to force more Huffman
-   coding and less string matching; it is somewhat intermediate between
-   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as
-   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The
-   strategy parameter only affects the compression ratio but not the
-   correctness of the compressed output even if it is not set appropriately.
-   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
-   decoder for special applications.
-
-     deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
-   memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
-   method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
-   incompatible with the version assumed by the caller (ZLIB_VERSION).  msg is
-   set to null if there is no error message.  deflateInit2 does not perform any
-   compression: this will be done by deflate().
-*/
-
-ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
-                                             const Bytef *dictionary,
-                                             uInt  dictLength));
-/*
-     Initializes the compression dictionary from the given byte sequence
-   without producing any compressed output.  When using the zlib format, this
-   function must be called immediately after deflateInit, deflateInit2 or
-   deflateReset, and before any call of deflate.  When doing raw deflate, this
-   function must be called either before any call of deflate, or immediately
-   after the completion of a deflate block, i.e. after all input has been
-   consumed and all output has been delivered when using any of the flush
-   options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH.  The
-   compressor and decompressor must use exactly the same dictionary (see
-   inflateSetDictionary).
-
-     The dictionary should consist of strings (byte sequences) that are likely
-   to be encountered later in the data to be compressed, with the most commonly
-   used strings preferably put towards the end of the dictionary.  Using a
-   dictionary is most useful when the data to be compressed is short and can be
-   predicted with good accuracy; the data can then be compressed better than
-   with the default empty dictionary.
-
-     Depending on the size of the compression data structures selected by
-   deflateInit or deflateInit2, a part of the dictionary may in effect be
-   discarded, for example if the dictionary is larger than the window size
-   provided in deflateInit or deflateInit2.  Thus the strings most likely to be
-   useful should be put at the end of the dictionary, not at the front.  In
-   addition, the current implementation of deflate will use at most the window
-   size minus 262 bytes of the provided dictionary.
-
-     Upon return of this function, strm->adler is set to the adler32 value
-   of the dictionary; the decompressor may later use this value to determine
-   which dictionary has been used by the compressor.  (The adler32 value
-   applies to the whole dictionary even if only a subset of the dictionary is
-   actually used by the compressor.) If a raw deflate was requested, then the
-   adler32 value is not computed and strm->adler is not set.
-
-     deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
-   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
-   inconsistent (for example if deflate has already been called for this stream
-   or if not at a block boundary for raw deflate).  deflateSetDictionary does
-   not perform any compression: this will be done by deflate().
-*/
-
-ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
-                                    z_streamp source));
-/*
-     Sets the destination stream as a complete copy of the source stream.
-
-     This function can be useful when several compression strategies will be
-   tried, for example when there are several ways of pre-processing the input
-   data with a filter.  The streams that will be discarded should then be freed
-   by calling deflateEnd.  Note that deflateCopy duplicates the internal
-   compression state which can be quite large, so this strategy is slow and can
-   consume lots of memory.
-
-     deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
-   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
-   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
-   destination.
-*/
-
-ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
-/*
-     This function is equivalent to deflateEnd followed by deflateInit,
-   but does not free and reallocate all the internal compression state.  The
-   stream will keep the same compression level and any other attributes that
-   may have been set by deflateInit2.
-
-     deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
-   stream state was inconsistent (such as zalloc or state being Z_NULL).
-*/
-
-ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
-                                      int level,
-                                      int strategy));
-/*
-     Dynamically update the compression level and compression strategy.  The
-   interpretation of level and strategy is as in deflateInit2.  This can be
-   used to switch between compression and straight copy of the input data, or
-   to switch to a different kind of input data requiring a different strategy.
-   If the compression level is changed, the input available so far is
-   compressed with the old level (and may be flushed); the new level will take
-   effect only at the next call of deflate().
-
-     Before the call of deflateParams, the stream state must be set as for
-   a call of deflate(), since the currently available input may have to be
-   compressed and flushed.  In particular, strm->avail_out must be non-zero.
-
-     deflateParams returns Z_OK if success, Z_STREAM_ERROR if the source
-   stream state was inconsistent or if a parameter was invalid, Z_BUF_ERROR if
-   strm->avail_out was zero.
-*/
-
-ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
-                                    int good_length,
-                                    int max_lazy,
-                                    int nice_length,
-                                    int max_chain));
-/*
-     Fine tune deflate's internal compression parameters.  This should only be
-   used by someone who understands the algorithm used by zlib's deflate for
-   searching for the best matching string, and even then only by the most
-   fanatic optimizer trying to squeeze out the last compressed bit for their
-   specific input data.  Read the deflate.c source code for the meaning of the
-   max_lazy, good_length, nice_length, and max_chain parameters.
-
-     deflateTune() can be called after deflateInit() or deflateInit2(), and
-   returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
- */
-
-ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
-                                       uLong sourceLen));
-/*
-     deflateBound() returns an upper bound on the compressed size after
-   deflation of sourceLen bytes.  It must be called after deflateInit() or
-   deflateInit2(), and after deflateSetHeader(), if used.  This would be used
-   to allocate an output buffer for deflation in a single pass, and so would be
-   called before deflate().  If that first deflate() call is provided the
-   sourceLen input bytes, an output buffer allocated to the size returned by
-   deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
-   to return Z_STREAM_END.  Note that it is possible for the compressed size to
-   be larger than the value returned by deflateBound() if flush options other
-   than Z_FINISH or Z_NO_FLUSH are used.
-*/
-
-ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm,
-                                       unsigned *pending,
-                                       int *bits));
-/*
-     deflatePending() returns the number of bytes and bits of output that have
-   been generated, but not yet provided in the available output.  The bytes not
-   provided would be due to the available output space having being consumed.
-   The number of bits of output not provided are between 0 and 7, where they
-   await more bits to join them in order to fill out a full byte.  If pending
-   or bits are Z_NULL, then those values are not set.
-
-     deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source
-   stream state was inconsistent.
- */
-
-ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
-                                     int bits,
-                                     int value));
-/*
-     deflatePrime() inserts bits in the deflate output stream.  The intent
-   is that this function is used to start off the deflate output with the bits
-   leftover from a previous deflate stream when appending to it.  As such, this
-   function can only be used for raw deflate, and must be used before the first
-   deflate() call after a deflateInit2() or deflateReset().  bits must be less
-   than or equal to 16, and that many of the least significant bits of value
-   will be inserted in the output.
-
-     deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough
-   room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the
-   source stream state was inconsistent.
-*/
-
-ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
-                                         gz_headerp head));
-/*
-     deflateSetHeader() provides gzip header information for when a gzip
-   stream is requested by deflateInit2().  deflateSetHeader() may be called
-   after deflateInit2() or deflateReset() and before the first call of
-   deflate().  The text, time, os, extra field, name, and comment information
-   in the provided gz_header structure are written to the gzip header (xflag is
-   ignored -- the extra flags are set according to the compression level).  The
-   caller must assure that, if not Z_NULL, name and comment are terminated with
-   a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
-   available there.  If hcrc is true, a gzip header crc is included.  Note that
-   the current versions of the command-line version of gzip (up through version
-   1.3.x) do not support header crc's, and will report that it is a "multi-part
-   gzip file" and give up.
-
-     If deflateSetHeader is not used, the default gzip header has text false,
-   the time set to zero, and os set to 255, with no extra, name, or comment
-   fields.  The gzip header is returned to the default state by deflateReset().
-
-     deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
-   stream state was inconsistent.
-*/
-
-/*
-ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
-                                     int  windowBits));
-
-     This is another version of inflateInit with an extra parameter.  The
-   fields next_in, avail_in, zalloc, zfree and opaque must be initialized
-   before by the caller.
-
-     The windowBits parameter is the base two logarithm of the maximum window
-   size (the size of the history buffer).  It should be in the range 8..15 for
-   this version of the library.  The default value is 15 if inflateInit is used
-   instead.  windowBits must be greater than or equal to the windowBits value
-   provided to deflateInit2() while compressing, or it must be equal to 15 if
-   deflateInit2() was not used.  If a compressed stream with a larger window
-   size is given as input, inflate() will return with the error code
-   Z_DATA_ERROR instead of trying to allocate a larger window.
-
-     windowBits can also be zero to request that inflate use the window size in
-   the zlib header of the compressed stream.
-
-     windowBits can also be -8..-15 for raw inflate.  In this case, -windowBits
-   determines the window size.  inflate() will then process raw deflate data,
-   not looking for a zlib or gzip header, not generating a check value, and not
-   looking for any check values for comparison at the end of the stream.  This
-   is for use with other formats that use the deflate compressed data format
-   such as zip.  Those formats provide their own check values.  If a custom
-   format is developed using the raw deflate format for compressed data, it is
-   recommended that a check value such as an adler32 or a crc32 be applied to
-   the uncompressed data as is done in the zlib, gzip, and zip formats.  For
-   most applications, the zlib format should be used as is.  Note that comments
-   above on the use in deflateInit2() applies to the magnitude of windowBits.
-
-     windowBits can also be greater than 15 for optional gzip decoding.  Add
-   32 to windowBits to enable zlib and gzip decoding with automatic header
-   detection, or add 16 to decode only the gzip format (the zlib format will
-   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is a
-   crc32 instead of an adler32.
-
-     inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
-   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
-   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
-   invalid, such as a null pointer to the structure.  msg is set to null if
-   there is no error message.  inflateInit2 does not perform any decompression
-   apart from possibly reading the zlib header if present: actual decompression
-   will be done by inflate().  (So next_in and avail_in may be modified, but
-   next_out and avail_out are unused and unchanged.) The current implementation
-   of inflateInit2() does not process any header information -- that is
-   deferred until inflate() is called.
-*/
-
-ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
-                                             const Bytef *dictionary,
-                                             uInt  dictLength));
-/*
-     Initializes the decompression dictionary from the given uncompressed byte
-   sequence.  This function must be called immediately after a call of inflate,
-   if that call returned Z_NEED_DICT.  The dictionary chosen by the compressor
-   can be determined from the adler32 value returned by that call of inflate.
-   The compressor and decompressor must use exactly the same dictionary (see
-   deflateSetDictionary).  For raw inflate, this function can be called at any
-   time to set the dictionary.  If the provided dictionary is smaller than the
-   window and there is already data in the window, then the provided dictionary
-   will amend what's there.  The application must insure that the dictionary
-   that was used for compression is provided.
-
-     inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
-   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
-   inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
-   expected one (incorrect adler32 value).  inflateSetDictionary does not
-   perform any decompression: this will be done by subsequent calls of
-   inflate().
-*/
-
-ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm,
-                                             Bytef *dictionary,
-                                             uInt  *dictLength));
-/*
-     Returns the sliding dictionary being maintained by inflate.  dictLength is
-   set to the number of bytes in the dictionary, and that many bytes are copied
-   to dictionary.  dictionary must have enough space, where 32768 bytes is
-   always enough.  If inflateGetDictionary() is called with dictionary equal to
-   Z_NULL, then only the dictionary length is returned, and nothing is copied.
-   Similary, if dictLength is Z_NULL, then it is not set.
-
-     inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
-   stream state is inconsistent.
-*/
-
-ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
-/*
-     Skips invalid compressed data until a possible full flush point (see above
-   for the description of deflate with Z_FULL_FLUSH) can be found, or until all
-   available input is skipped.  No output is provided.
-
-     inflateSync searches for a 00 00 FF FF pattern in the compressed data.
-   All full flush points have this pattern, but not all occurrences of this
-   pattern are full flush points.
-
-     inflateSync returns Z_OK if a possible full flush point has been found,
-   Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point
-   has been found, or Z_STREAM_ERROR if the stream structure was inconsistent.
-   In the success case, the application may save the current current value of
-   total_in which indicates where valid compressed data was found.  In the
-   error case, the application may repeatedly call inflateSync, providing more
-   input each time, until success or end of the input data.
-*/
-
-ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
-                                    z_streamp source));
-/*
-     Sets the destination stream as a complete copy of the source stream.
-
-     This function can be useful when randomly accessing a large stream.  The
-   first pass through the stream can periodically record the inflate state,
-   allowing restarting inflate at those points when randomly accessing the
-   stream.
-
-     inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
-   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
-   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
-   destination.
-*/
-
-ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
-/*
-     This function is equivalent to inflateEnd followed by inflateInit,
-   but does not free and reallocate all the internal decompression state.  The
-   stream will keep attributes that may have been set by inflateInit2.
-
-     inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
-   stream state was inconsistent (such as zalloc or state being Z_NULL).
-*/
-
-ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,
-                                      int windowBits));
-/*
-     This function is the same as inflateReset, but it also permits changing
-   the wrap and window size requests.  The windowBits parameter is interpreted
-   the same as it is for inflateInit2.
-
-     inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
-   stream state was inconsistent (such as zalloc or state being Z_NULL), or if
-   the windowBits parameter is invalid.
-*/
-
-ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
-                                     int bits,
-                                     int value));
-/*
-     This function inserts bits in the inflate input stream.  The intent is
-   that this function is used to start inflating at a bit position in the
-   middle of a byte.  The provided bits will be used before any bytes are used
-   from next_in.  This function should only be used with raw inflate, and
-   should be used before the first inflate() call after inflateInit2() or
-   inflateReset().  bits must be less than or equal to 16, and that many of the
-   least significant bits of value will be inserted in the input.
-
-     If bits is negative, then the input stream bit buffer is emptied.  Then
-   inflatePrime() can be called again to put bits in the buffer.  This is used
-   to clear out bits leftover after feeding inflate a block description prior
-   to feeding inflate codes.
-
-     inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
-   stream state was inconsistent.
-*/
-
-ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));
-/*
-     This function returns two values, one in the lower 16 bits of the return
-   value, and the other in the remaining upper bits, obtained by shifting the
-   return value down 16 bits.  If the upper value is -1 and the lower value is
-   zero, then inflate() is currently decoding information outside of a block.
-   If the upper value is -1 and the lower value is non-zero, then inflate is in
-   the middle of a stored block, with the lower value equaling the number of
-   bytes from the input remaining to copy.  If the upper value is not -1, then
-   it is the number of bits back from the current bit position in the input of
-   the code (literal or length/distance pair) currently being processed.  In
-   that case the lower value is the number of bytes already emitted for that
-   code.
-
-     A code is being processed if inflate is waiting for more input to complete
-   decoding of the code, or if it has completed decoding but is waiting for
-   more output space to write the literal or match data.
-
-     inflateMark() is used to mark locations in the input data for random
-   access, which may be at bit positions, and to note those cases where the
-   output of a code may span boundaries of random access blocks.  The current
-   location in the input stream can be determined from avail_in and data_type
-   as noted in the description for the Z_BLOCK flush parameter for inflate.
-
-     inflateMark returns the value noted above or -1 << 16 if the provided
-   source stream state was inconsistent.
-*/
-
-ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
-                                         gz_headerp head));
-/*
-     inflateGetHeader() requests that gzip header information be stored in the
-   provided gz_header structure.  inflateGetHeader() may be called after
-   inflateInit2() or inflateReset(), and before the first call of inflate().
-   As inflate() processes the gzip stream, head->done is zero until the header
-   is completed, at which time head->done is set to one.  If a zlib stream is
-   being decoded, then head->done is set to -1 to indicate that there will be
-   no gzip header information forthcoming.  Note that Z_BLOCK or Z_TREES can be
-   used to force inflate() to return immediately after header processing is
-   complete and before any actual data is decompressed.
-
-     The text, time, xflags, and os fields are filled in with the gzip header
-   contents.  hcrc is set to true if there is a header CRC.  (The header CRC
-   was valid if done is set to one.) If extra is not Z_NULL, then extra_max
-   contains the maximum number of bytes to write to extra.  Once done is true,
-   extra_len contains the actual extra field length, and extra contains the
-   extra field, or that field truncated if extra_max is less than extra_len.
-   If name is not Z_NULL, then up to name_max characters are written there,
-   terminated with a zero unless the length is greater than name_max.  If
-   comment is not Z_NULL, then up to comm_max characters are written there,
-   terminated with a zero unless the length is greater than comm_max.  When any
-   of extra, name, or comment are not Z_NULL and the respective field is not
-   present in the header, then that field is set to Z_NULL to signal its
-   absence.  This allows the use of deflateSetHeader() with the returned
-   structure to duplicate the header.  However if those fields are set to
-   allocated memory, then the application will need to save those pointers
-   elsewhere so that they can be eventually freed.
-
-     If inflateGetHeader is not used, then the header information is simply
-   discarded.  The header is always checked for validity, including the header
-   CRC if present.  inflateReset() will reset the process to discard the header
-   information.  The application would need to call inflateGetHeader() again to
-   retrieve the header from the next gzip stream.
-
-     inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
-   stream state was inconsistent.
-*/
-
-/*
-ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
-                                        unsigned char FAR *window));
-
-     Initialize the internal stream state for decompression using inflateBack()
-   calls.  The fields zalloc, zfree and opaque in strm must be initialized
-   before the call.  If zalloc and zfree are Z_NULL, then the default library-
-   derived memory allocation routines are used.  windowBits is the base two
-   logarithm of the window size, in the range 8..15.  window is a caller
-   supplied buffer of that size.  Except for special applications where it is
-   assured that deflate was used with small window sizes, windowBits must be 15
-   and a 32K byte window must be supplied to be able to decompress general
-   deflate streams.
-
-     See inflateBack() for the usage of these routines.
-
-     inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
-   the parameters are invalid, Z_MEM_ERROR if the internal state could not be
-   allocated, or Z_VERSION_ERROR if the version of the library does not match
-   the version of the header file.
-*/
-
-typedef unsigned (*in_func) OF((void FAR *,
-                                z_const unsigned char FAR * FAR *));
-typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
-
-ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
-                                    in_func in, void FAR *in_desc,
-                                    out_func out, void FAR *out_desc));
-/*
-     inflateBack() does a raw inflate with a single call using a call-back
-   interface for input and output.  This is potentially more efficient than
-   inflate() for file i/o applications, in that it avoids copying between the
-   output and the sliding window by simply making the window itself the output
-   buffer.  inflate() can be faster on modern CPUs when used with large
-   buffers.  inflateBack() trusts the application to not change the output
-   buffer passed by the output function, at least until inflateBack() returns.
-
-     inflateBackInit() must be called first to allocate the internal state
-   and to initialize the state with the user-provided window buffer.
-   inflateBack() may then be used multiple times to inflate a complete, raw
-   deflate stream with each call.  inflateBackEnd() is then called to free the
-   allocated state.
-
-     A raw deflate stream is one with no zlib or gzip header or trailer.
-   This routine would normally be used in a utility that reads zip or gzip
-   files and writes out uncompressed files.  The utility would decode the
-   header and process the trailer on its own, hence this routine expects only
-   the raw deflate stream to decompress.  This is different from the normal
-   behavior of inflate(), which expects either a zlib or gzip header and
-   trailer around the deflate stream.
-
-     inflateBack() uses two subroutines supplied by the caller that are then
-   called by inflateBack() for input and output.  inflateBack() calls those
-   routines until it reads a complete deflate stream and writes out all of the
-   uncompressed data, or until it encounters an error.  The function's
-   parameters and return types are defined above in the in_func and out_func
-   typedefs.  inflateBack() will call in(in_desc, &buf) which should return the
-   number of bytes of provided input, and a pointer to that input in buf.  If
-   there is no input available, in() must return zero--buf is ignored in that
-   case--and inflateBack() will return a buffer error.  inflateBack() will call
-   out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].  out()
-   should return zero on success, or non-zero on failure.  If out() returns
-   non-zero, inflateBack() will return with an error.  Neither in() nor out()
-   are permitted to change the contents of the window provided to
-   inflateBackInit(), which is also the buffer that out() uses to write from.
-   The length written by out() will be at most the window size.  Any non-zero
-   amount of input may be provided by in().
-
-     For convenience, inflateBack() can be provided input on the first call by
-   setting strm->next_in and strm->avail_in.  If that input is exhausted, then
-   in() will be called.  Therefore strm->next_in must be initialized before
-   calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called
-   immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in
-   must also be initialized, and then if strm->avail_in is not zero, input will
-   initially be taken from strm->next_in[0 ..  strm->avail_in - 1].
-
-     The in_desc and out_desc parameters of inflateBack() is passed as the
-   first parameter of in() and out() respectively when they are called.  These
-   descriptors can be optionally used to pass any information that the caller-
-   supplied in() and out() functions need to do their job.
-
-     On return, inflateBack() will set strm->next_in and strm->avail_in to
-   pass back any unused input that was provided by the last in() call.  The
-   return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
-   if in() or out() returned an error, Z_DATA_ERROR if there was a format error
-   in the deflate stream (in which case strm->msg is set to indicate the nature
-   of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
-   In the case of Z_BUF_ERROR, an input or output error can be distinguished
-   using strm->next_in which will be Z_NULL only if in() returned an error.  If
-   strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
-   non-zero.  (in() will always be called before out(), so strm->next_in is
-   assured to be defined if out() returns non-zero.) Note that inflateBack()
-   cannot return Z_OK.
-*/
-
-ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
-/*
-     All memory allocated by inflateBackInit() is freed.
-
-     inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
-   state was inconsistent.
-*/
-
-ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
-/* Return flags indicating compile-time options.
-
-    Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
-     1.0: size of uInt
-     3.2: size of uLong
-     5.4: size of voidpf (pointer)
-     7.6: size of z_off_t
-
-    Compiler, assembler, and debug options:
-     8: DEBUG
-     9: ASMV or ASMINF -- use ASM code
-     10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
-     11: 0 (reserved)
-
-    One-time table building (smaller code, but not thread-safe if true):
-     12: BUILDFIXED -- build static block decoding tables when needed
-     13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
-     14,15: 0 (reserved)
-
-    Library content (indicates missing functionality):
-     16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
-                          deflate code when not needed)
-     17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
-                    and decode gzip streams (to avoid linking crc code)
-     18-19: 0 (reserved)
-
-    Operation variations (changes in library functionality):
-     20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
-     21: FASTEST -- deflate algorithm with only one, lowest compression level
-     22,23: 0 (reserved)
-
-    The sprintf variant used by gzprintf (zero is best):
-     24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
-     25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
-     26: 0 = returns value, 1 = void -- 1 means inferred string length returned
-
-    Remainder:
-     27-31: 0 (reserved)
- */
-
-#ifndef Z_SOLO
-
-                        /* utility functions */
-
-/*
-     The following utility functions are implemented on top of the basic
-   stream-oriented functions.  To simplify the interface, some default options
-   are assumed (compression level and memory usage, standard memory allocation
-   functions).  The source code of these utility functions can be modified if
-   you need special options.
-*/
-
-ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
-                                 const Bytef *source, uLong sourceLen));
-/*
-     Compresses the source buffer into the destination buffer.  sourceLen is
-   the byte length of the source buffer.  Upon entry, destLen is the total size
-   of the destination buffer, which must be at least the value returned by
-   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
-   compressed buffer.
-
-     compress returns Z_OK if success, Z_MEM_ERROR if there was not
-   enough memory, Z_BUF_ERROR if there was not enough room in the output
-   buffer.
-*/
-
-ZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,
-                                  const Bytef *source, uLong sourceLen,
-                                  int level));
-/*
-     Compresses the source buffer into the destination buffer.  The level
-   parameter has the same meaning as in deflateInit.  sourceLen is the byte
-   length of the source buffer.  Upon entry, destLen is the total size of the
-   destination buffer, which must be at least the value returned by
-   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
-   compressed buffer.
-
-     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
-   memory, Z_BUF_ERROR if there was not enough room in the output buffer,
-   Z_STREAM_ERROR if the level parameter is invalid.
-*/
-
-ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
-/*
-     compressBound() returns an upper bound on the compressed size after
-   compress() or compress2() on sourceLen bytes.  It would be used before a
-   compress() or compress2() call to allocate the destination buffer.
-*/
-
-ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
-                                   const Bytef *source, uLong sourceLen));
-/*
-     Decompresses the source buffer into the destination buffer.  sourceLen is
-   the byte length of the source buffer.  Upon entry, destLen is the total size
-   of the destination buffer, which must be large enough to hold the entire
-   uncompressed data.  (The size of the uncompressed data must have been saved
-   previously by the compressor and transmitted to the decompressor by some
-   mechanism outside the scope of this compression library.) Upon exit, destLen
-   is the actual size of the uncompressed buffer.
-
-     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
-   enough memory, Z_BUF_ERROR if there was not enough room in the output
-   buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.  In
-   the case where there is not enough room, uncompress() will fill the output
-   buffer with the uncompressed data up to that point.
-*/
-
-                        /* gzip file access functions */
-
-/*
-     This library supports reading and writing files in gzip (.gz) format with
-   an interface similar to that of stdio, using the functions that start with
-   "gz".  The gzip format is different from the zlib format.  gzip is a gzip
-   wrapper, documented in RFC 1952, wrapped around a deflate stream.
-*/
-
-typedef struct gzFile_s *gzFile;    /* semi-opaque gzip file descriptor */
-
-/*
-ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
-
-     Opens a gzip (.gz) file for reading or writing.  The mode parameter is as
-   in fopen ("rb" or "wb") but can also include a compression level ("wb9") or
-   a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only
-   compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F'
-   for fixed code compression as in "wb9F".  (See the description of
-   deflateInit2 for more information about the strategy parameter.)  'T' will
-   request transparent writing or appending with no compression and not using
-   the gzip format.
-
-     "a" can be used instead of "w" to request that the gzip stream that will
-   be written be appended to the file.  "+" will result in an error, since
-   reading and writing to the same gzip file is not supported.  The addition of
-   "x" when writing will create the file exclusively, which fails if the file
-   already exists.  On systems that support it, the addition of "e" when
-   reading or writing will set the flag to close the file on an execve() call.
-
-     These functions, as well as gzip, will read and decode a sequence of gzip
-   streams in a file.  The append function of gzopen() can be used to create
-   such a file.  (Also see gzflush() for another way to do this.)  When
-   appending, gzopen does not test whether the file begins with a gzip stream,
-   nor does it look for the end of the gzip streams to begin appending.  gzopen
-   will simply append a gzip stream to the existing file.
-
-     gzopen can be used to read a file which is not in gzip format; in this
-   case gzread will directly read from the file without decompression.  When
-   reading, this will be detected automatically by looking for the magic two-
-   byte gzip header.
-
-     gzopen returns NULL if the file could not be opened, if there was
-   insufficient memory to allocate the gzFile state, or if an invalid mode was
-   specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
-   errno can be checked to determine if the reason gzopen failed was that the
-   file could not be opened.
-*/
-
-ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
-/*
-     gzdopen associates a gzFile with the file descriptor fd.  File descriptors
-   are obtained from calls like open, dup, creat, pipe or fileno (if the file
-   has been previously opened with fopen).  The mode parameter is as in gzopen.
-
-     The next call of gzclose on the returned gzFile will also close the file
-   descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
-   fd.  If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
-   mode);.  The duplicated descriptor should be saved to avoid a leak, since
-   gzdopen does not close fd if it fails.  If you are using fileno() to get the
-   file descriptor from a FILE *, then you will have to use dup() to avoid
-   double-close()ing the file descriptor.  Both gzclose() and fclose() will
-   close the associated file descriptor, so they need to have different file
-   descriptors.
-
-     gzdopen returns NULL if there was insufficient memory to allocate the
-   gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
-   provided, or '+' was provided), or if fd is -1.  The file descriptor is not
-   used until the next gz* read, write, seek, or close operation, so gzdopen
-   will not detect if fd is invalid (unless fd is -1).
-*/
-
-ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));
-/*
-     Set the internal buffer size used by this library's functions.  The
-   default buffer size is 8192 bytes.  This function must be called after
-   gzopen() or gzdopen(), and before any other calls that read or write the
-   file.  The buffer memory allocation is always deferred to the first read or
-   write.  Two buffers are allocated, either both of the specified size when
-   writing, or one of the specified size and the other twice that size when
-   reading.  A larger buffer size of, for example, 64K or 128K bytes will
-   noticeably increase the speed of decompression (reading).
-
-     The new buffer size also affects the maximum length for gzprintf().
-
-     gzbuffer() returns 0 on success, or -1 on failure, such as being called
-   too late.
-*/
-
-ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
-/*
-     Dynamically update the compression level or strategy.  See the description
-   of deflateInit2 for the meaning of these parameters.
-
-     gzsetparams returns Z_OK if success, or Z_STREAM_ERROR if the file was not
-   opened for writing.
-*/
-
-ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
-/*
-     Reads the given number of uncompressed bytes from the compressed file.  If
-   the input file is not in gzip format, gzread copies the given number of
-   bytes into the buffer directly from the file.
-
-     After reaching the end of a gzip stream in the input, gzread will continue
-   to read, looking for another gzip stream.  Any number of gzip streams may be
-   concatenated in the input file, and will all be decompressed by gzread().
-   If something other than a gzip stream is encountered after a gzip stream,
-   that remaining trailing garbage is ignored (and no error is returned).
-
-     gzread can be used to read a gzip file that is being concurrently written.
-   Upon reaching the end of the input, gzread will return with the available
-   data.  If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then
-   gzclearerr can be used to clear the end of file indicator in order to permit
-   gzread to be tried again.  Z_OK indicates that a gzip stream was completed
-   on the last gzread.  Z_BUF_ERROR indicates that the input file ended in the
-   middle of a gzip stream.  Note that gzread does not return -1 in the event
-   of an incomplete gzip stream.  This error is deferred until gzclose(), which
-   will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip
-   stream.  Alternatively, gzerror can be used before gzclose to detect this
-   case.
-
-     gzread returns the number of uncompressed bytes actually read, less than
-   len for end of file, or -1 for error.
-*/
-
-ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
-                                voidpc buf, unsigned len));
-/*
-     Writes the given number of uncompressed bytes into the compressed file.
-   gzwrite returns the number of uncompressed bytes written or 0 in case of
-   error.
-*/
-
-ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...));
-/*
-     Converts, formats, and writes the arguments to the compressed file under
-   control of the format string, as in fprintf.  gzprintf returns the number of
-   uncompressed bytes actually written, or 0 in case of error.  The number of
-   uncompressed bytes written is limited to 8191, or one less than the buffer
-   size given to gzbuffer().  The caller should assure that this limit is not
-   exceeded.  If it is exceeded, then gzprintf() will return an error (0) with
-   nothing written.  In this case, there may also be a buffer overflow with
-   unpredictable consequences, which is possible only if zlib was compiled with
-   the insecure functions sprintf() or vsprintf() because the secure snprintf()
-   or vsnprintf() functions were not available.  This can be determined using
-   zlibCompileFlags().
-*/
-
-ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
-/*
-     Writes the given null-terminated string to the compressed file, excluding
-   the terminating null character.
-
-     gzputs returns the number of characters written, or -1 in case of error.
-*/
-
-ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
-/*
-     Reads bytes from the compressed file until len-1 characters are read, or a
-   newline character is read and transferred to buf, or an end-of-file
-   condition is encountered.  If any characters are read or if len == 1, the
-   string is terminated with a null character.  If no characters are read due
-   to an end-of-file or len < 1, then the buffer is left untouched.
-
-     gzgets returns buf which is a null-terminated string, or it returns NULL
-   for end-of-file or in case of error.  If there was an error, the contents at
-   buf are indeterminate.
-*/
-
-ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
-/*
-     Writes c, converted to an unsigned char, into the compressed file.  gzputc
-   returns the value that was written, or -1 in case of error.
-*/
-
-ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
-/*
-     Reads one byte from the compressed file.  gzgetc returns this byte or -1
-   in case of end of file or error.  This is implemented as a macro for speed.
-   As such, it does not do all of the checking the other functions do.  I.e.
-   it does not check to see if file is NULL, nor whether the structure file
-   points to has been clobbered or not.
-*/
-
-ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
-/*
-     Push one character back onto the stream to be read as the first character
-   on the next read.  At least one character of push-back is allowed.
-   gzungetc() returns the character pushed, or -1 on failure.  gzungetc() will
-   fail if c is -1, and may fail if a character has been pushed but not read
-   yet.  If gzungetc is used immediately after gzopen or gzdopen, at least the
-   output buffer size of pushed characters is allowed.  (See gzbuffer above.)
-   The pushed character will be discarded if the stream is repositioned with
-   gzseek() or gzrewind().
-*/
-
-ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
-/*
-     Flushes all pending output into the compressed file.  The parameter flush
-   is as in the deflate() function.  The return value is the zlib error number
-   (see function gzerror below).  gzflush is only permitted when writing.
-
-     If the flush parameter is Z_FINISH, the remaining data is written and the
-   gzip stream is completed in the output.  If gzwrite() is called again, a new
-   gzip stream will be started in the output.  gzread() is able to read such
-   concatented gzip streams.
-
-     gzflush should be called only when strictly necessary because it will
-   degrade compression if called too often.
-*/
-
-/*
-ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
-                                   z_off_t offset, int whence));
-
-     Sets the starting position for the next gzread or gzwrite on the given
-   compressed file.  The offset represents a number of bytes in the
-   uncompressed data stream.  The whence parameter is defined as in lseek(2);
-   the value SEEK_END is not supported.
-
-     If the file is opened for reading, this function is emulated but can be
-   extremely slow.  If the file is opened for writing, only forward seeks are
-   supported; gzseek then compresses a sequence of zeroes up to the new
-   starting position.
-
-     gzseek returns the resulting offset location as measured in bytes from
-   the beginning of the uncompressed stream, or -1 in case of error, in
-   particular if the file is opened for writing and the new starting position
-   would be before the current position.
-*/
-
-ZEXTERN int ZEXPORT    gzrewind OF((gzFile file));
-/*
-     Rewinds the given file. This function is supported only for reading.
-
-     gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
-*/
-
-/*
-ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
-
-     Returns the starting position for the next gzread or gzwrite on the given
-   compressed file.  This position represents a number of bytes in the
-   uncompressed data stream, and is zero when starting, even if appending or
-   reading a gzip stream from the middle of a file using gzdopen().
-
-     gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
-*/
-
-/*
-ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));
-
-     Returns the current offset in the file being read or written.  This offset
-   includes the count of bytes that precede the gzip stream, for example when
-   appending or when using gzdopen() for reading.  When reading, the offset
-   does not include as yet unused buffered input.  This information can be used
-   for a progress indicator.  On error, gzoffset() returns -1.
-*/
-
-ZEXTERN int ZEXPORT gzeof OF((gzFile file));
-/*
-     Returns true (1) if the end-of-file indicator has been set while reading,
-   false (0) otherwise.  Note that the end-of-file indicator is set only if the
-   read tried to go past the end of the input, but came up short.  Therefore,
-   just like feof(), gzeof() may return false even if there is no more data to
-   read, in the event that the last read request was for the exact number of
-   bytes remaining in the input file.  This will happen if the input file size
-   is an exact multiple of the buffer size.
-
-     If gzeof() returns true, then the read functions will return no more data,
-   unless the end-of-file indicator is reset by gzclearerr() and the input file
-   has grown since the previous end of file was detected.
-*/
-
-ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
-/*
-     Returns true (1) if file is being copied directly while reading, or false
-   (0) if file is a gzip stream being decompressed.
-
-     If the input file is empty, gzdirect() will return true, since the input
-   does not contain a gzip stream.
-
-     If gzdirect() is used immediately after gzopen() or gzdopen() it will
-   cause buffers to be allocated to allow reading the file to determine if it
-   is a gzip file.  Therefore if gzbuffer() is used, it should be called before
-   gzdirect().
-
-     When writing, gzdirect() returns true (1) if transparent writing was
-   requested ("wT" for the gzopen() mode), or false (0) otherwise.  (Note:
-   gzdirect() is not needed when writing.  Transparent writing must be
-   explicitly requested, so the application already knows the answer.  When
-   linking statically, using gzdirect() will include all of the zlib code for
-   gzip file reading and decompression, which may not be desired.)
-*/
-
-ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
-/*
-     Flushes all pending output if necessary, closes the compressed file and
-   deallocates the (de)compression state.  Note that once file is closed, you
-   cannot call gzerror with file, since its structures have been deallocated.
-   gzclose must not be called more than once on the same file, just as free
-   must not be called more than once on the same allocation.
-
-     gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
-   file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the
-   last read ended in the middle of a gzip stream, or Z_OK on success.
-*/
-
-ZEXTERN int ZEXPORT gzclose_r OF((gzFile file));
-ZEXTERN int ZEXPORT gzclose_w OF((gzFile file));
-/*
-     Same as gzclose(), but gzclose_r() is only for use when reading, and
-   gzclose_w() is only for use when writing or appending.  The advantage to
-   using these instead of gzclose() is that they avoid linking in zlib
-   compression or decompression code that is not used when only reading or only
-   writing respectively.  If gzclose() is used, then both compression and
-   decompression code will be included the application when linking to a static
-   zlib library.
-*/
-
-ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
-/*
-     Returns the error message for the last error which occurred on the given
-   compressed file.  errnum is set to zlib error number.  If an error occurred
-   in the file system and not in the compression library, errnum is set to
-   Z_ERRNO and the application may consult errno to get the exact error code.
-
-     The application must not modify the returned string.  Future calls to
-   this function may invalidate the previously returned string.  If file is
-   closed, then the string previously returned by gzerror will no longer be
-   available.
-
-     gzerror() should be used to distinguish errors from end-of-file for those
-   functions above that do not distinguish those cases in their return values.
-*/
-
-ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
-/*
-     Clears the error and end-of-file flags for file.  This is analogous to the
-   clearerr() function in stdio.  This is useful for continuing to read a gzip
-   file that is being written concurrently.
-*/
-
-#endif /* !Z_SOLO */
-
-                        /* checksum functions */
-
-/*
-     These functions are not related to compression but are exported
-   anyway because they might be useful in applications using the compression
-   library.
-*/
-
-ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
-/*
-     Update a running Adler-32 checksum with the bytes buf[0..len-1] and
-   return the updated checksum.  If buf is Z_NULL, this function returns the
-   required initial value for the checksum.
-
-     An Adler-32 checksum is almost as reliable as a CRC32 but can be computed
-   much faster.
-
-   Usage example:
-
-     uLong adler = adler32(0L, Z_NULL, 0);
-
-     while (read_buffer(buffer, length) != EOF) {
-       adler = adler32(adler, buffer, length);
-     }
-     if (adler != original_adler) error();
-*/
-
-/*
-ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
-                                          z_off_t len2));
-
-     Combine two Adler-32 checksums into one.  For two sequences of bytes, seq1
-   and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
-   each, adler1 and adler2.  adler32_combine() returns the Adler-32 checksum of
-   seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.  Note
-   that the z_off_t type (like off_t) is a signed integer.  If len2 is
-   negative, the result has no meaning or utility.
-*/
-
-ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
-/*
-     Update a running CRC-32 with the bytes buf[0..len-1] and return the
-   updated CRC-32.  If buf is Z_NULL, this function returns the required
-   initial value for the crc.  Pre- and post-conditioning (one's complement) is
-   performed within this function so it shouldn't be done by the application.
-
-   Usage example:
-
-     uLong crc = crc32(0L, Z_NULL, 0);
-
-     while (read_buffer(buffer, length) != EOF) {
-       crc = crc32(crc, buffer, length);
-     }
-     if (crc != original_crc) error();
-*/
-
-/*
-ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
-
-     Combine two CRC-32 check values into one.  For two sequences of bytes,
-   seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
-   calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32
-   check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
-   len2.
-*/
-
-
-                        /* various hacks, don't look :) */
-
-/* deflateInit and inflateInit are macros to allow checking the zlib version
- * and the compiler's view of z_stream:
- */
-ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
-                                     const char *version, int stream_size));
-ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
-                                     const char *version, int stream_size));
-ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,
-                                      int windowBits, int memLevel,
-                                      int strategy, const char *version,
-                                      int stream_size));
-ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,
-                                      const char *version, int stream_size));
-ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
-                                         unsigned char FAR *window,
-                                         const char *version,
-                                         int stream_size));
-#define deflateInit(strm, level) \
-        deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
-#define inflateInit(strm) \
-        inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
-#define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
-        deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
-                      (strategy), ZLIB_VERSION, (int)sizeof(z_stream))
-#define inflateInit2(strm, windowBits) \
-        inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
-                      (int)sizeof(z_stream))
-#define inflateBackInit(strm, windowBits, window) \
-        inflateBackInit_((strm), (windowBits), (window), \
-                      ZLIB_VERSION, (int)sizeof(z_stream))
-
-#ifndef Z_SOLO
-
-/* gzgetc() macro and its supporting function and exposed data structure.  Note
- * that the real internal state is much larger than the exposed structure.
- * This abbreviated structure exposes just enough for the gzgetc() macro.  The
- * user should not mess with these exposed elements, since their names or
- * behavior could change in the future, perhaps even capriciously.  They can
- * only be used by the gzgetc() macro.  You have been warned.
- */
-struct gzFile_s {
-    unsigned have;
-    unsigned char *next;
-    z_off64_t pos;
-};
-ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file));  /* backward compatibility */
-#ifdef Z_PREFIX_SET
-#  undef z_gzgetc
-#  define z_gzgetc(g) \
-          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g))
-#else
-#  define gzgetc(g) \
-          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : gzgetc(g))
-#endif
-
-/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or
- * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
- * both are true, the application gets the *64 functions, and the regular
- * functions are changed to 64 bits) -- in case these are set on systems
- * without large file support, _LFS64_LARGEFILE must also be true
- */
-#ifdef Z_LARGE64
-   ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
-   ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
-   ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
-   ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
-   ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t));
-   ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t));
-#endif
-
-#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64)
-#  ifdef Z_PREFIX_SET
-#    define z_gzopen z_gzopen64
-#    define z_gzseek z_gzseek64
-#    define z_gztell z_gztell64
-#    define z_gzoffset z_gzoffset64
-#    define z_adler32_combine z_adler32_combine64
-#    define z_crc32_combine z_crc32_combine64
-#  else
-#    define gzopen gzopen64
-#    define gzseek gzseek64
-#    define gztell gztell64
-#    define gzoffset gzoffset64
-#    define adler32_combine adler32_combine64
-#    define crc32_combine crc32_combine64
-#  endif
-#  ifndef Z_LARGE64
-     ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
-     ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int));
-     ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile));
-     ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile));
-     ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
-     ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
-#  endif
-#else
-   ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));
-   ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));
-   ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));
-   ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));
-   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
-   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
-#endif
-
-#else /* Z_SOLO */
-
-   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
-   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
-
-#endif /* !Z_SOLO */
-
-/* hack for buggy compilers */
-#if !defined(ZUTIL_H) && !defined(NO_DUMMY_DECL)
-    struct internal_state {int dummy;};
-#endif
-
-/* undocumented functions */
-ZEXTERN const char   * ZEXPORT zError           OF((int));
-ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp));
-ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table    OF((void));
-ZEXTERN int            ZEXPORT inflateUndermine OF((z_streamp, int));
-ZEXTERN int            ZEXPORT inflateResetKeep OF((z_streamp));
-ZEXTERN int            ZEXPORT deflateResetKeep OF((z_streamp));
-#if defined(_WIN32) && !defined(Z_SOLO)
-ZEXTERN gzFile         ZEXPORT gzopen_w OF((const wchar_t *path,
-                                            const char *mode));
-#endif
-#if defined(STDC) || defined(Z_HAVE_STDARG_H)
-#  ifndef Z_SOLO
-ZEXTERN int            ZEXPORTVA gzvprintf Z_ARG((gzFile file,
-                                                  const char *format,
-                                                  va_list va));
-#  endif
-#endif
-
-#ifdef __cplusplus
-}
-#endif
-
-#endif /* ZLIB_H */
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/zutil.c	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,348 +0,0 @@
-/*
- * 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.
- */
-
-/* zutil.c -- target dependent utility functions for the compression library
- * Copyright (C) 1995-2005, 2010, 2011, 2012 Jean-loup Gailly.
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/* @(#) $Id$ */
-
-#include "zutil.h"
-#ifndef Z_SOLO
-#  include "gzguts.h"
-#endif
-
-#ifndef NO_DUMMY_DECL
-struct internal_state      {int dummy;}; /* for buggy compilers */
-#endif
-
-z_const char * const z_errmsg[10] = {
-"need dictionary",     /* Z_NEED_DICT       2  */
-"stream end",          /* Z_STREAM_END      1  */
-"",                    /* Z_OK              0  */
-"file error",          /* Z_ERRNO         (-1) */
-"stream error",        /* Z_STREAM_ERROR  (-2) */
-"data error",          /* Z_DATA_ERROR    (-3) */
-"insufficient memory", /* Z_MEM_ERROR     (-4) */
-"buffer error",        /* Z_BUF_ERROR     (-5) */
-"incompatible version",/* Z_VERSION_ERROR (-6) */
-""};
-
-
-const char * ZEXPORT zlibVersion()
-{
-    return ZLIB_VERSION;
-}
-
-uLong ZEXPORT zlibCompileFlags()
-{
-    uLong flags;
-
-    flags = 0;
-    switch ((int)(sizeof(uInt))) {
-    case 2:     break;
-    case 4:     flags += 1;     break;
-    case 8:     flags += 2;     break;
-    default:    flags += 3;
-    }
-    switch ((int)(sizeof(uLong))) {
-    case 2:     break;
-    case 4:     flags += 1 << 2;        break;
-    case 8:     flags += 2 << 2;        break;
-    default:    flags += 3 << 2;
-    }
-    switch ((int)(sizeof(voidpf))) {
-    case 2:     break;
-    case 4:     flags += 1 << 4;        break;
-    case 8:     flags += 2 << 4;        break;
-    default:    flags += 3 << 4;
-    }
-    switch ((int)(sizeof(z_off_t))) {
-    case 2:     break;
-    case 4:     flags += 1 << 6;        break;
-    case 8:     flags += 2 << 6;        break;
-    default:    flags += 3 << 6;
-    }
-#ifdef DEBUG
-    flags += 1 << 8;
-#endif
-#if defined(ASMV) || defined(ASMINF)
-    flags += 1 << 9;
-#endif
-#ifdef ZLIB_WINAPI
-    flags += 1 << 10;
-#endif
-#ifdef BUILDFIXED
-    flags += 1 << 12;
-#endif
-#ifdef DYNAMIC_CRC_TABLE
-    flags += 1 << 13;
-#endif
-#ifdef NO_GZCOMPRESS
-    flags += 1L << 16;
-#endif
-#ifdef NO_GZIP
-    flags += 1L << 17;
-#endif
-#ifdef PKZIP_BUG_WORKAROUND
-    flags += 1L << 20;
-#endif
-#ifdef FASTEST
-    flags += 1L << 21;
-#endif
-#if defined(STDC) || defined(Z_HAVE_STDARG_H)
-#  ifdef NO_vsnprintf
-    flags += 1L << 25;
-#    ifdef HAS_vsprintf_void
-    flags += 1L << 26;
-#    endif
-#  else
-#    ifdef HAS_vsnprintf_void
-    flags += 1L << 26;
-#    endif
-#  endif
-#else
-    flags += 1L << 24;
-#  ifdef NO_snprintf
-    flags += 1L << 25;
-#    ifdef HAS_sprintf_void
-    flags += 1L << 26;
-#    endif
-#  else
-#    ifdef HAS_snprintf_void
-    flags += 1L << 26;
-#    endif
-#  endif
-#endif
-    return flags;
-}
-
-#ifdef DEBUG
-
-#  ifndef verbose
-#    define verbose 0
-#  endif
-int ZLIB_INTERNAL z_verbose = verbose;
-
-void ZLIB_INTERNAL z_error (m)
-    char *m;
-{
-    fprintf(stderr, "%s\n", m);
-    exit(1);
-}
-#endif
-
-/* exported to allow conversion of error code to string for compress() and
- * uncompress()
- */
-const char * ZEXPORT zError(err)
-    int err;
-{
-    return ERR_MSG(err);
-}
-
-#if defined(_WIN32_WCE)
-    /* The Microsoft C Run-Time Library for Windows CE doesn't have
-     * errno.  We define it as a global variable to simplify porting.
-     * Its value is always 0 and should not be used.
-     */
-    int errno = 0;
-#endif
-
-#ifndef HAVE_MEMCPY
-
-void ZLIB_INTERNAL zmemcpy(dest, source, len)
-    Bytef* dest;
-    const Bytef* source;
-    uInt  len;
-{
-    if (len == 0) return;
-    do {
-        *dest++ = *source++; /* ??? to be unrolled */
-    } while (--len != 0);
-}
-
-int ZLIB_INTERNAL zmemcmp(s1, s2, len)
-    const Bytef* s1;
-    const Bytef* s2;
-    uInt  len;
-{
-    uInt j;
-
-    for (j = 0; j < len; j++) {
-        if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
-    }
-    return 0;
-}
-
-void ZLIB_INTERNAL zmemzero(dest, len)
-    Bytef* dest;
-    uInt  len;
-{
-    if (len == 0) return;
-    do {
-        *dest++ = 0;  /* ??? to be unrolled */
-    } while (--len != 0);
-}
-#endif
-
-#ifndef Z_SOLO
-
-#ifdef SYS16BIT
-
-#ifdef __TURBOC__
-/* Turbo C in 16-bit mode */
-
-#  define MY_ZCALLOC
-
-/* Turbo C malloc() does not allow dynamic allocation of 64K bytes
- * and farmalloc(64K) returns a pointer with an offset of 8, so we
- * must fix the pointer. Warning: the pointer must be put back to its
- * original form in order to free it, use zcfree().
- */
-
-#define MAX_PTR 10
-/* 10*64K = 640K */
-
-local int next_ptr = 0;
-
-typedef struct ptr_table_s {
-    voidpf org_ptr;
-    voidpf new_ptr;
-} ptr_table;
-
-local ptr_table table[MAX_PTR];
-/* This table is used to remember the original form of pointers
- * to large buffers (64K). Such pointers are normalized with a zero offset.
- * Since MSDOS is not a preemptive multitasking OS, this table is not
- * protected from concurrent access. This hack doesn't work anyway on
- * a protected system like OS/2. Use Microsoft C instead.
- */
-
-voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size)
-{
-    voidpf buf = opaque; /* just to make some compilers happy */
-    ulg bsize = (ulg)items*size;
-
-    /* If we allocate less than 65520 bytes, we assume that farmalloc
-     * will return a usable pointer which doesn't have to be normalized.
-     */
-    if (bsize < 65520L) {
-        buf = farmalloc(bsize);
-        if (*(ush*)&buf != 0) return buf;
-    } else {
-        buf = farmalloc(bsize + 16L);
-    }
-    if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
-    table[next_ptr].org_ptr = buf;
-
-    /* Normalize the pointer to seg:0 */
-    *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
-    *(ush*)&buf = 0;
-    table[next_ptr++].new_ptr = buf;
-    return buf;
-}
-
-void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
-{
-    int n;
-    if (*(ush*)&ptr != 0) { /* object < 64K */
-        farfree(ptr);
-        return;
-    }
-    /* Find the original pointer */
-    for (n = 0; n < next_ptr; n++) {
-        if (ptr != table[n].new_ptr) continue;
-
-        farfree(table[n].org_ptr);
-        while (++n < next_ptr) {
-            table[n-1] = table[n];
-        }
-        next_ptr--;
-        return;
-    }
-    ptr = opaque; /* just to make some compilers happy */
-    Assert(0, "zcfree: ptr not found");
-}
-
-#endif /* __TURBOC__ */
-
-
-#ifdef M_I86
-/* Microsoft C in 16-bit mode */
-
-#  define MY_ZCALLOC
-
-#if (!defined(_MSC_VER) || (_MSC_VER <= 600))
-#  define _halloc  halloc
-#  define _hfree   hfree
-#endif
-
-voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size)
-{
-    if (opaque) opaque = 0; /* to make compiler happy */
-    return _halloc((long)items, size);
-}
-
-void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
-{
-    if (opaque) opaque = 0; /* to make compiler happy */
-    _hfree(ptr);
-}
-
-#endif /* M_I86 */
-
-#endif /* SYS16BIT */
-
-
-#ifndef MY_ZCALLOC /* Any system without a special alloc function */
-
-#ifndef STDC
-extern voidp  malloc OF((uInt size));
-extern voidp  calloc OF((uInt items, uInt size));
-extern void   free   OF((voidpf ptr));
-#endif
-
-voidpf ZLIB_INTERNAL zcalloc (opaque, items, size)
-    voidpf opaque;
-    unsigned items;
-    unsigned size;
-{
-    if (opaque) items += size - size; /* make compiler happy */
-    return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
-                              (voidpf)calloc(items, size);
-}
-
-void ZLIB_INTERNAL zcfree (opaque, ptr)
-    voidpf opaque;
-    voidpf ptr;
-{
-    free(ptr);
-    if (opaque) return; /* make compiler happy */
-}
-
-#endif /* MY_ZCALLOC */
-
-#endif /* !Z_SOLO */
--- a/jdk/src/java.base/share/native/libzip/zlib-1.2.8/zutil.h	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,277 +0,0 @@
-/*
- * 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.
- */
-
-/* zutil.h -- internal interface and configuration of the compression library
- * Copyright (C) 1995-2013 Jean-loup Gailly.
- * For conditions of distribution and use, see copyright notice in zlib.h
- */
-
-/* WARNING: this file should *not* be used by applications. It is
-   part of the implementation of the compression library and is
-   subject to change. Applications should only use zlib.h.
- */
-
-/* @(#) $Id$ */
-
-#ifndef ZUTIL_H
-#define ZUTIL_H
-
-#ifdef HAVE_HIDDEN
-#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
-#else
-#  define ZLIB_INTERNAL
-#endif
-
-#include "zlib.h"
-
-#if defined(STDC) && !defined(Z_SOLO)
-#  if !(defined(_WIN32_WCE) && defined(_MSC_VER))
-#    include <stddef.h>
-#  endif
-#  include <string.h>
-#  include <stdlib.h>
-#endif
-
-#ifdef Z_SOLO
-   typedef long ptrdiff_t;  /* guess -- will be caught if guess is wrong */
-#endif
-
-#ifndef local
-#  define local static
-#endif
-/* compile with -Dlocal if your debugger can't find static symbols */
-
-typedef unsigned char  uch;
-typedef uch FAR uchf;
-typedef unsigned short ush;
-typedef ush FAR ushf;
-typedef unsigned long  ulg;
-
-extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
-/* (size given to avoid silly warnings with Visual C++) */
-
-#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
-
-#define ERR_RETURN(strm,err) \
-  return (strm->msg = ERR_MSG(err), (err))
-/* To be used only when the state is known to be valid */
-
-        /* common constants */
-
-#ifndef DEF_WBITS
-#  define DEF_WBITS MAX_WBITS
-#endif
-/* default windowBits for decompression. MAX_WBITS is for compression only */
-
-#if MAX_MEM_LEVEL >= 8
-#  define DEF_MEM_LEVEL 8
-#else
-#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
-#endif
-/* default memLevel */
-
-#define STORED_BLOCK 0
-#define STATIC_TREES 1
-#define DYN_TREES    2
-/* The three kinds of block type */
-
-#define MIN_MATCH  3
-#define MAX_MATCH  258
-/* The minimum and maximum match lengths */
-
-#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
-
-        /* target dependencies */
-
-#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
-#  define OS_CODE  0x00
-#  ifndef Z_SOLO
-#    if defined(__TURBOC__) || defined(__BORLANDC__)
-#      if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
-         /* Allow compilation with ANSI keywords only enabled */
-         void _Cdecl farfree( void *block );
-         void *_Cdecl farmalloc( unsigned long nbytes );
-#      else
-#        include <alloc.h>
-#      endif
-#    else /* MSC or DJGPP */
-#      include <malloc.h>
-#    endif
-#  endif
-#endif
-
-#ifdef AMIGA
-#  define OS_CODE  0x01
-#endif
-
-#if defined(VAXC) || defined(VMS)
-#  define OS_CODE  0x02
-#  define F_OPEN(name, mode) \
-     fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
-#endif
-
-#if defined(ATARI) || defined(atarist)
-#  define OS_CODE  0x05
-#endif
-
-#ifdef OS2
-#  define OS_CODE  0x06
-#  if defined(M_I86) && !defined(Z_SOLO)
-#    include <malloc.h>
-#  endif
-#endif
-
-#if defined(MACOS) || defined(TARGET_OS_MAC)
-#  define OS_CODE  0x07
-#  ifndef Z_SOLO
-#    if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
-#      include <unix.h> /* for fdopen */
-#    else
-#      ifndef fdopen
-#        define fdopen(fd,mode) NULL /* No fdopen() */
-#      endif
-#    endif
-#  endif
-#endif
-
-#ifdef TOPS20
-#  define OS_CODE  0x0a
-#endif
-
-#ifdef WIN32
-#  ifndef __CYGWIN__  /* Cygwin is Unix, not Win32 */
-#    define OS_CODE  0x0b
-#  endif
-#endif
-
-#ifdef __50SERIES /* Prime/PRIMOS */
-#  define OS_CODE  0x0f
-#endif
-
-#if defined(_BEOS_) || defined(RISCOS)
-#  define fdopen(fd,mode) NULL /* No fdopen() */
-#endif
-
-#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX
-#  if defined(_WIN32_WCE)
-#    define fdopen(fd,mode) NULL /* No fdopen() */
-#    ifndef _PTRDIFF_T_DEFINED
-       typedef int ptrdiff_t;
-#      define _PTRDIFF_T_DEFINED
-#    endif
-#  else
-#    define fdopen(fd,type)  _fdopen(fd,type)
-#  endif
-#endif
-
-#if defined(__BORLANDC__) && !defined(MSDOS)
-  #pragma warn -8004
-  #pragma warn -8008
-  #pragma warn -8066
-#endif
-
-/* provide prototypes for these when building zlib without LFS */
-#if !defined(_WIN32) && \
-    (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0)
-    ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
-    ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
-#endif
-
-        /* common defaults */
-
-#ifndef OS_CODE
-#  define OS_CODE  0x03  /* assume Unix */
-#endif
-
-#ifndef F_OPEN
-#  define F_OPEN(name, mode) fopen((name), (mode))
-#endif
-
-         /* functions */
-
-#if defined(pyr) || defined(Z_SOLO)
-#  define NO_MEMCPY
-#endif
-#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
- /* Use our own functions for small and medium model with MSC <= 5.0.
-  * You may have to use the same strategy for Borland C (untested).
-  * The __SC__ check is for Symantec.
-  */
-#  define NO_MEMCPY
-#endif
-#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
-#  define HAVE_MEMCPY
-#endif
-#ifdef HAVE_MEMCPY
-#  ifdef SMALL_MEDIUM /* MSDOS small or medium model */
-#    define zmemcpy _fmemcpy
-#    define zmemcmp _fmemcmp
-#    define zmemzero(dest, len) _fmemset(dest, 0, len)
-#  else
-#    define zmemcpy memcpy
-#    define zmemcmp memcmp
-#    define zmemzero(dest, len) memset(dest, 0, len)
-#  endif
-#else
-   void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
-   int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
-   void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len));
-#endif
-
-/* Diagnostic functions */
-#ifdef DEBUG
-#  include <stdio.h>
-   extern int ZLIB_INTERNAL z_verbose;
-   extern void ZLIB_INTERNAL z_error OF((char *m));
-#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}
-#  define Trace(x) {if (z_verbose>=0) fprintf x ;}
-#  define Tracev(x) {if (z_verbose>0) fprintf x ;}
-#  define Tracevv(x) {if (z_verbose>1) fprintf x ;}
-#  define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
-#  define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
-#else
-#  define Assert(cond,msg)
-#  define Trace(x)
-#  define Tracev(x)
-#  define Tracevv(x)
-#  define Tracec(c,x)
-#  define Tracecv(c,x)
-#endif
-
-#ifndef Z_SOLO
-   voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,
-                                    unsigned size));
-   void ZLIB_INTERNAL zcfree  OF((voidpf opaque, voidpf ptr));
-#endif
-
-#define ZALLOC(strm, items, size) \
-           (*((strm)->zalloc))((strm)->opaque, (items), (size))
-#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
-#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
-
-/* Reverse the bytes in a 32-bit value */
-#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
-                    (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
-
-#endif /* ZUTIL_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/ChangeLog	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,1515 @@
+
+                ChangeLog file for zlib
+
+Changes in 1.2.11 (15 Jan 2017)
+- Fix deflate stored bug when pulling last block from window
+- Permit immediate deflateParams changes before any deflate input
+
+Changes in 1.2.10 (2 Jan 2017)
+- Avoid warnings on snprintf() return value
+- Fix bug in deflate_stored() for zero-length input
+- Fix bug in gzwrite.c that produced corrupt gzip files
+- Remove files to be installed before copying them in Makefile.in
+- Add warnings when compiling with assembler code
+
+Changes in 1.2.9 (31 Dec 2016)
+- Fix contrib/minizip to permit unzipping with desktop API [Zouzou]
+- Improve contrib/blast to return unused bytes
+- Assure that gzoffset() is correct when appending
+- Improve compress() and uncompress() to support large lengths
+- Fix bug in test/example.c where error code not saved
+- Remedy Coverity warning [Randers-Pehrson]
+- Improve speed of gzprintf() in transparent mode
+- Fix inflateInit2() bug when windowBits is 16 or 32
+- Change DEBUG macro to ZLIB_DEBUG
+- Avoid uninitialized access by gzclose_w()
+- Allow building zlib outside of the source directory
+- Fix bug that accepted invalid zlib header when windowBits is zero
+- Fix gzseek() problem on MinGW due to buggy _lseeki64 there
+- Loop on write() calls in gzwrite.c in case of non-blocking I/O
+- Add --warn (-w) option to ./configure for more compiler warnings
+- Reject a window size of 256 bytes if not using the zlib wrapper
+- Fix bug when level 0 used with Z_HUFFMAN or Z_RLE
+- Add --debug (-d) option to ./configure to define ZLIB_DEBUG
+- Fix bugs in creating a very large gzip header
+- Add uncompress2() function, which returns the input size used
+- Assure that deflateParams() will not switch functions mid-block
+- Dramatically speed up deflation for level 0 (storing)
+- Add gzfread(), duplicating the interface of fread()
+- Add gzfwrite(), duplicating the interface of fwrite()
+- Add deflateGetDictionary() function
+- Use snprintf() for later versions of Microsoft C
+- Fix *Init macros to use z_ prefix when requested
+- Replace as400 with os400 for OS/400 support [Monnerat]
+- Add crc32_z() and adler32_z() functions with size_t lengths
+- Update Visual Studio project files [AraHaan]
+
+Changes in 1.2.8 (28 Apr 2013)
+- Update contrib/minizip/iowin32.c for Windows RT [Vollant]
+- Do not force Z_CONST for C++
+- Clean up contrib/vstudio [Roß]
+- Correct spelling error in zlib.h
+- Fix mixed line endings in contrib/vstudio
+
+Changes in 1.2.7.3 (13 Apr 2013)
+- Fix version numbers and DLL names in contrib/vstudio/*/zlib.rc
+
+Changes in 1.2.7.2 (13 Apr 2013)
+- Change check for a four-byte type back to hexadecimal
+- Fix typo in win32/Makefile.msc
+- Add casts in gzwrite.c for pointer differences
+
+Changes in 1.2.7.1 (24 Mar 2013)
+- Replace use of unsafe string functions with snprintf if available
+- Avoid including stddef.h on Windows for Z_SOLO compile [Niessink]
+- Fix gzgetc undefine when Z_PREFIX set [Turk]
+- Eliminate use of mktemp in Makefile (not always available)
+- Fix bug in 'F' mode for gzopen()
+- Add inflateGetDictionary() function
+- Correct comment in deflate.h
+- Use _snprintf for snprintf in Microsoft C
+- On Darwin, only use /usr/bin/libtool if libtool is not Apple
+- Delete "--version" file if created by "ar --version" [Richard G.]
+- Fix configure check for veracity of compiler error return codes
+- Fix CMake compilation of static lib for MSVC2010 x64
+- Remove unused variable in infback9.c
+- Fix argument checks in gzlog_compress() and gzlog_write()
+- Clean up the usage of z_const and respect const usage within zlib
+- Clean up examples/gzlog.[ch] comparisons of different types
+- Avoid shift equal to bits in type (caused endless loop)
+- Fix uninitialized value bug in gzputc() introduced by const patches
+- Fix memory allocation error in examples/zran.c [Nor]
+- Fix bug where gzopen(), gzclose() would write an empty file
+- Fix bug in gzclose() when gzwrite() runs out of memory
+- Check for input buffer malloc failure in examples/gzappend.c
+- Add note to contrib/blast to use binary mode in stdio
+- Fix comparisons of differently signed integers in contrib/blast
+- Check for invalid code length codes in contrib/puff
+- Fix serious but very rare decompression bug in inftrees.c
+- Update inflateBack() comments, since inflate() can be faster
+- Use underscored I/O function names for WINAPI_FAMILY
+- Add _tr_flush_bits to the external symbols prefixed by --zprefix
+- Add contrib/vstudio/vc10 pre-build step for static only
+- Quote --version-script argument in CMakeLists.txt
+- Don't specify --version-script on Apple platforms in CMakeLists.txt
+- Fix casting error in contrib/testzlib/testzlib.c
+- Fix types in contrib/minizip to match result of get_crc_table()
+- Simplify contrib/vstudio/vc10 with 'd' suffix
+- Add TOP support to win32/Makefile.msc
+- Suport i686 and amd64 assembler builds in CMakeLists.txt
+- Fix typos in the use of _LARGEFILE64_SOURCE in zconf.h
+- Add vc11 and vc12 build files to contrib/vstudio
+- Add gzvprintf() as an undocumented function in zlib
+- Fix configure for Sun shell
+- Remove runtime check in configure for four-byte integer type
+- Add casts and consts to ease user conversion to C++
+- Add man pages for minizip and miniunzip
+- In Makefile uninstall, don't rm if preceding cd fails
+- Do not return Z_BUF_ERROR if deflateParam() has nothing to write
+
+Changes in 1.2.7 (2 May 2012)
+- Replace use of memmove() with a simple copy for portability
+- Test for existence of strerror
+- Restore gzgetc_ for backward compatibility with 1.2.6
+- Fix build with non-GNU make on Solaris
+- Require gcc 4.0 or later on Mac OS X to use the hidden attribute
+- Include unistd.h for Watcom C
+- Use __WATCOMC__ instead of __WATCOM__
+- Do not use the visibility attribute if NO_VIZ defined
+- Improve the detection of no hidden visibility attribute
+- Avoid using __int64 for gcc or solo compilation
+- Cast to char * in gzprintf to avoid warnings [Zinser]
+- Fix make_vms.com for VAX [Zinser]
+- Don't use library or built-in byte swaps
+- Simplify test and use of gcc hidden attribute
+- Fix bug in gzclose_w() when gzwrite() fails to allocate memory
+- Add "x" (O_EXCL) and "e" (O_CLOEXEC) modes support to gzopen()
+- Fix bug in test/minigzip.c for configure --solo
+- Fix contrib/vstudio project link errors [Mohanathas]
+- Add ability to choose the builder in make_vms.com [Schweda]
+- Add DESTDIR support to mingw32 win32/Makefile.gcc
+- Fix comments in win32/Makefile.gcc for proper usage
+- Allow overriding the default install locations for cmake
+- Generate and install the pkg-config file with cmake
+- Build both a static and a shared version of zlib with cmake
+- Include version symbols for cmake builds
+- If using cmake with MSVC, add the source directory to the includes
+- Remove unneeded EXTRA_CFLAGS from win32/Makefile.gcc [Truta]
+- Move obsolete emx makefile to old [Truta]
+- Allow the use of -Wundef when compiling or using zlib
+- Avoid the use of the -u option with mktemp
+- Improve inflate() documentation on the use of Z_FINISH
+- Recognize clang as gcc
+- Add gzopen_w() in Windows for wide character path names
+- Rename zconf.h in CMakeLists.txt to move it out of the way
+- Add source directory in CMakeLists.txt for building examples
+- Look in build directory for zlib.pc in CMakeLists.txt
+- Remove gzflags from zlibvc.def in vc9 and vc10
+- Fix contrib/minizip compilation in the MinGW environment
+- Update ./configure for Solaris, support --64 [Mooney]
+- Remove -R. from Solaris shared build (possible security issue)
+- Avoid race condition for parallel make (-j) running example
+- Fix type mismatch between get_crc_table() and crc_table
+- Fix parsing of version with "-" in CMakeLists.txt [Snider, Ziegler]
+- Fix the path to zlib.map in CMakeLists.txt
+- Force the native libtool in Mac OS X to avoid GNU libtool [Beebe]
+- Add instructions to win32/Makefile.gcc for shared install [Torri]
+
+Changes in 1.2.6.1 (12 Feb 2012)
+- Avoid the use of the Objective-C reserved name "id"
+- Include io.h in gzguts.h for Microsoft compilers
+- Fix problem with ./configure --prefix and gzgetc macro
+- Include gz_header definition when compiling zlib solo
+- Put gzflags() functionality back in zutil.c
+- Avoid library header include in crc32.c for Z_SOLO
+- Use name in GCC_CLASSIC as C compiler for coverage testing, if set
+- Minor cleanup in contrib/minizip/zip.c [Vollant]
+- Update make_vms.com [Zinser]
+- Remove unnecessary gzgetc_ function
+- Use optimized byte swap operations for Microsoft and GNU [Snyder]
+- Fix minor typo in zlib.h comments [Rzesniowiecki]
+
+Changes in 1.2.6 (29 Jan 2012)
+- Update the Pascal interface in contrib/pascal
+- Fix function numbers for gzgetc_ in zlibvc.def files
+- Fix configure.ac for contrib/minizip [Schiffer]
+- Fix large-entry detection in minizip on 64-bit systems [Schiffer]
+- Have ./configure use the compiler return code for error indication
+- Fix CMakeLists.txt for cross compilation [McClure]
+- Fix contrib/minizip/zip.c for 64-bit architectures [Dalsnes]
+- Fix compilation of contrib/minizip on FreeBSD [Marquez]
+- Correct suggested usages in win32/Makefile.msc [Shachar, Horvath]
+- Include io.h for Turbo C / Borland C on all platforms [Truta]
+- Make version explicit in contrib/minizip/configure.ac [Bosmans]
+- Avoid warning for no encryption in contrib/minizip/zip.c [Vollant]
+- Minor cleanup up contrib/minizip/unzip.c [Vollant]
+- Fix bug when compiling minizip with C++ [Vollant]
+- Protect for long name and extra fields in contrib/minizip [Vollant]
+- Avoid some warnings in contrib/minizip [Vollant]
+- Add -I../.. -L../.. to CFLAGS for minizip and miniunzip
+- Add missing libs to minizip linker command
+- Add support for VPATH builds in contrib/minizip
+- Add an --enable-demos option to contrib/minizip/configure
+- Add the generation of configure.log by ./configure
+- Exit when required parameters not provided to win32/Makefile.gcc
+- Have gzputc return the character written instead of the argument
+- Use the -m option on ldconfig for BSD systems [Tobias]
+- Correct in zlib.map when deflateResetKeep was added
+
+Changes in 1.2.5.3 (15 Jan 2012)
+- Restore gzgetc function for binary compatibility
+- Do not use _lseeki64 under Borland C++ [Truta]
+- Update win32/Makefile.msc to build test/*.c [Truta]
+- Remove old/visualc6 given CMakefile and other alternatives
+- Update AS400 build files and documentation [Monnerat]
+- Update win32/Makefile.gcc to build test/*.c [Truta]
+- Permit stronger flushes after Z_BLOCK flushes
+- Avoid extraneous empty blocks when doing empty flushes
+- Permit Z_NULL arguments to deflatePending
+- Allow deflatePrime() to insert bits in the middle of a stream
+- Remove second empty static block for Z_PARTIAL_FLUSH
+- Write out all of the available bits when using Z_BLOCK
+- Insert the first two strings in the hash table after a flush
+
+Changes in 1.2.5.2 (17 Dec 2011)
+- fix ld error: unable to find version dependency 'ZLIB_1.2.5'
+- use relative symlinks for shared libs
+- Avoid searching past window for Z_RLE strategy
+- Assure that high-water mark initialization is always applied in deflate
+- Add assertions to fill_window() in deflate.c to match comments
+- Update python link in README
+- Correct spelling error in gzread.c
+- Fix bug in gzgets() for a concatenated empty gzip stream
+- Correct error in comment for gz_make()
+- Change gzread() and related to ignore junk after gzip streams
+- Allow gzread() and related to continue after gzclearerr()
+- Allow gzrewind() and gzseek() after a premature end-of-file
+- Simplify gzseek() now that raw after gzip is ignored
+- Change gzgetc() to a macro for speed (~40% speedup in testing)
+- Fix gzclose() to return the actual error last encountered
+- Always add large file support for windows
+- Include zconf.h for windows large file support
+- Include zconf.h.cmakein for windows large file support
+- Update zconf.h.cmakein on make distclean
+- Merge vestigial vsnprintf determination from zutil.h to gzguts.h
+- Clarify how gzopen() appends in zlib.h comments
+- Correct documentation of gzdirect() since junk at end now ignored
+- Add a transparent write mode to gzopen() when 'T' is in the mode
+- Update python link in zlib man page
+- Get inffixed.h and MAKEFIXED result to match
+- Add a ./config --solo option to make zlib subset with no library use
+- Add undocumented inflateResetKeep() function for CAB file decoding
+- Add --cover option to ./configure for gcc coverage testing
+- Add #define ZLIB_CONST option to use const in the z_stream interface
+- Add comment to gzdopen() in zlib.h to use dup() when using fileno()
+- Note behavior of uncompress() to provide as much data as it can
+- Add files in contrib/minizip to aid in building libminizip
+- Split off AR options in Makefile.in and configure
+- Change ON macro to Z_ARG to avoid application conflicts
+- Facilitate compilation with Borland C++ for pragmas and vsnprintf
+- Include io.h for Turbo C / Borland C++
+- Move example.c and minigzip.c to test/
+- Simplify incomplete code table filling in inflate_table()
+- Remove code from inflate.c and infback.c that is impossible to execute
+- Test the inflate code with full coverage
+- Allow deflateSetDictionary, inflateSetDictionary at any time (in raw)
+- Add deflateResetKeep and fix inflateResetKeep to retain dictionary
+- Fix gzwrite.c to accommodate reduced memory zlib compilation
+- Have inflate() with Z_FINISH avoid the allocation of a window
+- Do not set strm->adler when doing raw inflate
+- Fix gzeof() to behave just like feof() when read is not past end of file
+- Fix bug in gzread.c when end-of-file is reached
+- Avoid use of Z_BUF_ERROR in gz* functions except for premature EOF
+- Document gzread() capability to read concurrently written files
+- Remove hard-coding of resource compiler in CMakeLists.txt [Blammo]
+
+Changes in 1.2.5.1 (10 Sep 2011)
+- Update FAQ entry on shared builds (#13)
+- Avoid symbolic argument to chmod in Makefile.in
+- Fix bug and add consts in contrib/puff [Oberhumer]
+- Update contrib/puff/zeros.raw test file to have all block types
+- Add full coverage test for puff in contrib/puff/Makefile
+- Fix static-only-build install in Makefile.in
+- Fix bug in unzGetCurrentFileInfo() in contrib/minizip [Kuno]
+- Add libz.a dependency to shared in Makefile.in for parallel builds
+- Spell out "number" (instead of "nb") in zlib.h for total_in, total_out
+- Replace $(...) with `...` in configure for non-bash sh [Bowler]
+- Add darwin* to Darwin* and solaris* to SunOS\ 5* in configure [Groffen]
+- Add solaris* to Linux* in configure to allow gcc use [Groffen]
+- Add *bsd* to Linux* case in configure [Bar-Lev]
+- Add inffast.obj to dependencies in win32/Makefile.msc
+- Correct spelling error in deflate.h [Kohler]
+- Change libzdll.a again to libz.dll.a (!) in win32/Makefile.gcc
+- Add test to configure for GNU C looking for gcc in output of $cc -v
+- Add zlib.pc generation to win32/Makefile.gcc [Weigelt]
+- Fix bug in zlib.h for _FILE_OFFSET_BITS set and _LARGEFILE64_SOURCE not
+- Add comment in zlib.h that adler32_combine with len2 < 0 makes no sense
+- Make NO_DIVIDE option in adler32.c much faster (thanks to John Reiser)
+- Make stronger test in zconf.h to include unistd.h for LFS
+- Apply Darwin patches for 64-bit file offsets to contrib/minizip [Slack]
+- Fix zlib.h LFS support when Z_PREFIX used
+- Add updated as400 support (removed from old) [Monnerat]
+- Avoid deflate sensitivity to volatile input data
+- Avoid division in adler32_combine for NO_DIVIDE
+- Clarify the use of Z_FINISH with deflateBound() amount of space
+- Set binary for output file in puff.c
+- Use u4 type for crc_table to avoid conversion warnings
+- Apply casts in zlib.h to avoid conversion warnings
+- Add OF to prototypes for adler32_combine_ and crc32_combine_ [Miller]
+- Improve inflateSync() documentation to note indeterminancy
+- Add deflatePending() function to return the amount of pending output
+- Correct the spelling of "specification" in FAQ [Randers-Pehrson]
+- Add a check in configure for stdarg.h, use for gzprintf()
+- Check that pointers fit in ints when gzprint() compiled old style
+- Add dummy name before $(SHAREDLIBV) in Makefile [Bar-Lev, Bowler]
+- Delete line in configure that adds -L. libz.a to LDFLAGS [Weigelt]
+- Add debug records in assmebler code [Londer]
+- Update RFC references to use http://tools.ietf.org/html/... [Li]
+- Add --archs option, use of libtool to configure for Mac OS X [Borstel]
+
+Changes in 1.2.5 (19 Apr 2010)
+- Disable visibility attribute in win32/Makefile.gcc [Bar-Lev]
+- Default to libdir as sharedlibdir in configure [Nieder]
+- Update copyright dates on modified source files
+- Update trees.c to be able to generate modified trees.h
+- Exit configure for MinGW, suggesting win32/Makefile.gcc
+- Check for NULL path in gz_open [Homurlu]
+
+Changes in 1.2.4.5 (18 Apr 2010)
+- Set sharedlibdir in configure [Torok]
+- Set LDFLAGS in Makefile.in [Bar-Lev]
+- Avoid mkdir objs race condition in Makefile.in [Bowler]
+- Add ZLIB_INTERNAL in front of internal inter-module functions and arrays
+- Define ZLIB_INTERNAL to hide internal functions and arrays for GNU C
+- Don't use hidden attribute when it is a warning generator (e.g. Solaris)
+
+Changes in 1.2.4.4 (18 Apr 2010)
+- Fix CROSS_PREFIX executable testing, CHOST extract, mingw* [Torok]
+- Undefine _LARGEFILE64_SOURCE in zconf.h if it is zero, but not if empty
+- Try to use bash or ksh regardless of functionality of /bin/sh
+- Fix configure incompatibility with NetBSD sh
+- Remove attempt to run under bash or ksh since have better NetBSD fix
+- Fix win32/Makefile.gcc for MinGW [Bar-Lev]
+- Add diagnostic messages when using CROSS_PREFIX in configure
+- Added --sharedlibdir option to configure [Weigelt]
+- Use hidden visibility attribute when available [Frysinger]
+
+Changes in 1.2.4.3 (10 Apr 2010)
+- Only use CROSS_PREFIX in configure for ar and ranlib if they exist
+- Use CROSS_PREFIX for nm [Bar-Lev]
+- Assume _LARGEFILE64_SOURCE defined is equivalent to true
+- Avoid use of undefined symbols in #if with && and ||
+- Make *64 prototypes in gzguts.h consistent with functions
+- Add -shared load option for MinGW in configure [Bowler]
+- Move z_off64_t to public interface, use instead of off64_t
+- Remove ! from shell test in configure (not portable to Solaris)
+- Change +0 macro tests to -0 for possibly increased portability
+
+Changes in 1.2.4.2 (9 Apr 2010)
+- Add consistent carriage returns to readme.txt's in masmx86 and masmx64
+- Really provide prototypes for *64 functions when building without LFS
+- Only define unlink() in minigzip.c if unistd.h not included
+- Update README to point to contrib/vstudio project files
+- Move projects/vc6 to old/ and remove projects/
+- Include stdlib.h in minigzip.c for setmode() definition under WinCE
+- Clean up assembler builds in win32/Makefile.msc [Rowe]
+- Include sys/types.h for Microsoft for off_t definition
+- Fix memory leak on error in gz_open()
+- Symbolize nm as $NM in configure [Weigelt]
+- Use TEST_LDSHARED instead of LDSHARED to link test programs [Weigelt]
+- Add +0 to _FILE_OFFSET_BITS and _LFS64_LARGEFILE in case not defined
+- Fix bug in gzeof() to take into account unused input data
+- Avoid initialization of structures with variables in puff.c
+- Updated win32/README-WIN32.txt [Rowe]
+
+Changes in 1.2.4.1 (28 Mar 2010)
+- Remove the use of [a-z] constructs for sed in configure [gentoo 310225]
+- Remove $(SHAREDLIB) from LIBS in Makefile.in [Creech]
+- Restore "for debugging" comment on sprintf() in gzlib.c
+- Remove fdopen for MVS from gzguts.h
+- Put new README-WIN32.txt in win32 [Rowe]
+- Add check for shell to configure and invoke another shell if needed
+- Fix big fat stinking bug in gzseek() on uncompressed files
+- Remove vestigial F_OPEN64 define in zutil.h
+- Set and check the value of _LARGEFILE_SOURCE and _LARGEFILE64_SOURCE
+- Avoid errors on non-LFS systems when applications define LFS macros
+- Set EXE to ".exe" in configure for MINGW [Kahle]
+- Match crc32() in crc32.c exactly to the prototype in zlib.h [Sherrill]
+- Add prefix for cross-compilation in win32/makefile.gcc [Bar-Lev]
+- Add DLL install in win32/makefile.gcc [Bar-Lev]
+- Allow Linux* or linux* from uname in configure [Bar-Lev]
+- Allow ldconfig to be redefined in configure and Makefile.in [Bar-Lev]
+- Add cross-compilation prefixes to configure [Bar-Lev]
+- Match type exactly in gz_load() invocation in gzread.c
+- Match type exactly of zcalloc() in zutil.c to zlib.h alloc_func
+- Provide prototypes for *64 functions when building zlib without LFS
+- Don't use -lc when linking shared library on MinGW
+- Remove errno.h check in configure and vestigial errno code in zutil.h
+
+Changes in 1.2.4 (14 Mar 2010)
+- Fix VER3 extraction in configure for no fourth subversion
+- Update zlib.3, add docs to Makefile.in to make .pdf out of it
+- Add zlib.3.pdf to distribution
+- Don't set error code in gzerror() if passed pointer is NULL
+- Apply destination directory fixes to CMakeLists.txt [Lowman]
+- Move #cmakedefine's to a new zconf.in.cmakein
+- Restore zconf.h for builds that don't use configure or cmake
+- Add distclean to dummy Makefile for convenience
+- Update and improve INDEX, README, and FAQ
+- Update CMakeLists.txt for the return of zconf.h [Lowman]
+- Update contrib/vstudio/vc9 and vc10 [Vollant]
+- Change libz.dll.a back to libzdll.a in win32/Makefile.gcc
+- Apply license and readme changes to contrib/asm686 [Raiter]
+- Check file name lengths and add -c option in minigzip.c [Li]
+- Update contrib/amd64 and contrib/masmx86/ [Vollant]
+- Avoid use of "eof" parameter in trees.c to not shadow library variable
+- Update make_vms.com for removal of zlibdefs.h [Zinser]
+- Update assembler code and vstudio projects in contrib [Vollant]
+- Remove outdated assembler code contrib/masm686 and contrib/asm586
+- Remove old vc7 and vc8 from contrib/vstudio
+- Update win32/Makefile.msc, add ZLIB_VER_SUBREVISION [Rowe]
+- Fix memory leaks in gzclose_r() and gzclose_w(), file leak in gz_open()
+- Add contrib/gcc_gvmat64 for longest_match and inflate_fast [Vollant]
+- Remove *64 functions from win32/zlib.def (they're not 64-bit yet)
+- Fix bug in void-returning vsprintf() case in gzwrite.c
+- Fix name change from inflate.h in contrib/inflate86/inffas86.c
+- Check if temporary file exists before removing in make_vms.com [Zinser]
+- Fix make install and uninstall for --static option
+- Fix usage of _MSC_VER in gzguts.h and zutil.h [Truta]
+- Update readme.txt in contrib/masmx64 and masmx86 to assemble
+
+Changes in 1.2.3.9 (21 Feb 2010)
+- Expunge gzio.c
+- Move as400 build information to old
+- Fix updates in contrib/minizip and contrib/vstudio
+- Add const to vsnprintf test in configure to avoid warnings [Weigelt]
+- Delete zconf.h (made by configure) [Weigelt]
+- Change zconf.in.h to zconf.h.in per convention [Weigelt]
+- Check for NULL buf in gzgets()
+- Return empty string for gzgets() with len == 1 (like fgets())
+- Fix description of gzgets() in zlib.h for end-of-file, NULL return
+- Update minizip to 1.1 [Vollant]
+- Avoid MSVC loss of data warnings in gzread.c, gzwrite.c
+- Note in zlib.h that gzerror() should be used to distinguish from EOF
+- Remove use of snprintf() from gzlib.c
+- Fix bug in gzseek()
+- Update contrib/vstudio, adding vc9 and vc10 [Kuno, Vollant]
+- Fix zconf.h generation in CMakeLists.txt [Lowman]
+- Improve comments in zconf.h where modified by configure
+
+Changes in 1.2.3.8 (13 Feb 2010)
+- Clean up text files (tabs, trailing whitespace, etc.) [Oberhumer]
+- Use z_off64_t in gz_zero() and gz_skip() to match state->skip
+- Avoid comparison problem when sizeof(int) == sizeof(z_off64_t)
+- Revert to Makefile.in from 1.2.3.6 (live with the clutter)
+- Fix missing error return in gzflush(), add zlib.h note
+- Add *64 functions to zlib.map [Levin]
+- Fix signed/unsigned comparison in gz_comp()
+- Use SFLAGS when testing shared linking in configure
+- Add --64 option to ./configure to use -m64 with gcc
+- Fix ./configure --help to correctly name options
+- Have make fail if a test fails [Levin]
+- Avoid buffer overrun in contrib/masmx64/gvmat64.asm [Simpson]
+- Remove assembler object files from contrib
+
+Changes in 1.2.3.7 (24 Jan 2010)
+- Always gzopen() with O_LARGEFILE if available
+- Fix gzdirect() to work immediately after gzopen() or gzdopen()
+- Make gzdirect() more precise when the state changes while reading
+- Improve zlib.h documentation in many places
+- Catch memory allocation failure in gz_open()
+- Complete close operation if seek forward in gzclose_w() fails
+- Return Z_ERRNO from gzclose_r() if close() fails
+- Return Z_STREAM_ERROR instead of EOF for gzclose() being passed NULL
+- Return zero for gzwrite() errors to match zlib.h description
+- Return -1 on gzputs() error to match zlib.h description
+- Add zconf.in.h to allow recovery from configure modification [Weigelt]
+- Fix static library permissions in Makefile.in [Weigelt]
+- Avoid warnings in configure tests that hide functionality [Weigelt]
+- Add *BSD and DragonFly to Linux case in configure [gentoo 123571]
+- Change libzdll.a to libz.dll.a in win32/Makefile.gcc [gentoo 288212]
+- Avoid access of uninitialized data for first inflateReset2 call [Gomes]
+- Keep object files in subdirectories to reduce the clutter somewhat
+- Remove default Makefile and zlibdefs.h, add dummy Makefile
+- Add new external functions to Z_PREFIX, remove duplicates, z_z_ -> z_
+- Remove zlibdefs.h completely -- modify zconf.h instead
+
+Changes in 1.2.3.6 (17 Jan 2010)
+- Avoid void * arithmetic in gzread.c and gzwrite.c
+- Make compilers happier with const char * for gz_error message
+- Avoid unused parameter warning in inflate.c
+- Avoid signed-unsigned comparison warning in inflate.c
+- Indent #pragma's for traditional C
+- Fix usage of strwinerror() in glib.c, change to gz_strwinerror()
+- Correct email address in configure for system options
+- Update make_vms.com and add make_vms.com to contrib/minizip [Zinser]
+- Update zlib.map [Brown]
+- Fix Makefile.in for Solaris 10 make of example64 and minizip64 [Torok]
+- Apply various fixes to CMakeLists.txt [Lowman]
+- Add checks on len in gzread() and gzwrite()
+- Add error message for no more room for gzungetc()
+- Remove zlib version check in gzwrite()
+- Defer compression of gzprintf() result until need to
+- Use snprintf() in gzdopen() if available
+- Remove USE_MMAP configuration determination (only used by minigzip)
+- Remove examples/pigz.c (available separately)
+- Update examples/gun.c to 1.6
+
+Changes in 1.2.3.5 (8 Jan 2010)
+- Add space after #if in zutil.h for some compilers
+- Fix relatively harmless bug in deflate_fast() [Exarevsky]
+- Fix same problem in deflate_slow()
+- Add $(SHAREDLIBV) to LIBS in Makefile.in [Brown]
+- Add deflate_rle() for faster Z_RLE strategy run-length encoding
+- Add deflate_huff() for faster Z_HUFFMAN_ONLY encoding
+- Change name of "write" variable in inffast.c to avoid library collisions
+- Fix premature EOF from gzread() in gzio.c [Brown]
+- Use zlib header window size if windowBits is 0 in inflateInit2()
+- Remove compressBound() call in deflate.c to avoid linking compress.o
+- Replace use of errno in gz* with functions, support WinCE [Alves]
+- Provide alternative to perror() in minigzip.c for WinCE [Alves]
+- Don't use _vsnprintf on later versions of MSVC [Lowman]
+- Add CMake build script and input file [Lowman]
+- Update contrib/minizip to 1.1 [Svensson, Vollant]
+- Moved nintendods directory from contrib to .
+- Replace gzio.c with a new set of routines with the same functionality
+- Add gzbuffer(), gzoffset(), gzclose_r(), gzclose_w() as part of above
+- Update contrib/minizip to 1.1b
+- Change gzeof() to return 0 on error instead of -1 to agree with zlib.h
+
+Changes in 1.2.3.4 (21 Dec 2009)
+- Use old school .SUFFIXES in Makefile.in for FreeBSD compatibility
+- Update comments in configure and Makefile.in for default --shared
+- Fix test -z's in configure [Marquess]
+- Build examplesh and minigzipsh when not testing
+- Change NULL's to Z_NULL's in deflate.c and in comments in zlib.h
+- Import LDFLAGS from the environment in configure
+- Fix configure to populate SFLAGS with discovered CFLAGS options
+- Adapt make_vms.com to the new Makefile.in [Zinser]
+- Add zlib2ansi script for C++ compilation [Marquess]
+- Add _FILE_OFFSET_BITS=64 test to make test (when applicable)
+- Add AMD64 assembler code for longest match to contrib [Teterin]
+- Include options from $SFLAGS when doing $LDSHARED
+- Simplify 64-bit file support by introducing z_off64_t type
+- Make shared object files in objs directory to work around old Sun cc
+- Use only three-part version number for Darwin shared compiles
+- Add rc option to ar in Makefile.in for when ./configure not run
+- Add -WI,-rpath,. to LDFLAGS for OSF 1 V4*
+- Set LD_LIBRARYN32_PATH for SGI IRIX shared compile
+- Protect against _FILE_OFFSET_BITS being defined when compiling zlib
+- Rename Makefile.in targets allstatic to static and allshared to shared
+- Fix static and shared Makefile.in targets to be independent
+- Correct error return bug in gz_open() by setting state [Brown]
+- Put spaces before ;;'s in configure for better sh compatibility
+- Add pigz.c (parallel implementation of gzip) to examples/
+- Correct constant in crc32.c to UL [Leventhal]
+- Reject negative lengths in crc32_combine()
+- Add inflateReset2() function to work like inflateEnd()/inflateInit2()
+- Include sys/types.h for _LARGEFILE64_SOURCE [Brown]
+- Correct typo in doc/algorithm.txt [Janik]
+- Fix bug in adler32_combine() [Zhu]
+- Catch missing-end-of-block-code error in all inflates and in puff
+    Assures that random input to inflate eventually results in an error
+- Added enough.c (calculation of ENOUGH for inftrees.h) to examples/
+- Update ENOUGH and its usage to reflect discovered bounds
+- Fix gzerror() error report on empty input file [Brown]
+- Add ush casts in trees.c to avoid pedantic runtime errors
+- Fix typo in zlib.h uncompress() description [Reiss]
+- Correct inflate() comments with regard to automatic header detection
+- Remove deprecation comment on Z_PARTIAL_FLUSH (it stays)
+- Put new version of gzlog (2.0) in examples with interruption recovery
+- Add puff compile option to permit invalid distance-too-far streams
+- Add puff TEST command options, ability to read piped input
+- Prototype the *64 functions in zlib.h when _FILE_OFFSET_BITS == 64, but
+  _LARGEFILE64_SOURCE not defined
+- Fix Z_FULL_FLUSH to truly erase the past by resetting s->strstart
+- Fix deflateSetDictionary() to use all 32K for output consistency
+- Remove extraneous #define MIN_LOOKAHEAD in deflate.c (in deflate.h)
+- Clear bytes after deflate lookahead to avoid use of uninitialized data
+- Change a limit in inftrees.c to be more transparent to Coverity Prevent
+- Update win32/zlib.def with exported symbols from zlib.h
+- Correct spelling errors in zlib.h [Willem, Sobrado]
+- Allow Z_BLOCK for deflate() to force a new block
+- Allow negative bits in inflatePrime() to delete existing bit buffer
+- Add Z_TREES flush option to inflate() to return at end of trees
+- Add inflateMark() to return current state information for random access
+- Add Makefile for NintendoDS to contrib [Costa]
+- Add -w in configure compile tests to avoid spurious warnings [Beucler]
+- Fix typos in zlib.h comments for deflateSetDictionary()
+- Fix EOF detection in transparent gzread() [Maier]
+
+Changes in 1.2.3.3 (2 October 2006)
+- Make --shared the default for configure, add a --static option
+- Add compile option to permit invalid distance-too-far streams
+- Add inflateUndermine() function which is required to enable above
+- Remove use of "this" variable name for C++ compatibility [Marquess]
+- Add testing of shared library in make test, if shared library built
+- Use ftello() and fseeko() if available instead of ftell() and fseek()
+- Provide two versions of all functions that use the z_off_t type for
+  binary compatibility -- a normal version and a 64-bit offset version,
+  per the Large File Support Extension when _LARGEFILE64_SOURCE is
+  defined; use the 64-bit versions by default when _FILE_OFFSET_BITS
+  is defined to be 64
+- Add a --uname= option to configure to perhaps help with cross-compiling
+
+Changes in 1.2.3.2 (3 September 2006)
+- Turn off silly Borland warnings [Hay]
+- Use off64_t and define _LARGEFILE64_SOURCE when present
+- Fix missing dependency on inffixed.h in Makefile.in
+- Rig configure --shared to build both shared and static [Teredesai, Truta]
+- Remove zconf.in.h and instead create a new zlibdefs.h file
+- Fix contrib/minizip/unzip.c non-encrypted after encrypted [Vollant]
+- Add treebuild.xml (see http://treebuild.metux.de/) [Weigelt]
+
+Changes in 1.2.3.1 (16 August 2006)
+- Add watcom directory with OpenWatcom make files [Daniel]
+- Remove #undef of FAR in zconf.in.h for MVS [Fedtke]
+- Update make_vms.com [Zinser]
+- Use -fPIC for shared build in configure [Teredesai, Nicholson]
+- Use only major version number for libz.so on IRIX and OSF1 [Reinholdtsen]
+- Use fdopen() (not _fdopen()) for Interix in zutil.h [Bäck]
+- Add some FAQ entries about the contrib directory
+- Update the MVS question in the FAQ
+- Avoid extraneous reads after EOF in gzio.c [Brown]
+- Correct spelling of "successfully" in gzio.c [Randers-Pehrson]
+- Add comments to zlib.h about gzerror() usage [Brown]
+- Set extra flags in gzip header in gzopen() like deflate() does
+- Make configure options more compatible with double-dash conventions
+  [Weigelt]
+- Clean up compilation under Solaris SunStudio cc [Rowe, Reinholdtsen]
+- Fix uninstall target in Makefile.in [Truta]
+- Add pkgconfig support [Weigelt]
+- Use $(DESTDIR) macro in Makefile.in [Reinholdtsen, Weigelt]
+- Replace set_data_type() with a more accurate detect_data_type() in
+  trees.c, according to the txtvsbin.txt document [Truta]
+- Swap the order of #include <stdio.h> and #include "zlib.h" in
+  gzio.c, example.c and minigzip.c [Truta]
+- Shut up annoying VS2005 warnings about standard C deprecation [Rowe,
+  Truta] (where?)
+- Fix target "clean" from win32/Makefile.bor [Truta]
+- Create .pdb and .manifest files in win32/makefile.msc [Ziegler, Rowe]
+- Update zlib www home address in win32/DLL_FAQ.txt [Truta]
+- Update contrib/masmx86/inffas32.asm for VS2005 [Vollant, Van Wassenhove]
+- Enable browse info in the "Debug" and "ASM Debug" configurations in
+  the Visual C++ 6 project, and set (non-ASM) "Debug" as default [Truta]
+- Add pkgconfig support [Weigelt]
+- Add ZLIB_VER_MAJOR, ZLIB_VER_MINOR and ZLIB_VER_REVISION in zlib.h,
+  for use in win32/zlib1.rc [Polushin, Rowe, Truta]
+- Add a document that explains the new text detection scheme to
+  doc/txtvsbin.txt [Truta]
+- Add rfc1950.txt, rfc1951.txt and rfc1952.txt to doc/ [Truta]
+- Move algorithm.txt into doc/ [Truta]
+- Synchronize FAQ with website
+- Fix compressBound(), was low for some pathological cases [Fearnley]
+- Take into account wrapper variations in deflateBound()
+- Set examples/zpipe.c input and output to binary mode for Windows
+- Update examples/zlib_how.html with new zpipe.c (also web site)
+- Fix some warnings in examples/gzlog.c and examples/zran.c (it seems
+  that gcc became pickier in 4.0)
+- Add zlib.map for Linux: "All symbols from zlib-1.1.4 remain
+  un-versioned, the patch adds versioning only for symbols introduced in
+  zlib-1.2.0 or later.  It also declares as local those symbols which are
+  not designed to be exported." [Levin]
+- Update Z_PREFIX list in zconf.in.h, add --zprefix option to configure
+- Do not initialize global static by default in trees.c, add a response
+  NO_INIT_GLOBAL_POINTERS to initialize them if needed [Marquess]
+- Don't use strerror() in gzio.c under WinCE [Yakimov]
+- Don't use errno.h in zutil.h under WinCE [Yakimov]
+- Move arguments for AR to its usage to allow replacing ar [Marot]
+- Add HAVE_VISIBILITY_PRAGMA in zconf.in.h for Mozilla [Randers-Pehrson]
+- Improve inflateInit() and inflateInit2() documentation
+- Fix structure size comment in inflate.h
+- Change configure help option from --h* to --help [Santos]
+
+Changes in 1.2.3 (18 July 2005)
+- Apply security vulnerability fixes to contrib/infback9 as well
+- Clean up some text files (carriage returns, trailing space)
+- Update testzlib, vstudio, masmx64, and masmx86 in contrib [Vollant]
+
+Changes in 1.2.2.4 (11 July 2005)
+- Add inflatePrime() function for starting inflation at bit boundary
+- Avoid some Visual C warnings in deflate.c
+- Avoid more silly Visual C warnings in inflate.c and inftrees.c for 64-bit
+  compile
+- Fix some spelling errors in comments [Betts]
+- Correct inflateInit2() error return documentation in zlib.h
+- Add zran.c example of compressed data random access to examples
+  directory, shows use of inflatePrime()
+- Fix cast for assignments to strm->state in inflate.c and infback.c
+- Fix zlibCompileFlags() in zutil.c to use 1L for long shifts [Oberhumer]
+- Move declarations of gf2 functions to right place in crc32.c [Oberhumer]
+- Add cast in trees.c t avoid a warning [Oberhumer]
+- Avoid some warnings in fitblk.c, gun.c, gzjoin.c in examples [Oberhumer]
+- Update make_vms.com [Zinser]
+- Initialize state->write in inflateReset() since copied in inflate_fast()
+- Be more strict on incomplete code sets in inflate_table() and increase
+  ENOUGH and MAXD -- this repairs a possible security vulnerability for
+  invalid inflate input.  Thanks to Tavis Ormandy and Markus Oberhumer for
+  discovering the vulnerability and providing test cases.
+- Add ia64 support to configure for HP-UX [Smith]
+- Add error return to gzread() for format or i/o error [Levin]
+- Use malloc.h for OS/2 [Necasek]
+
+Changes in 1.2.2.3 (27 May 2005)
+- Replace 1U constants in inflate.c and inftrees.c for 64-bit compile
+- Typecast fread() return values in gzio.c [Vollant]
+- Remove trailing space in minigzip.c outmode (VC++ can't deal with it)
+- Fix crc check bug in gzread() after gzungetc() [Heiner]
+- Add the deflateTune() function to adjust internal compression parameters
+- Add a fast gzip decompressor, gun.c, to examples (use of inflateBack)
+- Remove an incorrect assertion in examples/zpipe.c
+- Add C++ wrapper in infback9.h [Donais]
+- Fix bug in inflateCopy() when decoding fixed codes
+- Note in zlib.h how much deflateSetDictionary() actually uses
+- Remove USE_DICT_HEAD in deflate.c (would mess up inflate if used)
+- Add _WIN32_WCE to define WIN32 in zconf.in.h [Spencer]
+- Don't include stderr.h or errno.h for _WIN32_WCE in zutil.h [Spencer]
+- Add gzdirect() function to indicate transparent reads
+- Update contrib/minizip [Vollant]
+- Fix compilation of deflate.c when both ASMV and FASTEST [Oberhumer]
+- Add casts in crc32.c to avoid warnings [Oberhumer]
+- Add contrib/masmx64 [Vollant]
+- Update contrib/asm586, asm686, masmx86, testzlib, vstudio [Vollant]
+
+Changes in 1.2.2.2 (30 December 2004)
+- Replace structure assignments in deflate.c and inflate.c with zmemcpy to
+  avoid implicit memcpy calls (portability for no-library compilation)
+- Increase sprintf() buffer size in gzdopen() to allow for large numbers
+- Add INFLATE_STRICT to check distances against zlib header
+- Improve WinCE errno handling and comments [Chang]
+- Remove comment about no gzip header processing in FAQ
+- Add Z_FIXED strategy option to deflateInit2() to force fixed trees
+- Add updated make_vms.com [Coghlan], update README
+- Create a new "examples" directory, move gzappend.c there, add zpipe.c,
+  fitblk.c, gzlog.[ch], gzjoin.c, and zlib_how.html.
+- Add FAQ entry and comments in deflate.c on uninitialized memory access
+- Add Solaris 9 make options in configure [Gilbert]
+- Allow strerror() usage in gzio.c for STDC
+- Fix DecompressBuf in contrib/delphi/ZLib.pas [ManChesTer]
+- Update contrib/masmx86/inffas32.asm and gvmat32.asm [Vollant]
+- Use z_off_t for adler32_combine() and crc32_combine() lengths
+- Make adler32() much faster for small len
+- Use OS_CODE in deflate() default gzip header
+
+Changes in 1.2.2.1 (31 October 2004)
+- Allow inflateSetDictionary() call for raw inflate
+- Fix inflate header crc check bug for file names and comments
+- Add deflateSetHeader() and gz_header structure for custom gzip headers
+- Add inflateGetheader() to retrieve gzip headers
+- Add crc32_combine() and adler32_combine() functions
+- Add alloc_func, free_func, in_func, out_func to Z_PREFIX list
+- Use zstreamp consistently in zlib.h (inflate_back functions)
+- Remove GUNZIP condition from definition of inflate_mode in inflate.h
+  and in contrib/inflate86/inffast.S [Truta, Anderson]
+- Add support for AMD64 in contrib/inflate86/inffas86.c [Anderson]
+- Update projects/README.projects and projects/visualc6 [Truta]
+- Update win32/DLL_FAQ.txt [Truta]
+- Avoid warning under NO_GZCOMPRESS in gzio.c; fix typo [Truta]
+- Deprecate Z_ASCII; use Z_TEXT instead [Truta]
+- Use a new algorithm for setting strm->data_type in trees.c [Truta]
+- Do not define an exit() prototype in zutil.c unless DEBUG defined
+- Remove prototype of exit() from zutil.c, example.c, minigzip.c [Truta]
+- Add comment in zlib.h for Z_NO_FLUSH parameter to deflate()
+- Fix Darwin build version identification [Peterson]
+
+Changes in 1.2.2 (3 October 2004)
+- Update zlib.h comments on gzip in-memory processing
+- Set adler to 1 in inflateReset() to support Java test suite [Walles]
+- Add contrib/dotzlib [Ravn]
+- Update win32/DLL_FAQ.txt [Truta]
+- Update contrib/minizip [Vollant]
+- Move contrib/visual-basic.txt to old/ [Truta]
+- Fix assembler builds in projects/visualc6/ [Truta]
+
+Changes in 1.2.1.2 (9 September 2004)
+- Update INDEX file
+- Fix trees.c to update strm->data_type (no one ever noticed!)
+- Fix bug in error case in inflate.c, infback.c, and infback9.c [Brown]
+- Add "volatile" to crc table flag declaration (for DYNAMIC_CRC_TABLE)
+- Add limited multitasking protection to DYNAMIC_CRC_TABLE
+- Add NO_vsnprintf for VMS in zutil.h [Mozilla]
+- Don't declare strerror() under VMS [Mozilla]
+- Add comment to DYNAMIC_CRC_TABLE to use get_crc_table() to initialize
+- Update contrib/ada [Anisimkov]
+- Update contrib/minizip [Vollant]
+- Fix configure to not hardcode directories for Darwin [Peterson]
+- Fix gzio.c to not return error on empty files [Brown]
+- Fix indentation; update version in contrib/delphi/ZLib.pas and
+  contrib/pascal/zlibpas.pas [Truta]
+- Update mkasm.bat in contrib/masmx86 [Truta]
+- Update contrib/untgz [Truta]
+- Add projects/README.projects [Truta]
+- Add project for MS Visual C++ 6.0 in projects/visualc6 [Cadieux, Truta]
+- Update win32/DLL_FAQ.txt [Truta]
+- Update list of Z_PREFIX symbols in zconf.h [Randers-Pehrson, Truta]
+- Remove an unnecessary assignment to curr in inftrees.c [Truta]
+- Add OS/2 to exe builds in configure [Poltorak]
+- Remove err dummy parameter in zlib.h [Kientzle]
+
+Changes in 1.2.1.1 (9 January 2004)
+- Update email address in README
+- Several FAQ updates
+- Fix a big fat bug in inftrees.c that prevented decoding valid
+  dynamic blocks with only literals and no distance codes --
+  Thanks to "Hot Emu" for the bug report and sample file
+- Add a note to puff.c on no distance codes case.
+
+Changes in 1.2.1 (17 November 2003)
+- Remove a tab in contrib/gzappend/gzappend.c
+- Update some interfaces in contrib for new zlib functions
+- Update zlib version number in some contrib entries
+- Add Windows CE definition for ptrdiff_t in zutil.h [Mai, Truta]
+- Support shared libraries on Hurd and KFreeBSD [Brown]
+- Fix error in NO_DIVIDE option of adler32.c
+
+Changes in 1.2.0.8 (4 November 2003)
+- Update version in contrib/delphi/ZLib.pas and contrib/pascal/zlibpas.pas
+- Add experimental NO_DIVIDE #define in adler32.c
+    - Possibly faster on some processors (let me know if it is)
+- Correct Z_BLOCK to not return on first inflate call if no wrap
+- Fix strm->data_type on inflate() return to correctly indicate EOB
+- Add deflatePrime() function for appending in the middle of a byte
+- Add contrib/gzappend for an example of appending to a stream
+- Update win32/DLL_FAQ.txt [Truta]
+- Delete Turbo C comment in README [Truta]
+- Improve some indentation in zconf.h [Truta]
+- Fix infinite loop on bad input in configure script [Church]
+- Fix gzeof() for concatenated gzip files [Johnson]
+- Add example to contrib/visual-basic.txt [Michael B.]
+- Add -p to mkdir's in Makefile.in [vda]
+- Fix configure to properly detect presence or lack of printf functions
+- Add AS400 support [Monnerat]
+- Add a little Cygwin support [Wilson]
+
+Changes in 1.2.0.7 (21 September 2003)
+- Correct some debug formats in contrib/infback9
+- Cast a type in a debug statement in trees.c
+- Change search and replace delimiter in configure from % to # [Beebe]
+- Update contrib/untgz to 0.2 with various fixes [Truta]
+- Add build support for Amiga [Nikl]
+- Remove some directories in old that have been updated to 1.2
+- Add dylib building for Mac OS X in configure and Makefile.in
+- Remove old distribution stuff from Makefile
+- Update README to point to DLL_FAQ.txt, and add comment on Mac OS X
+- Update links in README
+
+Changes in 1.2.0.6 (13 September 2003)
+- Minor FAQ updates
+- Update contrib/minizip to 1.00 [Vollant]
+- Remove test of gz functions in example.c when GZ_COMPRESS defined [Truta]
+- Update POSTINC comment for 68060 [Nikl]
+- Add contrib/infback9 with deflate64 decoding (unsupported)
+- For MVS define NO_vsnprintf and undefine FAR [van Burik]
+- Add pragma for fdopen on MVS [van Burik]
+
+Changes in 1.2.0.5 (8 September 2003)
+- Add OF to inflateBackEnd() declaration in zlib.h
+- Remember start when using gzdopen in the middle of a file
+- Use internal off_t counters in gz* functions to properly handle seeks
+- Perform more rigorous check for distance-too-far in inffast.c
+- Add Z_BLOCK flush option to return from inflate at block boundary
+- Set strm->data_type on return from inflate
+    - Indicate bits unused, if at block boundary, and if in last block
+- Replace size_t with ptrdiff_t in crc32.c, and check for correct size
+- Add condition so old NO_DEFLATE define still works for compatibility
+- FAQ update regarding the Windows DLL [Truta]
+- INDEX update: add qnx entry, remove aix entry [Truta]
+- Install zlib.3 into mandir [Wilson]
+- Move contrib/zlib_dll_FAQ.txt to win32/DLL_FAQ.txt; update [Truta]
+- Adapt the zlib interface to the new DLL convention guidelines [Truta]
+- Introduce ZLIB_WINAPI macro to allow the export of functions using
+  the WINAPI calling convention, for Visual Basic [Vollant, Truta]
+- Update msdos and win32 scripts and makefiles [Truta]
+- Export symbols by name, not by ordinal, in win32/zlib.def [Truta]
+- Add contrib/ada [Anisimkov]
+- Move asm files from contrib/vstudio/vc70_32 to contrib/asm386 [Truta]
+- Rename contrib/asm386 to contrib/masmx86 [Truta, Vollant]
+- Add contrib/masm686 [Truta]
+- Fix offsets in contrib/inflate86 and contrib/masmx86/inffas32.asm
+  [Truta, Vollant]
+- Update contrib/delphi; rename to contrib/pascal; add example [Truta]
+- Remove contrib/delphi2; add a new contrib/delphi [Truta]
+- Avoid inclusion of the nonstandard <memory.h> in contrib/iostream,
+  and fix some method prototypes [Truta]
+- Fix the ZCR_SEED2 constant to avoid warnings in contrib/minizip
+  [Truta]
+- Avoid the use of backslash (\) in contrib/minizip [Vollant]
+- Fix file time handling in contrib/untgz; update makefiles [Truta]
+- Update contrib/vstudio/vc70_32 to comply with the new DLL guidelines
+  [Vollant]
+- Remove contrib/vstudio/vc15_16 [Vollant]
+- Rename contrib/vstudio/vc70_32 to contrib/vstudio/vc7 [Truta]
+- Update README.contrib [Truta]
+- Invert the assignment order of match_head and s->prev[...] in
+  INSERT_STRING [Truta]
+- Compare TOO_FAR with 32767 instead of 32768, to avoid 16-bit warnings
+  [Truta]
+- Compare function pointers with 0, not with NULL or Z_NULL [Truta]
+- Fix prototype of syncsearch in inflate.c [Truta]
+- Introduce ASMINF macro to be enabled when using an ASM implementation
+  of inflate_fast [Truta]
+- Change NO_DEFLATE to NO_GZCOMPRESS [Truta]
+- Modify test_gzio in example.c to take a single file name as a
+  parameter [Truta]
+- Exit the example.c program if gzopen fails [Truta]
+- Add type casts around strlen in example.c [Truta]
+- Remove casting to sizeof in minigzip.c; give a proper type
+  to the variable compared with SUFFIX_LEN [Truta]
+- Update definitions of STDC and STDC99 in zconf.h [Truta]
+- Synchronize zconf.h with the new Windows DLL interface [Truta]
+- Use SYS16BIT instead of __32BIT__ to distinguish between
+  16- and 32-bit platforms [Truta]
+- Use far memory allocators in small 16-bit memory models for
+  Turbo C [Truta]
+- Add info about the use of ASMV, ASMINF and ZLIB_WINAPI in
+  zlibCompileFlags [Truta]
+- Cygwin has vsnprintf [Wilson]
+- In Windows16, OS_CODE is 0, as in MSDOS [Truta]
+- In Cygwin, OS_CODE is 3 (Unix), not 11 (Windows32) [Wilson]
+
+Changes in 1.2.0.4 (10 August 2003)
+- Minor FAQ updates
+- Be more strict when checking inflateInit2's windowBits parameter
+- Change NO_GUNZIP compile option to NO_GZIP to cover deflate as well
+- Add gzip wrapper option to deflateInit2 using windowBits
+- Add updated QNX rule in configure and qnx directory [Bonnefoy]
+- Make inflate distance-too-far checks more rigorous
+- Clean up FAR usage in inflate
+- Add casting to sizeof() in gzio.c and minigzip.c
+
+Changes in 1.2.0.3 (19 July 2003)
+- Fix silly error in gzungetc() implementation [Vollant]
+- Update contrib/minizip and contrib/vstudio [Vollant]
+- Fix printf format in example.c
+- Correct cdecl support in zconf.in.h [Anisimkov]
+- Minor FAQ updates
+
+Changes in 1.2.0.2 (13 July 2003)
+- Add ZLIB_VERNUM in zlib.h for numerical preprocessor comparisons
+- Attempt to avoid warnings in crc32.c for pointer-int conversion
+- Add AIX to configure, remove aix directory [Bakker]
+- Add some casts to minigzip.c
+- Improve checking after insecure sprintf() or vsprintf() calls
+- Remove #elif's from crc32.c
+- Change leave label to inf_leave in inflate.c and infback.c to avoid
+  library conflicts
+- Remove inflate gzip decoding by default--only enable gzip decoding by
+  special request for stricter backward compatibility
+- Add zlibCompileFlags() function to return compilation information
+- More typecasting in deflate.c to avoid warnings
+- Remove leading underscore from _Capital #defines [Truta]
+- Fix configure to link shared library when testing
+- Add some Windows CE target adjustments [Mai]
+- Remove #define ZLIB_DLL in zconf.h [Vollant]
+- Add zlib.3 [Rodgers]
+- Update RFC URL in deflate.c and algorithm.txt [Mai]
+- Add zlib_dll_FAQ.txt to contrib [Truta]
+- Add UL to some constants [Truta]
+- Update minizip and vstudio [Vollant]
+- Remove vestigial NEED_DUMMY_RETURN from zconf.in.h
+- Expand use of NO_DUMMY_DECL to avoid all dummy structures
+- Added iostream3 to contrib [Schwardt]
+- Replace rewind() with fseek() for WinCE [Truta]
+- Improve setting of zlib format compression level flags
+    - Report 0 for huffman and rle strategies and for level == 0 or 1
+    - Report 2 only for level == 6
+- Only deal with 64K limit when necessary at compile time [Truta]
+- Allow TOO_FAR check to be turned off at compile time [Truta]
+- Add gzclearerr() function [Souza]
+- Add gzungetc() function
+
+Changes in 1.2.0.1 (17 March 2003)
+- Add Z_RLE strategy for run-length encoding [Truta]
+    - When Z_RLE requested, restrict matches to distance one
+    - Update zlib.h, minigzip.c, gzopen(), gzdopen() for Z_RLE
+- Correct FASTEST compilation to allow level == 0
+- Clean up what gets compiled for FASTEST
+- Incorporate changes to zconf.in.h [Vollant]
+    - Refine detection of Turbo C need for dummy returns
+    - Refine ZLIB_DLL compilation
+    - Include additional header file on VMS for off_t typedef
+- Try to use _vsnprintf where it supplants vsprintf [Vollant]
+- Add some casts in inffast.c
+- Enchance comments in zlib.h on what happens if gzprintf() tries to
+  write more than 4095 bytes before compression
+- Remove unused state from inflateBackEnd()
+- Remove exit(0) from minigzip.c, example.c
+- Get rid of all those darn tabs
+- Add "check" target to Makefile.in that does the same thing as "test"
+- Add "mostlyclean" and "maintainer-clean" targets to Makefile.in
+- Update contrib/inflate86 [Anderson]
+- Update contrib/testzlib, contrib/vstudio, contrib/minizip [Vollant]
+- Add msdos and win32 directories with makefiles [Truta]
+- More additions and improvements to the FAQ
+
+Changes in 1.2.0 (9 March 2003)
+- New and improved inflate code
+    - About 20% faster
+    - Does not allocate 32K window unless and until needed
+    - Automatically detects and decompresses gzip streams
+    - Raw inflate no longer needs an extra dummy byte at end
+    - Added inflateBack functions using a callback interface--even faster
+      than inflate, useful for file utilities (gzip, zip)
+    - Added inflateCopy() function to record state for random access on
+      externally generated deflate streams (e.g. in gzip files)
+    - More readable code (I hope)
+- New and improved crc32()
+    - About 50% faster, thanks to suggestions from Rodney Brown
+- Add deflateBound() and compressBound() functions
+- Fix memory leak in deflateInit2()
+- Permit setting dictionary for raw deflate (for parallel deflate)
+- Fix const declaration for gzwrite()
+- Check for some malloc() failures in gzio.c
+- Fix bug in gzopen() on single-byte file 0x1f
+- Fix bug in gzread() on concatenated file with 0x1f at end of buffer
+  and next buffer doesn't start with 0x8b
+- Fix uncompress() to return Z_DATA_ERROR on truncated input
+- Free memory at end of example.c
+- Remove MAX #define in trees.c (conflicted with some libraries)
+- Fix static const's in deflate.c, gzio.c, and zutil.[ch]
+- Declare malloc() and free() in gzio.c if STDC not defined
+- Use malloc() instead of calloc() in zutil.c if int big enough
+- Define STDC for AIX
+- Add aix/ with approach for compiling shared library on AIX
+- Add HP-UX support for shared libraries in configure
+- Add OpenUNIX support for shared libraries in configure
+- Use $cc instead of gcc to build shared library
+- Make prefix directory if needed when installing
+- Correct Macintosh avoidance of typedef Byte in zconf.h
+- Correct Turbo C memory allocation when under Linux
+- Use libz.a instead of -lz in Makefile (assure use of compiled library)
+- Update configure to check for snprintf or vsnprintf functions and their
+  return value, warn during make if using an insecure function
+- Fix configure problem with compile-time knowledge of HAVE_UNISTD_H that
+  is lost when library is used--resolution is to build new zconf.h
+- Documentation improvements (in zlib.h):
+    - Document raw deflate and inflate
+    - Update RFCs URL
+    - Point out that zlib and gzip formats are different
+    - Note that Z_BUF_ERROR is not fatal
+    - Document string limit for gzprintf() and possible buffer overflow
+    - Note requirement on avail_out when flushing
+    - Note permitted values of flush parameter of inflate()
+- Add some FAQs (and even answers) to the FAQ
+- Add contrib/inflate86/ for x86 faster inflate
+- Add contrib/blast/ for PKWare Data Compression Library decompression
+- Add contrib/puff/ simple inflate for deflate format description
+
+Changes in 1.1.4 (11 March 2002)
+- ZFREE was repeated on same allocation on some error conditions.
+  This creates a security problem described in
+  http://www.zlib.org/advisory-2002-03-11.txt
+- Returned incorrect error (Z_MEM_ERROR) on some invalid data
+- Avoid accesses before window for invalid distances with inflate window
+  less than 32K.
+- force windowBits > 8 to avoid a bug in the encoder for a window size
+  of 256 bytes. (A complete fix will be available in 1.1.5).
+
+Changes in 1.1.3 (9 July 1998)
+- fix "an inflate input buffer bug that shows up on rare but persistent
+  occasions" (Mark)
+- fix gzread and gztell for concatenated .gz files (Didier Le Botlan)
+- fix gzseek(..., SEEK_SET) in write mode
+- fix crc check after a gzeek (Frank Faubert)
+- fix miniunzip when the last entry in a zip file is itself a zip file
+  (J Lillge)
+- add contrib/asm586 and contrib/asm686 (Brian Raiter)
+  See http://www.muppetlabs.com/~breadbox/software/assembly.html
+- add support for Delphi 3 in contrib/delphi (Bob Dellaca)
+- add support for C++Builder 3 and Delphi 3 in contrib/delphi2 (Davide Moretti)
+- do not exit prematurely in untgz if 0 at start of block (Magnus Holmgren)
+- use macro EXTERN instead of extern to support DLL for BeOS (Sander Stoks)
+- added a FAQ file
+
+- Support gzdopen on Mac with Metrowerks (Jason Linhart)
+- Do not redefine Byte on Mac (Brad Pettit & Jason Linhart)
+- define SEEK_END too if SEEK_SET is not defined (Albert Chin-A-Young)
+- avoid some warnings with Borland C (Tom Tanner)
+- fix a problem in contrib/minizip/zip.c for 16-bit MSDOS (Gilles Vollant)
+- emulate utime() for WIN32 in contrib/untgz  (Gilles Vollant)
+- allow several arguments to configure (Tim Mooney, Frodo Looijaard)
+- use libdir and includedir in Makefile.in (Tim Mooney)
+- support shared libraries on OSF1 V4 (Tim Mooney)
+- remove so_locations in "make clean"  (Tim Mooney)
+- fix maketree.c compilation error (Glenn, Mark)
+- Python interface to zlib now in Python 1.5 (Jeremy Hylton)
+- new Makefile.riscos (Rich Walker)
+- initialize static descriptors in trees.c for embedded targets (Nick Smith)
+- use "foo-gz" in example.c for RISCOS and VMS (Nick Smith)
+- add the OS/2 files in Makefile.in too (Andrew Zabolotny)
+- fix fdopen and halloc macros for Microsoft C 6.0 (Tom Lane)
+- fix maketree.c to allow clean compilation of inffixed.h (Mark)
+- fix parameter check in deflateCopy (Gunther Nikl)
+- cleanup trees.c, use compressed_len only in debug mode (Christian Spieler)
+- Many portability patches by Christian Spieler:
+  . zutil.c, zutil.h: added "const" for zmem*
+  . Make_vms.com: fixed some typos
+  . Make_vms.com: msdos/Makefile.*: removed zutil.h from some dependency lists
+  . msdos/Makefile.msc: remove "default rtl link library" info from obj files
+  . msdos/Makefile.*: use model-dependent name for the built zlib library
+  . msdos/Makefile.emx, nt/Makefile.emx, nt/Makefile.gcc:
+     new makefiles, for emx (DOS/OS2), emx&rsxnt and mingw32 (Windows 9x / NT)
+- use define instead of typedef for Bytef also for MSC small/medium (Tom Lane)
+- replace __far with _far for better portability (Christian Spieler, Tom Lane)
+- fix test for errno.h in configure (Tim Newsham)
+
+Changes in 1.1.2 (19 March 98)
+- added contrib/minzip, mini zip and unzip based on zlib (Gilles Vollant)
+  See http://www.winimage.com/zLibDll/unzip.html
+- preinitialize the inflate tables for fixed codes, to make the code
+  completely thread safe (Mark)
+- some simplifications and slight speed-up to the inflate code (Mark)
+- fix gzeof on non-compressed files (Allan Schrum)
+- add -std1 option in configure for OSF1 to fix gzprintf (Martin Mokrejs)
+- use default value of 4K for Z_BUFSIZE for 16-bit MSDOS (Tim Wegner + Glenn)
+- added os2/Makefile.def and os2/zlib.def (Andrew Zabolotny)
+- add shared lib support for UNIX_SV4.2MP (MATSUURA Takanori)
+- do not wrap extern "C" around system includes (Tom Lane)
+- mention zlib binding for TCL in README (Andreas Kupries)
+- added amiga/Makefile.pup for Amiga powerUP SAS/C PPC (Andreas Kleinert)
+- allow "make install prefix=..." even after configure (Glenn Randers-Pehrson)
+- allow "configure --prefix $HOME" (Tim Mooney)
+- remove warnings in example.c and gzio.c (Glenn Randers-Pehrson)
+- move Makefile.sas to amiga/Makefile.sas
+
+Changes in 1.1.1 (27 Feb 98)
+- fix macros _tr_tally_* in deflate.h for debug mode  (Glenn Randers-Pehrson)
+- remove block truncation heuristic which had very marginal effect for zlib
+  (smaller lit_bufsize than in gzip 1.2.4) and degraded a little the
+  compression ratio on some files. This also allows inlining _tr_tally for
+  matches in deflate_slow.
+- added msdos/Makefile.w32 for WIN32 Microsoft Visual C++ (Bob Frazier)
+
+Changes in 1.1.0 (24 Feb 98)
+- do not return STREAM_END prematurely in inflate (John Bowler)
+- revert to the zlib 1.0.8 inflate to avoid the gcc 2.8.0 bug (Jeremy Buhler)
+- compile with -DFASTEST to get compression code optimized for speed only
+- in minigzip, try mmap'ing the input file first (Miguel Albrecht)
+- increase size of I/O buffers in minigzip.c and gzio.c (not a big gain
+  on Sun but significant on HP)
+
+- add a pointer to experimental unzip library in README (Gilles Vollant)
+- initialize variable gcc in configure (Chris Herborth)
+
+Changes in 1.0.9 (17 Feb 1998)
+- added gzputs and gzgets functions
+- do not clear eof flag in gzseek (Mark Diekhans)
+- fix gzseek for files in transparent mode (Mark Diekhans)
+- do not assume that vsprintf returns the number of bytes written (Jens Krinke)
+- replace EXPORT with ZEXPORT to avoid conflict with other programs
+- added compress2 in zconf.h, zlib.def, zlib.dnt
+- new asm code from Gilles Vollant in contrib/asm386
+- simplify the inflate code (Mark):
+ . Replace ZALLOC's in huft_build() with single ZALLOC in inflate_blocks_new()
+ . ZALLOC the length list in inflate_trees_fixed() instead of using stack
+ . ZALLOC the value area for huft_build() instead of using stack
+ . Simplify Z_FINISH check in inflate()
+
+- Avoid gcc 2.8.0 comparison bug a little differently than zlib 1.0.8
+- in inftrees.c, avoid cc -O bug on HP (Farshid Elahi)
+- in zconf.h move the ZLIB_DLL stuff earlier to avoid problems with
+  the declaration of FAR (Gilles VOllant)
+- install libz.so* with mode 755 (executable) instead of 644 (Marc Lehmann)
+- read_buf buf parameter of type Bytef* instead of charf*
+- zmemcpy parameters are of type Bytef*, not charf* (Joseph Strout)
+- do not redeclare unlink in minigzip.c for WIN32 (John Bowler)
+- fix check for presence of directories in "make install" (Ian Willis)
+
+Changes in 1.0.8 (27 Jan 1998)
+- fixed offsets in contrib/asm386/gvmat32.asm (Gilles Vollant)
+- fix gzgetc and gzputc for big endian systems (Markus Oberhumer)
+- added compress2() to allow setting the compression level
+- include sys/types.h to get off_t on some systems (Marc Lehmann & QingLong)
+- use constant arrays for the static trees in trees.c instead of computing
+  them at run time (thanks to Ken Raeburn for this suggestion). To create
+  trees.h, compile with GEN_TREES_H and run "make test".
+- check return code of example in "make test" and display result
+- pass minigzip command line options to file_compress
+- simplifying code of inflateSync to avoid gcc 2.8 bug
+
+- support CC="gcc -Wall" in configure -s (QingLong)
+- avoid a flush caused by ftell in gzopen for write mode (Ken Raeburn)
+- fix test for shared library support to avoid compiler warnings
+- zlib.lib -> zlib.dll in msdos/zlib.rc (Gilles Vollant)
+- check for TARGET_OS_MAC in addition to MACOS (Brad Pettit)
+- do not use fdopen for Metrowerks on Mac (Brad Pettit))
+- add checks for gzputc and gzputc in example.c
+- avoid warnings in gzio.c and deflate.c (Andreas Kleinert)
+- use const for the CRC table (Ken Raeburn)
+- fixed "make uninstall" for shared libraries
+- use Tracev instead of Trace in infblock.c
+- in example.c use correct compressed length for test_sync
+- suppress +vnocompatwarnings in configure for HPUX (not always supported)
+
+Changes in 1.0.7 (20 Jan 1998)
+- fix gzseek which was broken in write mode
+- return error for gzseek to negative absolute position
+- fix configure for Linux (Chun-Chung Chen)
+- increase stack space for MSC (Tim Wegner)
+- get_crc_table and inflateSyncPoint are EXPORTed (Gilles Vollant)
+- define EXPORTVA for gzprintf (Gilles Vollant)
+- added man page zlib.3 (Rick Rodgers)
+- for contrib/untgz, fix makedir() and improve Makefile
+
+- check gzseek in write mode in example.c
+- allocate extra buffer for seeks only if gzseek is actually called
+- avoid signed/unsigned comparisons (Tim Wegner, Gilles Vollant)
+- add inflateSyncPoint in zconf.h
+- fix list of exported functions in nt/zlib.dnt and mdsos/zlib.def
+
+Changes in 1.0.6 (19 Jan 1998)
+- add functions gzprintf, gzputc, gzgetc, gztell, gzeof, gzseek, gzrewind and
+  gzsetparams (thanks to Roland Giersig and Kevin Ruland for some of this code)
+- Fix a deflate bug occurring only with compression level 0 (thanks to
+  Andy Buckler for finding this one).
+- In minigzip, pass transparently also the first byte for .Z files.
+- return Z_BUF_ERROR instead of Z_OK if output buffer full in uncompress()
+- check Z_FINISH in inflate (thanks to Marc Schluper)
+- Implement deflateCopy (thanks to Adam Costello)
+- make static libraries by default in configure, add --shared option.
+- move MSDOS or Windows specific files to directory msdos
+- suppress the notion of partial flush to simplify the interface
+  (but the symbol Z_PARTIAL_FLUSH is kept for compatibility with 1.0.4)
+- suppress history buffer provided by application to simplify the interface
+  (this feature was not implemented anyway in 1.0.4)
+- next_in and avail_in must be initialized before calling inflateInit or
+  inflateInit2
+- add EXPORT in all exported functions (for Windows DLL)
+- added Makefile.nt (thanks to Stephen Williams)
+- added the unsupported "contrib" directory:
+   contrib/asm386/ by Gilles Vollant <info@winimage.com>
+        386 asm code replacing longest_match().
+   contrib/iostream/ by Kevin Ruland <kevin@rodin.wustl.edu>
+        A C++ I/O streams interface to the zlib gz* functions
+   contrib/iostream2/  by Tyge Løvset <Tyge.Lovset@cmr.no>
+        Another C++ I/O streams interface
+   contrib/untgz/  by "Pedro A. Aranda Guti\irrez" <paag@tid.es>
+        A very simple tar.gz file extractor using zlib
+   contrib/visual-basic.txt by Carlos Rios <c_rios@sonda.cl>
+        How to use compress(), uncompress() and the gz* functions from VB.
+- pass params -f (filtered data), -h (huffman only), -1 to -9 (compression
+  level) in minigzip (thanks to Tom Lane)
+
+- use const for rommable constants in deflate
+- added test for gzseek and gztell in example.c
+- add undocumented function inflateSyncPoint() (hack for Paul Mackerras)
+- add undocumented function zError to convert error code to string
+  (for Tim Smithers)
+- Allow compilation of gzio with -DNO_DEFLATE to avoid the compression code.
+- Use default memcpy for Symantec MSDOS compiler.
+- Add EXPORT keyword for check_func (needed for Windows DLL)
+- add current directory to LD_LIBRARY_PATH for "make test"
+- create also a link for libz.so.1
+- added support for FUJITSU UXP/DS (thanks to Toshiaki Nomura)
+- use $(SHAREDLIB) instead of libz.so in Makefile.in (for HPUX)
+- added -soname for Linux in configure (Chun-Chung Chen,
+- assign numbers to the exported functions in zlib.def (for Windows DLL)
+- add advice in zlib.h for best usage of deflateSetDictionary
+- work around compiler bug on Atari (cast Z_NULL in call of s->checkfn)
+- allow compilation with ANSI keywords only enabled for TurboC in large model
+- avoid "versionString"[0] (Borland bug)
+- add NEED_DUMMY_RETURN for Borland
+- use variable z_verbose for tracing in debug mode (L. Peter Deutsch).
+- allow compilation with CC
+- defined STDC for OS/2 (David Charlap)
+- limit external names to 8 chars for MVS (Thomas Lund)
+- in minigzip.c, use static buffers only for 16-bit systems
+- fix suffix check for "minigzip -d foo.gz"
+- do not return an error for the 2nd of two consecutive gzflush() (Felix Lee)
+- use _fdopen instead of fdopen for MSC >= 6.0 (Thomas Fanslau)
+- added makelcc.bat for lcc-win32 (Tom St Denis)
+- in Makefile.dj2, use copy and del instead of install and rm (Frank Donahoe)
+- Avoid expanded $Id$. Use "rcs -kb" or "cvs admin -kb" to avoid Id expansion.
+- check for unistd.h in configure (for off_t)
+- remove useless check parameter in inflate_blocks_free
+- avoid useless assignment of s->check to itself in inflate_blocks_new
+- do not flush twice in gzclose (thanks to Ken Raeburn)
+- rename FOPEN as F_OPEN to avoid clash with /usr/include/sys/file.h
+- use NO_ERRNO_H instead of enumeration of operating systems with errno.h
+- work around buggy fclose on pipes for HP/UX
+- support zlib DLL with BORLAND C++ 5.0 (thanks to Glenn Randers-Pehrson)
+- fix configure if CC is already equal to gcc
+
+Changes in 1.0.5 (3 Jan 98)
+- Fix inflate to terminate gracefully when fed corrupted or invalid data
+- Use const for rommable constants in inflate
+- Eliminate memory leaks on error conditions in inflate
+- Removed some vestigial code in inflate
+- Update web address in README
+
+Changes in 1.0.4 (24 Jul 96)
+- In very rare conditions, deflate(s, Z_FINISH) could fail to produce an EOF
+  bit, so the decompressor could decompress all the correct data but went
+  on to attempt decompressing extra garbage data. This affected minigzip too.
+- zlibVersion and gzerror return const char* (needed for DLL)
+- port to RISCOS (no fdopen, no multiple dots, no unlink, no fileno)
+- use z_error only for DEBUG (avoid problem with DLLs)
+
+Changes in 1.0.3 (2 Jul 96)
+- use z_streamp instead of z_stream *, which is now a far pointer in MSDOS
+  small and medium models; this makes the library incompatible with previous
+  versions for these models. (No effect in large model or on other systems.)
+- return OK instead of BUF_ERROR if previous deflate call returned with
+  avail_out as zero but there is nothing to do
+- added memcmp for non STDC compilers
+- define NO_DUMMY_DECL for more Mac compilers (.h files merged incorrectly)
+- define __32BIT__ if __386__ or i386 is defined (pb. with Watcom and SCO)
+- better check for 16-bit mode MSC (avoids problem with Symantec)
+
+Changes in 1.0.2 (23 May 96)
+- added Windows DLL support
+- added a function zlibVersion (for the DLL support)
+- fixed declarations using Bytef in infutil.c (pb with MSDOS medium model)
+- Bytef is define's instead of typedef'd only for Borland C
+- avoid reading uninitialized memory in example.c
+- mention in README that the zlib format is now RFC1950
+- updated Makefile.dj2
+- added algorithm.doc
+
+Changes in 1.0.1 (20 May 96) [1.0 skipped to avoid confusion]
+- fix array overlay in deflate.c which sometimes caused bad compressed data
+- fix inflate bug with empty stored block
+- fix MSDOS medium model which was broken in 0.99
+- fix deflateParams() which could generate bad compressed data.
+- Bytef is define'd instead of typedef'ed (work around Borland bug)
+- added an INDEX file
+- new makefiles for DJGPP (Makefile.dj2), 32-bit Borland (Makefile.b32),
+  Watcom (Makefile.wat), Amiga SAS/C (Makefile.sas)
+- speed up adler32 for modern machines without auto-increment
+- added -ansi for IRIX in configure
+- static_init_done in trees.c is an int
+- define unlink as delete for VMS
+- fix configure for QNX
+- add configure branch for SCO and HPUX
+- avoid many warnings (unused variables, dead assignments, etc...)
+- no fdopen for BeOS
+- fix the Watcom fix for 32 bit mode (define FAR as empty)
+- removed redefinition of Byte for MKWERKS
+- work around an MWKERKS bug (incorrect merge of all .h files)
+
+Changes in 0.99 (27 Jan 96)
+- allow preset dictionary shared between compressor and decompressor
+- allow compression level 0 (no compression)
+- add deflateParams in zlib.h: allow dynamic change of compression level
+  and compression strategy.
+- test large buffers and deflateParams in example.c
+- add optional "configure" to build zlib as a shared library
+- suppress Makefile.qnx, use configure instead
+- fixed deflate for 64-bit systems (detected on Cray)
+- fixed inflate_blocks for 64-bit systems (detected on Alpha)
+- declare Z_DEFLATED in zlib.h (possible parameter for deflateInit2)
+- always return Z_BUF_ERROR when deflate() has nothing to do
+- deflateInit and inflateInit are now macros to allow version checking
+- prefix all global functions and types with z_ with -DZ_PREFIX
+- make falloc completely reentrant (inftrees.c)
+- fixed very unlikely race condition in ct_static_init
+- free in reverse order of allocation to help memory manager
+- use zlib-1.0/* instead of zlib/* inside the tar.gz
+- make zlib warning-free with "gcc -O3 -Wall -Wwrite-strings -Wpointer-arith
+  -Wconversion -Wstrict-prototypes -Wmissing-prototypes"
+- allow gzread on concatenated .gz files
+- deflateEnd now returns Z_DATA_ERROR if it was premature
+- deflate is finally (?) fully deterministic (no matches beyond end of input)
+- Document Z_SYNC_FLUSH
+- add uninstall in Makefile
+- Check for __cpluplus in zlib.h
+- Better test in ct_align for partial flush
+- avoid harmless warnings for Borland C++
+- initialize hash_head in deflate.c
+- avoid warning on fdopen (gzio.c) for HP cc -Aa
+- include stdlib.h for STDC compilers
+- include errno.h for Cray
+- ignore error if ranlib doesn't exist
+- call ranlib twice for NeXTSTEP
+- use exec_prefix instead of prefix for libz.a
+- renamed ct_* as _tr_* to avoid conflict with applications
+- clear z->msg in inflateInit2 before any error return
+- initialize opaque in example.c, gzio.c, deflate.c and inflate.c
+- fixed typo in zconf.h (_GNUC__ => __GNUC__)
+- check for WIN32 in zconf.h and zutil.c (avoid farmalloc in 32-bit mode)
+- fix typo in Make_vms.com (f$trnlnm -> f$getsyi)
+- in fcalloc, normalize pointer if size > 65520 bytes
+- don't use special fcalloc for 32 bit Borland C++
+- use STDC instead of __GO32__ to avoid redeclaring exit, calloc, etc...
+- use Z_BINARY instead of BINARY
+- document that gzclose after gzdopen will close the file
+- allow "a" as mode in gzopen.
+- fix error checking in gzread
+- allow skipping .gz extra-field on pipes
+- added reference to Perl interface in README
+- put the crc table in FAR data (I dislike more and more the medium model :)
+- added get_crc_table
+- added a dimension to all arrays (Borland C can't count).
+- workaround Borland C bug in declaration of inflate_codes_new & inflate_fast
+- guard against multiple inclusion of *.h (for precompiled header on Mac)
+- Watcom C pretends to be Microsoft C small model even in 32 bit mode.
+- don't use unsized arrays to avoid silly warnings by Visual C++:
+     warning C4746: 'inflate_mask' : unsized array treated as  '__far'
+     (what's wrong with far data in far model?).
+- define enum out of inflate_blocks_state to allow compilation with C++
+
+Changes in 0.95 (16 Aug 95)
+- fix MSDOS small and medium model (now easier to adapt to any compiler)
+- inlined send_bits
+- fix the final (:-) bug for deflate with flush (output was correct but
+  not completely flushed in rare occasions).
+- default window size is same for compression and decompression
+  (it's now sufficient to set MAX_WBITS in zconf.h).
+- voidp -> voidpf and voidnp -> voidp (for consistency with other
+  typedefs and because voidnp was not near in large model).
+
+Changes in 0.94 (13 Aug 95)
+- support MSDOS medium model
+- fix deflate with flush (could sometimes generate bad output)
+- fix deflateReset (zlib header was incorrectly suppressed)
+- added support for VMS
+- allow a compression level in gzopen()
+- gzflush now calls fflush
+- For deflate with flush, flush even if no more input is provided.
+- rename libgz.a as libz.a
+- avoid complex expression in infcodes.c triggering Turbo C bug
+- work around a problem with gcc on Alpha (in INSERT_STRING)
+- don't use inline functions (problem with some gcc versions)
+- allow renaming of Byte, uInt, etc... with #define.
+- avoid warning about (unused) pointer before start of array in deflate.c
+- avoid various warnings in gzio.c, example.c, infblock.c, adler32.c, zutil.c
+- avoid reserved word 'new' in trees.c
+
+Changes in 0.93 (25 June 95)
+- temporarily disable inline functions
+- make deflate deterministic
+- give enough lookahead for PARTIAL_FLUSH
+- Set binary mode for stdin/stdout in minigzip.c for OS/2
+- don't even use signed char in inflate (not portable enough)
+- fix inflate memory leak for segmented architectures
+
+Changes in 0.92 (3 May 95)
+- don't assume that char is signed (problem on SGI)
+- Clear bit buffer when starting a stored block
+- no memcpy on Pyramid
+- suppressed inftest.c
+- optimized fill_window, put longest_match inline for gcc
+- optimized inflate on stored blocks.
+- untabify all sources to simplify patches
+
+Changes in 0.91 (2 May 95)
+- Default MEM_LEVEL is 8 (not 9 for Unix) as documented in zlib.h
+- Document the memory requirements in zconf.h
+- added "make install"
+- fix sync search logic in inflateSync
+- deflate(Z_FULL_FLUSH) now works even if output buffer too short
+- after inflateSync, don't scare people with just "lo world"
+- added support for DJGPP
+
+Changes in 0.9 (1 May 95)
+- don't assume that zalloc clears the allocated memory (the TurboC bug
+  was Mark's bug after all :)
+- let again gzread copy uncompressed data unchanged (was working in 0.71)
+- deflate(Z_FULL_FLUSH), inflateReset and inflateSync are now fully implemented
+- added a test of inflateSync in example.c
+- moved MAX_WBITS to zconf.h because users might want to change that.
+- document explicitly that zalloc(64K) on MSDOS must return a normalized
+  pointer (zero offset)
+- added Makefiles for Microsoft C, Turbo C, Borland C++
+- faster crc32()
+
+Changes in 0.8 (29 April 95)
+- added fast inflate (inffast.c)
+- deflate(Z_FINISH) now returns Z_STREAM_END when done. Warning: this
+  is incompatible with previous versions of zlib which returned Z_OK.
+- work around a TurboC compiler bug (bad code for b << 0, see infutil.h)
+  (actually that was not a compiler bug, see 0.81 above)
+- gzread no longer reads one extra byte in certain cases
+- In gzio destroy(), don't reference a freed structure
+- avoid many warnings for MSDOS
+- avoid the ERROR symbol which is used by MS Windows
+
+Changes in 0.71 (14 April 95)
+- Fixed more MSDOS compilation problems :( There is still a bug with
+  TurboC large model.
+
+Changes in 0.7 (14 April 95)
+- Added full inflate support.
+- Simplified the crc32() interface. The pre- and post-conditioning
+  (one's complement) is now done inside crc32(). WARNING: this is
+  incompatible with previous versions; see zlib.h for the new usage.
+
+Changes in 0.61 (12 April 95)
+- workaround for a bug in TurboC. example and minigzip now work on MSDOS.
+
+Changes in 0.6 (11 April 95)
+- added minigzip.c
+- added gzdopen to reopen a file descriptor as gzFile
+- added transparent reading of non-gziped files in gzread.
+- fixed bug in gzread (don't read crc as data)
+- fixed bug in destroy (gzio.c) (don't return Z_STREAM_END for gzclose).
+- don't allocate big arrays in the stack (for MSDOS)
+- fix some MSDOS compilation problems
+
+Changes in 0.5:
+- do real compression in deflate.c. Z_PARTIAL_FLUSH is supported but
+  not yet Z_FULL_FLUSH.
+- support decompression but only in a single step (forced Z_FINISH)
+- added opaque object for zalloc and zfree.
+- added deflateReset and inflateReset
+- added a variable zlib_version for consistency checking.
+- renamed the 'filter' parameter of deflateInit2 as 'strategy'.
+  Added Z_FILTERED and Z_HUFFMAN_ONLY constants.
+
+Changes in 0.4:
+- avoid "zip" everywhere, use zlib instead of ziplib.
+- suppress Z_BLOCK_FLUSH, interpret Z_PARTIAL_FLUSH as block flush
+  if compression method == 8.
+- added adler32 and crc32
+- renamed deflateOptions as deflateInit2, call one or the other but not both
+- added the method parameter for deflateInit2.
+- added inflateInit2
+- simplied considerably deflateInit and inflateInit by not supporting
+  user-provided history buffer. This is supported only in deflateInit2
+  and inflateInit2.
+
+Changes in 0.3:
+- prefix all macro names with Z_
+- use Z_FINISH instead of deflateEnd to finish compression.
+- added Z_HUFFMAN_ONLY
+- added gzerror()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/README	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,115 @@
+ZLIB DATA COMPRESSION LIBRARY
+
+zlib 1.2.11 is a general purpose data compression library.  All the code is
+thread safe.  The data format used by the zlib library is described by RFCs
+(Request for Comments) 1950 to 1952 in the files
+http://tools.ietf.org/html/rfc1950 (zlib format), rfc1951 (deflate format) and
+rfc1952 (gzip format).
+
+All functions of the compression library are documented in the file zlib.h
+(volunteer to write man pages welcome, contact zlib@gzip.org).  A usage example
+of the library is given in the file test/example.c which also tests that
+the library is working correctly.  Another example is given in the file
+test/minigzip.c.  The compression library itself is composed of all source
+files in the root directory.
+
+To compile all files and run the test program, follow the instructions given at
+the top of Makefile.in.  In short "./configure; make test", and if that goes
+well, "make install" should work for most flavors of Unix.  For Windows, use
+one of the special makefiles in win32/ or contrib/vstudio/ .  For VMS, use
+make_vms.com.
+
+Questions about zlib should be sent to <zlib@gzip.org>, or to Gilles Vollant
+<info@winimage.com> for the Windows DLL version.  The zlib home page is
+http://zlib.net/ .  Before reporting a problem, please check this site to
+verify that you have the latest version of zlib; otherwise get the latest
+version and check whether the problem still exists or not.
+
+PLEASE read the zlib FAQ http://zlib.net/zlib_faq.html before asking for help.
+
+Mark Nelson <markn@ieee.org> wrote an article about zlib for the Jan.  1997
+issue of Dr.  Dobb's Journal; a copy of the article is available at
+http://marknelson.us/1997/01/01/zlib-engine/ .
+
+The changes made in version 1.2.11 are documented in the file ChangeLog.
+
+Unsupported third party contributions are provided in directory contrib/ .
+
+zlib is available in Java using the java.util.zip package, documented at
+http://java.sun.com/developer/technicalArticles/Programming/compression/ .
+
+A Perl interface to zlib written by Paul Marquess <pmqs@cpan.org> is available
+at CPAN (Comprehensive Perl Archive Network) sites, including
+http://search.cpan.org/~pmqs/IO-Compress-Zlib/ .
+
+A Python interface to zlib written by A.M. Kuchling <amk@amk.ca> is
+available in Python 1.5 and later versions, see
+http://docs.python.org/library/zlib.html .
+
+zlib is built into tcl: http://wiki.tcl.tk/4610 .
+
+An experimental package to read and write files in .zip format, written on top
+of zlib by Gilles Vollant <info@winimage.com>, is available in the
+contrib/minizip directory of zlib.
+
+
+Notes for some targets:
+
+- For Windows DLL versions, please see win32/DLL_FAQ.txt
+
+- For 64-bit Irix, deflate.c must be compiled without any optimization. With
+  -O, one libpng test fails. The test works in 32 bit mode (with the -n32
+  compiler flag). The compiler bug has been reported to SGI.
+
+- zlib doesn't work with gcc 2.6.3 on a DEC 3000/300LX under OSF/1 2.1 it works
+  when compiled with cc.
+
+- On Digital Unix 4.0D (formely OSF/1) on AlphaServer, the cc option -std1 is
+  necessary to get gzprintf working correctly. This is done by configure.
+
+- zlib doesn't work on HP-UX 9.05 with some versions of /bin/cc. It works with
+  other compilers. Use "make test" to check your compiler.
+
+- gzdopen is not supported on RISCOS or BEOS.
+
+- For PalmOs, see http://palmzlib.sourceforge.net/
+
+
+Acknowledgments:
+
+  The deflate format used by zlib was defined by Phil Katz.  The deflate and
+  zlib specifications were written by L.  Peter Deutsch.  Thanks to all the
+  people who reported problems and suggested various improvements in zlib; they
+  are too numerous to cite here.
+
+Copyright notice:
+
+ (C) 1995-2017 Jean-loup Gailly and Mark Adler
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Jean-loup Gailly        Mark Adler
+  jloup@gzip.org          madler@alumni.caltech.edu
+
+If you use the zlib library in a product, we would appreciate *not* receiving
+lengthy legal documents to sign.  The sources are provided for free but without
+warranty of any kind.  The library has been entirely written by Jean-loup
+Gailly and Mark Adler; it does not include third-party code.
+
+If you redistribute modified sources, we would appreciate that you include in
+the file ChangeLog history information documenting your changes.  Please read
+the FAQ for more information on the distribution of modified source versions.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/compress.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,110 @@
+/*
+ * 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.
+ */
+
+/* compress.c -- compress a memory buffer
+ * Copyright (C) 1995-2005, 2014, 2016 Jean-loup Gailly, Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#define ZLIB_INTERNAL
+#include "zlib.h"
+
+/* ===========================================================================
+     Compresses the source buffer into the destination buffer. The level
+   parameter has the same meaning as in deflateInit.  sourceLen is the byte
+   length of the source buffer. Upon entry, destLen is the total size of the
+   destination buffer, which must be at least 0.1% larger than sourceLen plus
+   12 bytes. Upon exit, destLen is the actual size of the compressed buffer.
+
+     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_BUF_ERROR if there was not enough room in the output buffer,
+   Z_STREAM_ERROR if the level parameter is invalid.
+*/
+int ZEXPORT compress2 (dest, destLen, source, sourceLen, level)
+    Bytef *dest;
+    uLongf *destLen;
+    const Bytef *source;
+    uLong sourceLen;
+    int level;
+{
+    z_stream stream;
+    int err;
+    const uInt max = (uInt)-1;
+    uLong left;
+
+    left = *destLen;
+    *destLen = 0;
+
+    stream.zalloc = (alloc_func)0;
+    stream.zfree = (free_func)0;
+    stream.opaque = (voidpf)0;
+
+    err = deflateInit(&stream, level);
+    if (err != Z_OK) return err;
+
+    stream.next_out = dest;
+    stream.avail_out = 0;
+    stream.next_in = (z_const Bytef *)source;
+    stream.avail_in = 0;
+
+    do {
+        if (stream.avail_out == 0) {
+            stream.avail_out = left > (uLong)max ? max : (uInt)left;
+            left -= stream.avail_out;
+        }
+        if (stream.avail_in == 0) {
+            stream.avail_in = sourceLen > (uLong)max ? max : (uInt)sourceLen;
+            sourceLen -= stream.avail_in;
+        }
+        err = deflate(&stream, sourceLen ? Z_NO_FLUSH : Z_FINISH);
+    } while (err == Z_OK);
+
+    *destLen = stream.total_out;
+    deflateEnd(&stream);
+    return err == Z_STREAM_END ? Z_OK : err;
+}
+
+/* ===========================================================================
+ */
+int ZEXPORT compress (dest, destLen, source, sourceLen)
+    Bytef *dest;
+    uLongf *destLen;
+    const Bytef *source;
+    uLong sourceLen;
+{
+    return compress2(dest, destLen, source, sourceLen, Z_DEFAULT_COMPRESSION);
+}
+
+/* ===========================================================================
+     If the default memLevel or windowBits for deflateInit() is changed, then
+   this function needs to be updated.
+ */
+uLong ZEXPORT compressBound (sourceLen)
+    uLong sourceLen;
+{
+    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
+           (sourceLen >> 25) + 13;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/crc32.h	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,465 @@
+/*
+ * 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.
+ */
+
+/* crc32.h -- tables for rapid CRC calculation
+ * Generated automatically by crc32.c
+ */
+
+local const z_crc_t FAR crc_table[TBLS][256] =
+{
+  {
+    0x00000000UL, 0x77073096UL, 0xee0e612cUL, 0x990951baUL, 0x076dc419UL,
+    0x706af48fUL, 0xe963a535UL, 0x9e6495a3UL, 0x0edb8832UL, 0x79dcb8a4UL,
+    0xe0d5e91eUL, 0x97d2d988UL, 0x09b64c2bUL, 0x7eb17cbdUL, 0xe7b82d07UL,
+    0x90bf1d91UL, 0x1db71064UL, 0x6ab020f2UL, 0xf3b97148UL, 0x84be41deUL,
+    0x1adad47dUL, 0x6ddde4ebUL, 0xf4d4b551UL, 0x83d385c7UL, 0x136c9856UL,
+    0x646ba8c0UL, 0xfd62f97aUL, 0x8a65c9ecUL, 0x14015c4fUL, 0x63066cd9UL,
+    0xfa0f3d63UL, 0x8d080df5UL, 0x3b6e20c8UL, 0x4c69105eUL, 0xd56041e4UL,
+    0xa2677172UL, 0x3c03e4d1UL, 0x4b04d447UL, 0xd20d85fdUL, 0xa50ab56bUL,
+    0x35b5a8faUL, 0x42b2986cUL, 0xdbbbc9d6UL, 0xacbcf940UL, 0x32d86ce3UL,
+    0x45df5c75UL, 0xdcd60dcfUL, 0xabd13d59UL, 0x26d930acUL, 0x51de003aUL,
+    0xc8d75180UL, 0xbfd06116UL, 0x21b4f4b5UL, 0x56b3c423UL, 0xcfba9599UL,
+    0xb8bda50fUL, 0x2802b89eUL, 0x5f058808UL, 0xc60cd9b2UL, 0xb10be924UL,
+    0x2f6f7c87UL, 0x58684c11UL, 0xc1611dabUL, 0xb6662d3dUL, 0x76dc4190UL,
+    0x01db7106UL, 0x98d220bcUL, 0xefd5102aUL, 0x71b18589UL, 0x06b6b51fUL,
+    0x9fbfe4a5UL, 0xe8b8d433UL, 0x7807c9a2UL, 0x0f00f934UL, 0x9609a88eUL,
+    0xe10e9818UL, 0x7f6a0dbbUL, 0x086d3d2dUL, 0x91646c97UL, 0xe6635c01UL,
+    0x6b6b51f4UL, 0x1c6c6162UL, 0x856530d8UL, 0xf262004eUL, 0x6c0695edUL,
+    0x1b01a57bUL, 0x8208f4c1UL, 0xf50fc457UL, 0x65b0d9c6UL, 0x12b7e950UL,
+    0x8bbeb8eaUL, 0xfcb9887cUL, 0x62dd1ddfUL, 0x15da2d49UL, 0x8cd37cf3UL,
+    0xfbd44c65UL, 0x4db26158UL, 0x3ab551ceUL, 0xa3bc0074UL, 0xd4bb30e2UL,
+    0x4adfa541UL, 0x3dd895d7UL, 0xa4d1c46dUL, 0xd3d6f4fbUL, 0x4369e96aUL,
+    0x346ed9fcUL, 0xad678846UL, 0xda60b8d0UL, 0x44042d73UL, 0x33031de5UL,
+    0xaa0a4c5fUL, 0xdd0d7cc9UL, 0x5005713cUL, 0x270241aaUL, 0xbe0b1010UL,
+    0xc90c2086UL, 0x5768b525UL, 0x206f85b3UL, 0xb966d409UL, 0xce61e49fUL,
+    0x5edef90eUL, 0x29d9c998UL, 0xb0d09822UL, 0xc7d7a8b4UL, 0x59b33d17UL,
+    0x2eb40d81UL, 0xb7bd5c3bUL, 0xc0ba6cadUL, 0xedb88320UL, 0x9abfb3b6UL,
+    0x03b6e20cUL, 0x74b1d29aUL, 0xead54739UL, 0x9dd277afUL, 0x04db2615UL,
+    0x73dc1683UL, 0xe3630b12UL, 0x94643b84UL, 0x0d6d6a3eUL, 0x7a6a5aa8UL,
+    0xe40ecf0bUL, 0x9309ff9dUL, 0x0a00ae27UL, 0x7d079eb1UL, 0xf00f9344UL,
+    0x8708a3d2UL, 0x1e01f268UL, 0x6906c2feUL, 0xf762575dUL, 0x806567cbUL,
+    0x196c3671UL, 0x6e6b06e7UL, 0xfed41b76UL, 0x89d32be0UL, 0x10da7a5aUL,
+    0x67dd4accUL, 0xf9b9df6fUL, 0x8ebeeff9UL, 0x17b7be43UL, 0x60b08ed5UL,
+    0xd6d6a3e8UL, 0xa1d1937eUL, 0x38d8c2c4UL, 0x4fdff252UL, 0xd1bb67f1UL,
+    0xa6bc5767UL, 0x3fb506ddUL, 0x48b2364bUL, 0xd80d2bdaUL, 0xaf0a1b4cUL,
+    0x36034af6UL, 0x41047a60UL, 0xdf60efc3UL, 0xa867df55UL, 0x316e8eefUL,
+    0x4669be79UL, 0xcb61b38cUL, 0xbc66831aUL, 0x256fd2a0UL, 0x5268e236UL,
+    0xcc0c7795UL, 0xbb0b4703UL, 0x220216b9UL, 0x5505262fUL, 0xc5ba3bbeUL,
+    0xb2bd0b28UL, 0x2bb45a92UL, 0x5cb36a04UL, 0xc2d7ffa7UL, 0xb5d0cf31UL,
+    0x2cd99e8bUL, 0x5bdeae1dUL, 0x9b64c2b0UL, 0xec63f226UL, 0x756aa39cUL,
+    0x026d930aUL, 0x9c0906a9UL, 0xeb0e363fUL, 0x72076785UL, 0x05005713UL,
+    0x95bf4a82UL, 0xe2b87a14UL, 0x7bb12baeUL, 0x0cb61b38UL, 0x92d28e9bUL,
+    0xe5d5be0dUL, 0x7cdcefb7UL, 0x0bdbdf21UL, 0x86d3d2d4UL, 0xf1d4e242UL,
+    0x68ddb3f8UL, 0x1fda836eUL, 0x81be16cdUL, 0xf6b9265bUL, 0x6fb077e1UL,
+    0x18b74777UL, 0x88085ae6UL, 0xff0f6a70UL, 0x66063bcaUL, 0x11010b5cUL,
+    0x8f659effUL, 0xf862ae69UL, 0x616bffd3UL, 0x166ccf45UL, 0xa00ae278UL,
+    0xd70dd2eeUL, 0x4e048354UL, 0x3903b3c2UL, 0xa7672661UL, 0xd06016f7UL,
+    0x4969474dUL, 0x3e6e77dbUL, 0xaed16a4aUL, 0xd9d65adcUL, 0x40df0b66UL,
+    0x37d83bf0UL, 0xa9bcae53UL, 0xdebb9ec5UL, 0x47b2cf7fUL, 0x30b5ffe9UL,
+    0xbdbdf21cUL, 0xcabac28aUL, 0x53b39330UL, 0x24b4a3a6UL, 0xbad03605UL,
+    0xcdd70693UL, 0x54de5729UL, 0x23d967bfUL, 0xb3667a2eUL, 0xc4614ab8UL,
+    0x5d681b02UL, 0x2a6f2b94UL, 0xb40bbe37UL, 0xc30c8ea1UL, 0x5a05df1bUL,
+    0x2d02ef8dUL
+#ifdef BYFOUR
+  },
+  {
+    0x00000000UL, 0x191b3141UL, 0x32366282UL, 0x2b2d53c3UL, 0x646cc504UL,
+    0x7d77f445UL, 0x565aa786UL, 0x4f4196c7UL, 0xc8d98a08UL, 0xd1c2bb49UL,
+    0xfaefe88aUL, 0xe3f4d9cbUL, 0xacb54f0cUL, 0xb5ae7e4dUL, 0x9e832d8eUL,
+    0x87981ccfUL, 0x4ac21251UL, 0x53d92310UL, 0x78f470d3UL, 0x61ef4192UL,
+    0x2eaed755UL, 0x37b5e614UL, 0x1c98b5d7UL, 0x05838496UL, 0x821b9859UL,
+    0x9b00a918UL, 0xb02dfadbUL, 0xa936cb9aUL, 0xe6775d5dUL, 0xff6c6c1cUL,
+    0xd4413fdfUL, 0xcd5a0e9eUL, 0x958424a2UL, 0x8c9f15e3UL, 0xa7b24620UL,
+    0xbea97761UL, 0xf1e8e1a6UL, 0xe8f3d0e7UL, 0xc3de8324UL, 0xdac5b265UL,
+    0x5d5daeaaUL, 0x44469febUL, 0x6f6bcc28UL, 0x7670fd69UL, 0x39316baeUL,
+    0x202a5aefUL, 0x0b07092cUL, 0x121c386dUL, 0xdf4636f3UL, 0xc65d07b2UL,
+    0xed705471UL, 0xf46b6530UL, 0xbb2af3f7UL, 0xa231c2b6UL, 0x891c9175UL,
+    0x9007a034UL, 0x179fbcfbUL, 0x0e848dbaUL, 0x25a9de79UL, 0x3cb2ef38UL,
+    0x73f379ffUL, 0x6ae848beUL, 0x41c51b7dUL, 0x58de2a3cUL, 0xf0794f05UL,
+    0xe9627e44UL, 0xc24f2d87UL, 0xdb541cc6UL, 0x94158a01UL, 0x8d0ebb40UL,
+    0xa623e883UL, 0xbf38d9c2UL, 0x38a0c50dUL, 0x21bbf44cUL, 0x0a96a78fUL,
+    0x138d96ceUL, 0x5ccc0009UL, 0x45d73148UL, 0x6efa628bUL, 0x77e153caUL,
+    0xbabb5d54UL, 0xa3a06c15UL, 0x888d3fd6UL, 0x91960e97UL, 0xded79850UL,
+    0xc7cca911UL, 0xece1fad2UL, 0xf5facb93UL, 0x7262d75cUL, 0x6b79e61dUL,
+    0x4054b5deUL, 0x594f849fUL, 0x160e1258UL, 0x0f152319UL, 0x243870daUL,
+    0x3d23419bUL, 0x65fd6ba7UL, 0x7ce65ae6UL, 0x57cb0925UL, 0x4ed03864UL,
+    0x0191aea3UL, 0x188a9fe2UL, 0x33a7cc21UL, 0x2abcfd60UL, 0xad24e1afUL,
+    0xb43fd0eeUL, 0x9f12832dUL, 0x8609b26cUL, 0xc94824abUL, 0xd05315eaUL,
+    0xfb7e4629UL, 0xe2657768UL, 0x2f3f79f6UL, 0x362448b7UL, 0x1d091b74UL,
+    0x04122a35UL, 0x4b53bcf2UL, 0x52488db3UL, 0x7965de70UL, 0x607eef31UL,
+    0xe7e6f3feUL, 0xfefdc2bfUL, 0xd5d0917cUL, 0xcccba03dUL, 0x838a36faUL,
+    0x9a9107bbUL, 0xb1bc5478UL, 0xa8a76539UL, 0x3b83984bUL, 0x2298a90aUL,
+    0x09b5fac9UL, 0x10aecb88UL, 0x5fef5d4fUL, 0x46f46c0eUL, 0x6dd93fcdUL,
+    0x74c20e8cUL, 0xf35a1243UL, 0xea412302UL, 0xc16c70c1UL, 0xd8774180UL,
+    0x9736d747UL, 0x8e2de606UL, 0xa500b5c5UL, 0xbc1b8484UL, 0x71418a1aUL,
+    0x685abb5bUL, 0x4377e898UL, 0x5a6cd9d9UL, 0x152d4f1eUL, 0x0c367e5fUL,
+    0x271b2d9cUL, 0x3e001cddUL, 0xb9980012UL, 0xa0833153UL, 0x8bae6290UL,
+    0x92b553d1UL, 0xddf4c516UL, 0xc4eff457UL, 0xefc2a794UL, 0xf6d996d5UL,
+    0xae07bce9UL, 0xb71c8da8UL, 0x9c31de6bUL, 0x852aef2aUL, 0xca6b79edUL,
+    0xd37048acUL, 0xf85d1b6fUL, 0xe1462a2eUL, 0x66de36e1UL, 0x7fc507a0UL,
+    0x54e85463UL, 0x4df36522UL, 0x02b2f3e5UL, 0x1ba9c2a4UL, 0x30849167UL,
+    0x299fa026UL, 0xe4c5aeb8UL, 0xfdde9ff9UL, 0xd6f3cc3aUL, 0xcfe8fd7bUL,
+    0x80a96bbcUL, 0x99b25afdUL, 0xb29f093eUL, 0xab84387fUL, 0x2c1c24b0UL,
+    0x350715f1UL, 0x1e2a4632UL, 0x07317773UL, 0x4870e1b4UL, 0x516bd0f5UL,
+    0x7a468336UL, 0x635db277UL, 0xcbfad74eUL, 0xd2e1e60fUL, 0xf9ccb5ccUL,
+    0xe0d7848dUL, 0xaf96124aUL, 0xb68d230bUL, 0x9da070c8UL, 0x84bb4189UL,
+    0x03235d46UL, 0x1a386c07UL, 0x31153fc4UL, 0x280e0e85UL, 0x674f9842UL,
+    0x7e54a903UL, 0x5579fac0UL, 0x4c62cb81UL, 0x8138c51fUL, 0x9823f45eUL,
+    0xb30ea79dUL, 0xaa1596dcUL, 0xe554001bUL, 0xfc4f315aUL, 0xd7626299UL,
+    0xce7953d8UL, 0x49e14f17UL, 0x50fa7e56UL, 0x7bd72d95UL, 0x62cc1cd4UL,
+    0x2d8d8a13UL, 0x3496bb52UL, 0x1fbbe891UL, 0x06a0d9d0UL, 0x5e7ef3ecUL,
+    0x4765c2adUL, 0x6c48916eUL, 0x7553a02fUL, 0x3a1236e8UL, 0x230907a9UL,
+    0x0824546aUL, 0x113f652bUL, 0x96a779e4UL, 0x8fbc48a5UL, 0xa4911b66UL,
+    0xbd8a2a27UL, 0xf2cbbce0UL, 0xebd08da1UL, 0xc0fdde62UL, 0xd9e6ef23UL,
+    0x14bce1bdUL, 0x0da7d0fcUL, 0x268a833fUL, 0x3f91b27eUL, 0x70d024b9UL,
+    0x69cb15f8UL, 0x42e6463bUL, 0x5bfd777aUL, 0xdc656bb5UL, 0xc57e5af4UL,
+    0xee530937UL, 0xf7483876UL, 0xb809aeb1UL, 0xa1129ff0UL, 0x8a3fcc33UL,
+    0x9324fd72UL
+  },
+  {
+    0x00000000UL, 0x01c26a37UL, 0x0384d46eUL, 0x0246be59UL, 0x0709a8dcUL,
+    0x06cbc2ebUL, 0x048d7cb2UL, 0x054f1685UL, 0x0e1351b8UL, 0x0fd13b8fUL,
+    0x0d9785d6UL, 0x0c55efe1UL, 0x091af964UL, 0x08d89353UL, 0x0a9e2d0aUL,
+    0x0b5c473dUL, 0x1c26a370UL, 0x1de4c947UL, 0x1fa2771eUL, 0x1e601d29UL,
+    0x1b2f0bacUL, 0x1aed619bUL, 0x18abdfc2UL, 0x1969b5f5UL, 0x1235f2c8UL,
+    0x13f798ffUL, 0x11b126a6UL, 0x10734c91UL, 0x153c5a14UL, 0x14fe3023UL,
+    0x16b88e7aUL, 0x177ae44dUL, 0x384d46e0UL, 0x398f2cd7UL, 0x3bc9928eUL,
+    0x3a0bf8b9UL, 0x3f44ee3cUL, 0x3e86840bUL, 0x3cc03a52UL, 0x3d025065UL,
+    0x365e1758UL, 0x379c7d6fUL, 0x35dac336UL, 0x3418a901UL, 0x3157bf84UL,
+    0x3095d5b3UL, 0x32d36beaUL, 0x331101ddUL, 0x246be590UL, 0x25a98fa7UL,
+    0x27ef31feUL, 0x262d5bc9UL, 0x23624d4cUL, 0x22a0277bUL, 0x20e69922UL,
+    0x2124f315UL, 0x2a78b428UL, 0x2bbade1fUL, 0x29fc6046UL, 0x283e0a71UL,
+    0x2d711cf4UL, 0x2cb376c3UL, 0x2ef5c89aUL, 0x2f37a2adUL, 0x709a8dc0UL,
+    0x7158e7f7UL, 0x731e59aeUL, 0x72dc3399UL, 0x7793251cUL, 0x76514f2bUL,
+    0x7417f172UL, 0x75d59b45UL, 0x7e89dc78UL, 0x7f4bb64fUL, 0x7d0d0816UL,
+    0x7ccf6221UL, 0x798074a4UL, 0x78421e93UL, 0x7a04a0caUL, 0x7bc6cafdUL,
+    0x6cbc2eb0UL, 0x6d7e4487UL, 0x6f38fadeUL, 0x6efa90e9UL, 0x6bb5866cUL,
+    0x6a77ec5bUL, 0x68315202UL, 0x69f33835UL, 0x62af7f08UL, 0x636d153fUL,
+    0x612bab66UL, 0x60e9c151UL, 0x65a6d7d4UL, 0x6464bde3UL, 0x662203baUL,
+    0x67e0698dUL, 0x48d7cb20UL, 0x4915a117UL, 0x4b531f4eUL, 0x4a917579UL,
+    0x4fde63fcUL, 0x4e1c09cbUL, 0x4c5ab792UL, 0x4d98dda5UL, 0x46c49a98UL,
+    0x4706f0afUL, 0x45404ef6UL, 0x448224c1UL, 0x41cd3244UL, 0x400f5873UL,
+    0x4249e62aUL, 0x438b8c1dUL, 0x54f16850UL, 0x55330267UL, 0x5775bc3eUL,
+    0x56b7d609UL, 0x53f8c08cUL, 0x523aaabbUL, 0x507c14e2UL, 0x51be7ed5UL,
+    0x5ae239e8UL, 0x5b2053dfUL, 0x5966ed86UL, 0x58a487b1UL, 0x5deb9134UL,
+    0x5c29fb03UL, 0x5e6f455aUL, 0x5fad2f6dUL, 0xe1351b80UL, 0xe0f771b7UL,
+    0xe2b1cfeeUL, 0xe373a5d9UL, 0xe63cb35cUL, 0xe7fed96bUL, 0xe5b86732UL,
+    0xe47a0d05UL, 0xef264a38UL, 0xeee4200fUL, 0xeca29e56UL, 0xed60f461UL,
+    0xe82fe2e4UL, 0xe9ed88d3UL, 0xebab368aUL, 0xea695cbdUL, 0xfd13b8f0UL,
+    0xfcd1d2c7UL, 0xfe976c9eUL, 0xff5506a9UL, 0xfa1a102cUL, 0xfbd87a1bUL,
+    0xf99ec442UL, 0xf85cae75UL, 0xf300e948UL, 0xf2c2837fUL, 0xf0843d26UL,
+    0xf1465711UL, 0xf4094194UL, 0xf5cb2ba3UL, 0xf78d95faUL, 0xf64fffcdUL,
+    0xd9785d60UL, 0xd8ba3757UL, 0xdafc890eUL, 0xdb3ee339UL, 0xde71f5bcUL,
+    0xdfb39f8bUL, 0xddf521d2UL, 0xdc374be5UL, 0xd76b0cd8UL, 0xd6a966efUL,
+    0xd4efd8b6UL, 0xd52db281UL, 0xd062a404UL, 0xd1a0ce33UL, 0xd3e6706aUL,
+    0xd2241a5dUL, 0xc55efe10UL, 0xc49c9427UL, 0xc6da2a7eUL, 0xc7184049UL,
+    0xc25756ccUL, 0xc3953cfbUL, 0xc1d382a2UL, 0xc011e895UL, 0xcb4dafa8UL,
+    0xca8fc59fUL, 0xc8c97bc6UL, 0xc90b11f1UL, 0xcc440774UL, 0xcd866d43UL,
+    0xcfc0d31aUL, 0xce02b92dUL, 0x91af9640UL, 0x906dfc77UL, 0x922b422eUL,
+    0x93e92819UL, 0x96a63e9cUL, 0x976454abUL, 0x9522eaf2UL, 0x94e080c5UL,
+    0x9fbcc7f8UL, 0x9e7eadcfUL, 0x9c381396UL, 0x9dfa79a1UL, 0x98b56f24UL,
+    0x99770513UL, 0x9b31bb4aUL, 0x9af3d17dUL, 0x8d893530UL, 0x8c4b5f07UL,
+    0x8e0de15eUL, 0x8fcf8b69UL, 0x8a809decUL, 0x8b42f7dbUL, 0x89044982UL,
+    0x88c623b5UL, 0x839a6488UL, 0x82580ebfUL, 0x801eb0e6UL, 0x81dcdad1UL,
+    0x8493cc54UL, 0x8551a663UL, 0x8717183aUL, 0x86d5720dUL, 0xa9e2d0a0UL,
+    0xa820ba97UL, 0xaa6604ceUL, 0xaba46ef9UL, 0xaeeb787cUL, 0xaf29124bUL,
+    0xad6fac12UL, 0xacadc625UL, 0xa7f18118UL, 0xa633eb2fUL, 0xa4755576UL,
+    0xa5b73f41UL, 0xa0f829c4UL, 0xa13a43f3UL, 0xa37cfdaaUL, 0xa2be979dUL,
+    0xb5c473d0UL, 0xb40619e7UL, 0xb640a7beUL, 0xb782cd89UL, 0xb2cddb0cUL,
+    0xb30fb13bUL, 0xb1490f62UL, 0xb08b6555UL, 0xbbd72268UL, 0xba15485fUL,
+    0xb853f606UL, 0xb9919c31UL, 0xbcde8ab4UL, 0xbd1ce083UL, 0xbf5a5edaUL,
+    0xbe9834edUL
+  },
+  {
+    0x00000000UL, 0xb8bc6765UL, 0xaa09c88bUL, 0x12b5afeeUL, 0x8f629757UL,
+    0x37def032UL, 0x256b5fdcUL, 0x9dd738b9UL, 0xc5b428efUL, 0x7d084f8aUL,
+    0x6fbde064UL, 0xd7018701UL, 0x4ad6bfb8UL, 0xf26ad8ddUL, 0xe0df7733UL,
+    0x58631056UL, 0x5019579fUL, 0xe8a530faUL, 0xfa109f14UL, 0x42acf871UL,
+    0xdf7bc0c8UL, 0x67c7a7adUL, 0x75720843UL, 0xcdce6f26UL, 0x95ad7f70UL,
+    0x2d111815UL, 0x3fa4b7fbUL, 0x8718d09eUL, 0x1acfe827UL, 0xa2738f42UL,
+    0xb0c620acUL, 0x087a47c9UL, 0xa032af3eUL, 0x188ec85bUL, 0x0a3b67b5UL,
+    0xb28700d0UL, 0x2f503869UL, 0x97ec5f0cUL, 0x8559f0e2UL, 0x3de59787UL,
+    0x658687d1UL, 0xdd3ae0b4UL, 0xcf8f4f5aUL, 0x7733283fUL, 0xeae41086UL,
+    0x525877e3UL, 0x40edd80dUL, 0xf851bf68UL, 0xf02bf8a1UL, 0x48979fc4UL,
+    0x5a22302aUL, 0xe29e574fUL, 0x7f496ff6UL, 0xc7f50893UL, 0xd540a77dUL,
+    0x6dfcc018UL, 0x359fd04eUL, 0x8d23b72bUL, 0x9f9618c5UL, 0x272a7fa0UL,
+    0xbafd4719UL, 0x0241207cUL, 0x10f48f92UL, 0xa848e8f7UL, 0x9b14583dUL,
+    0x23a83f58UL, 0x311d90b6UL, 0x89a1f7d3UL, 0x1476cf6aUL, 0xaccaa80fUL,
+    0xbe7f07e1UL, 0x06c36084UL, 0x5ea070d2UL, 0xe61c17b7UL, 0xf4a9b859UL,
+    0x4c15df3cUL, 0xd1c2e785UL, 0x697e80e0UL, 0x7bcb2f0eUL, 0xc377486bUL,
+    0xcb0d0fa2UL, 0x73b168c7UL, 0x6104c729UL, 0xd9b8a04cUL, 0x446f98f5UL,
+    0xfcd3ff90UL, 0xee66507eUL, 0x56da371bUL, 0x0eb9274dUL, 0xb6054028UL,
+    0xa4b0efc6UL, 0x1c0c88a3UL, 0x81dbb01aUL, 0x3967d77fUL, 0x2bd27891UL,
+    0x936e1ff4UL, 0x3b26f703UL, 0x839a9066UL, 0x912f3f88UL, 0x299358edUL,
+    0xb4446054UL, 0x0cf80731UL, 0x1e4da8dfUL, 0xa6f1cfbaUL, 0xfe92dfecUL,
+    0x462eb889UL, 0x549b1767UL, 0xec277002UL, 0x71f048bbUL, 0xc94c2fdeUL,
+    0xdbf98030UL, 0x6345e755UL, 0x6b3fa09cUL, 0xd383c7f9UL, 0xc1366817UL,
+    0x798a0f72UL, 0xe45d37cbUL, 0x5ce150aeUL, 0x4e54ff40UL, 0xf6e89825UL,
+    0xae8b8873UL, 0x1637ef16UL, 0x048240f8UL, 0xbc3e279dUL, 0x21e91f24UL,
+    0x99557841UL, 0x8be0d7afUL, 0x335cb0caUL, 0xed59b63bUL, 0x55e5d15eUL,
+    0x47507eb0UL, 0xffec19d5UL, 0x623b216cUL, 0xda874609UL, 0xc832e9e7UL,
+    0x708e8e82UL, 0x28ed9ed4UL, 0x9051f9b1UL, 0x82e4565fUL, 0x3a58313aUL,
+    0xa78f0983UL, 0x1f336ee6UL, 0x0d86c108UL, 0xb53aa66dUL, 0xbd40e1a4UL,
+    0x05fc86c1UL, 0x1749292fUL, 0xaff54e4aUL, 0x322276f3UL, 0x8a9e1196UL,
+    0x982bbe78UL, 0x2097d91dUL, 0x78f4c94bUL, 0xc048ae2eUL, 0xd2fd01c0UL,
+    0x6a4166a5UL, 0xf7965e1cUL, 0x4f2a3979UL, 0x5d9f9697UL, 0xe523f1f2UL,
+    0x4d6b1905UL, 0xf5d77e60UL, 0xe762d18eUL, 0x5fdeb6ebUL, 0xc2098e52UL,
+    0x7ab5e937UL, 0x680046d9UL, 0xd0bc21bcUL, 0x88df31eaUL, 0x3063568fUL,
+    0x22d6f961UL, 0x9a6a9e04UL, 0x07bda6bdUL, 0xbf01c1d8UL, 0xadb46e36UL,
+    0x15080953UL, 0x1d724e9aUL, 0xa5ce29ffUL, 0xb77b8611UL, 0x0fc7e174UL,
+    0x9210d9cdUL, 0x2aacbea8UL, 0x38191146UL, 0x80a57623UL, 0xd8c66675UL,
+    0x607a0110UL, 0x72cfaefeUL, 0xca73c99bUL, 0x57a4f122UL, 0xef189647UL,
+    0xfdad39a9UL, 0x45115eccUL, 0x764dee06UL, 0xcef18963UL, 0xdc44268dUL,
+    0x64f841e8UL, 0xf92f7951UL, 0x41931e34UL, 0x5326b1daUL, 0xeb9ad6bfUL,
+    0xb3f9c6e9UL, 0x0b45a18cUL, 0x19f00e62UL, 0xa14c6907UL, 0x3c9b51beUL,
+    0x842736dbUL, 0x96929935UL, 0x2e2efe50UL, 0x2654b999UL, 0x9ee8defcUL,
+    0x8c5d7112UL, 0x34e11677UL, 0xa9362eceUL, 0x118a49abUL, 0x033fe645UL,
+    0xbb838120UL, 0xe3e09176UL, 0x5b5cf613UL, 0x49e959fdUL, 0xf1553e98UL,
+    0x6c820621UL, 0xd43e6144UL, 0xc68bceaaUL, 0x7e37a9cfUL, 0xd67f4138UL,
+    0x6ec3265dUL, 0x7c7689b3UL, 0xc4caeed6UL, 0x591dd66fUL, 0xe1a1b10aUL,
+    0xf3141ee4UL, 0x4ba87981UL, 0x13cb69d7UL, 0xab770eb2UL, 0xb9c2a15cUL,
+    0x017ec639UL, 0x9ca9fe80UL, 0x241599e5UL, 0x36a0360bUL, 0x8e1c516eUL,
+    0x866616a7UL, 0x3eda71c2UL, 0x2c6fde2cUL, 0x94d3b949UL, 0x090481f0UL,
+    0xb1b8e695UL, 0xa30d497bUL, 0x1bb12e1eUL, 0x43d23e48UL, 0xfb6e592dUL,
+    0xe9dbf6c3UL, 0x516791a6UL, 0xccb0a91fUL, 0x740cce7aUL, 0x66b96194UL,
+    0xde0506f1UL
+  },
+  {
+    0x00000000UL, 0x96300777UL, 0x2c610eeeUL, 0xba510999UL, 0x19c46d07UL,
+    0x8ff46a70UL, 0x35a563e9UL, 0xa395649eUL, 0x3288db0eUL, 0xa4b8dc79UL,
+    0x1ee9d5e0UL, 0x88d9d297UL, 0x2b4cb609UL, 0xbd7cb17eUL, 0x072db8e7UL,
+    0x911dbf90UL, 0x6410b71dUL, 0xf220b06aUL, 0x4871b9f3UL, 0xde41be84UL,
+    0x7dd4da1aUL, 0xebe4dd6dUL, 0x51b5d4f4UL, 0xc785d383UL, 0x56986c13UL,
+    0xc0a86b64UL, 0x7af962fdUL, 0xecc9658aUL, 0x4f5c0114UL, 0xd96c0663UL,
+    0x633d0ffaUL, 0xf50d088dUL, 0xc8206e3bUL, 0x5e10694cUL, 0xe44160d5UL,
+    0x727167a2UL, 0xd1e4033cUL, 0x47d4044bUL, 0xfd850dd2UL, 0x6bb50aa5UL,
+    0xfaa8b535UL, 0x6c98b242UL, 0xd6c9bbdbUL, 0x40f9bcacUL, 0xe36cd832UL,
+    0x755cdf45UL, 0xcf0dd6dcUL, 0x593dd1abUL, 0xac30d926UL, 0x3a00de51UL,
+    0x8051d7c8UL, 0x1661d0bfUL, 0xb5f4b421UL, 0x23c4b356UL, 0x9995bacfUL,
+    0x0fa5bdb8UL, 0x9eb80228UL, 0x0888055fUL, 0xb2d90cc6UL, 0x24e90bb1UL,
+    0x877c6f2fUL, 0x114c6858UL, 0xab1d61c1UL, 0x3d2d66b6UL, 0x9041dc76UL,
+    0x0671db01UL, 0xbc20d298UL, 0x2a10d5efUL, 0x8985b171UL, 0x1fb5b606UL,
+    0xa5e4bf9fUL, 0x33d4b8e8UL, 0xa2c90778UL, 0x34f9000fUL, 0x8ea80996UL,
+    0x18980ee1UL, 0xbb0d6a7fUL, 0x2d3d6d08UL, 0x976c6491UL, 0x015c63e6UL,
+    0xf4516b6bUL, 0x62616c1cUL, 0xd8306585UL, 0x4e0062f2UL, 0xed95066cUL,
+    0x7ba5011bUL, 0xc1f40882UL, 0x57c40ff5UL, 0xc6d9b065UL, 0x50e9b712UL,
+    0xeab8be8bUL, 0x7c88b9fcUL, 0xdf1ddd62UL, 0x492dda15UL, 0xf37cd38cUL,
+    0x654cd4fbUL, 0x5861b24dUL, 0xce51b53aUL, 0x7400bca3UL, 0xe230bbd4UL,
+    0x41a5df4aUL, 0xd795d83dUL, 0x6dc4d1a4UL, 0xfbf4d6d3UL, 0x6ae96943UL,
+    0xfcd96e34UL, 0x468867adUL, 0xd0b860daUL, 0x732d0444UL, 0xe51d0333UL,
+    0x5f4c0aaaUL, 0xc97c0dddUL, 0x3c710550UL, 0xaa410227UL, 0x10100bbeUL,
+    0x86200cc9UL, 0x25b56857UL, 0xb3856f20UL, 0x09d466b9UL, 0x9fe461ceUL,
+    0x0ef9de5eUL, 0x98c9d929UL, 0x2298d0b0UL, 0xb4a8d7c7UL, 0x173db359UL,
+    0x810db42eUL, 0x3b5cbdb7UL, 0xad6cbac0UL, 0x2083b8edUL, 0xb6b3bf9aUL,
+    0x0ce2b603UL, 0x9ad2b174UL, 0x3947d5eaUL, 0xaf77d29dUL, 0x1526db04UL,
+    0x8316dc73UL, 0x120b63e3UL, 0x843b6494UL, 0x3e6a6d0dUL, 0xa85a6a7aUL,
+    0x0bcf0ee4UL, 0x9dff0993UL, 0x27ae000aUL, 0xb19e077dUL, 0x44930ff0UL,
+    0xd2a30887UL, 0x68f2011eUL, 0xfec20669UL, 0x5d5762f7UL, 0xcb676580UL,
+    0x71366c19UL, 0xe7066b6eUL, 0x761bd4feUL, 0xe02bd389UL, 0x5a7ada10UL,
+    0xcc4add67UL, 0x6fdfb9f9UL, 0xf9efbe8eUL, 0x43beb717UL, 0xd58eb060UL,
+    0xe8a3d6d6UL, 0x7e93d1a1UL, 0xc4c2d838UL, 0x52f2df4fUL, 0xf167bbd1UL,
+    0x6757bca6UL, 0xdd06b53fUL, 0x4b36b248UL, 0xda2b0dd8UL, 0x4c1b0aafUL,
+    0xf64a0336UL, 0x607a0441UL, 0xc3ef60dfUL, 0x55df67a8UL, 0xef8e6e31UL,
+    0x79be6946UL, 0x8cb361cbUL, 0x1a8366bcUL, 0xa0d26f25UL, 0x36e26852UL,
+    0x95770cccUL, 0x03470bbbUL, 0xb9160222UL, 0x2f260555UL, 0xbe3bbac5UL,
+    0x280bbdb2UL, 0x925ab42bUL, 0x046ab35cUL, 0xa7ffd7c2UL, 0x31cfd0b5UL,
+    0x8b9ed92cUL, 0x1daede5bUL, 0xb0c2649bUL, 0x26f263ecUL, 0x9ca36a75UL,
+    0x0a936d02UL, 0xa906099cUL, 0x3f360eebUL, 0x85670772UL, 0x13570005UL,
+    0x824abf95UL, 0x147ab8e2UL, 0xae2bb17bUL, 0x381bb60cUL, 0x9b8ed292UL,
+    0x0dbed5e5UL, 0xb7efdc7cUL, 0x21dfdb0bUL, 0xd4d2d386UL, 0x42e2d4f1UL,
+    0xf8b3dd68UL, 0x6e83da1fUL, 0xcd16be81UL, 0x5b26b9f6UL, 0xe177b06fUL,
+    0x7747b718UL, 0xe65a0888UL, 0x706a0fffUL, 0xca3b0666UL, 0x5c0b0111UL,
+    0xff9e658fUL, 0x69ae62f8UL, 0xd3ff6b61UL, 0x45cf6c16UL, 0x78e20aa0UL,
+    0xeed20dd7UL, 0x5483044eUL, 0xc2b30339UL, 0x612667a7UL, 0xf71660d0UL,
+    0x4d476949UL, 0xdb776e3eUL, 0x4a6ad1aeUL, 0xdc5ad6d9UL, 0x660bdf40UL,
+    0xf03bd837UL, 0x53aebca9UL, 0xc59ebbdeUL, 0x7fcfb247UL, 0xe9ffb530UL,
+    0x1cf2bdbdUL, 0x8ac2bacaUL, 0x3093b353UL, 0xa6a3b424UL, 0x0536d0baUL,
+    0x9306d7cdUL, 0x2957de54UL, 0xbf67d923UL, 0x2e7a66b3UL, 0xb84a61c4UL,
+    0x021b685dUL, 0x942b6f2aUL, 0x37be0bb4UL, 0xa18e0cc3UL, 0x1bdf055aUL,
+    0x8def022dUL
+  },
+  {
+    0x00000000UL, 0x41311b19UL, 0x82623632UL, 0xc3532d2bUL, 0x04c56c64UL,
+    0x45f4777dUL, 0x86a75a56UL, 0xc796414fUL, 0x088ad9c8UL, 0x49bbc2d1UL,
+    0x8ae8effaUL, 0xcbd9f4e3UL, 0x0c4fb5acUL, 0x4d7eaeb5UL, 0x8e2d839eUL,
+    0xcf1c9887UL, 0x5112c24aUL, 0x1023d953UL, 0xd370f478UL, 0x9241ef61UL,
+    0x55d7ae2eUL, 0x14e6b537UL, 0xd7b5981cUL, 0x96848305UL, 0x59981b82UL,
+    0x18a9009bUL, 0xdbfa2db0UL, 0x9acb36a9UL, 0x5d5d77e6UL, 0x1c6c6cffUL,
+    0xdf3f41d4UL, 0x9e0e5acdUL, 0xa2248495UL, 0xe3159f8cUL, 0x2046b2a7UL,
+    0x6177a9beUL, 0xa6e1e8f1UL, 0xe7d0f3e8UL, 0x2483dec3UL, 0x65b2c5daUL,
+    0xaaae5d5dUL, 0xeb9f4644UL, 0x28cc6b6fUL, 0x69fd7076UL, 0xae6b3139UL,
+    0xef5a2a20UL, 0x2c09070bUL, 0x6d381c12UL, 0xf33646dfUL, 0xb2075dc6UL,
+    0x715470edUL, 0x30656bf4UL, 0xf7f32abbUL, 0xb6c231a2UL, 0x75911c89UL,
+    0x34a00790UL, 0xfbbc9f17UL, 0xba8d840eUL, 0x79dea925UL, 0x38efb23cUL,
+    0xff79f373UL, 0xbe48e86aUL, 0x7d1bc541UL, 0x3c2ade58UL, 0x054f79f0UL,
+    0x447e62e9UL, 0x872d4fc2UL, 0xc61c54dbUL, 0x018a1594UL, 0x40bb0e8dUL,
+    0x83e823a6UL, 0xc2d938bfUL, 0x0dc5a038UL, 0x4cf4bb21UL, 0x8fa7960aUL,
+    0xce968d13UL, 0x0900cc5cUL, 0x4831d745UL, 0x8b62fa6eUL, 0xca53e177UL,
+    0x545dbbbaUL, 0x156ca0a3UL, 0xd63f8d88UL, 0x970e9691UL, 0x5098d7deUL,
+    0x11a9ccc7UL, 0xd2fae1ecUL, 0x93cbfaf5UL, 0x5cd76272UL, 0x1de6796bUL,
+    0xdeb55440UL, 0x9f844f59UL, 0x58120e16UL, 0x1923150fUL, 0xda703824UL,
+    0x9b41233dUL, 0xa76bfd65UL, 0xe65ae67cUL, 0x2509cb57UL, 0x6438d04eUL,
+    0xa3ae9101UL, 0xe29f8a18UL, 0x21cca733UL, 0x60fdbc2aUL, 0xafe124adUL,
+    0xeed03fb4UL, 0x2d83129fUL, 0x6cb20986UL, 0xab2448c9UL, 0xea1553d0UL,
+    0x29467efbUL, 0x687765e2UL, 0xf6793f2fUL, 0xb7482436UL, 0x741b091dUL,
+    0x352a1204UL, 0xf2bc534bUL, 0xb38d4852UL, 0x70de6579UL, 0x31ef7e60UL,
+    0xfef3e6e7UL, 0xbfc2fdfeUL, 0x7c91d0d5UL, 0x3da0cbccUL, 0xfa368a83UL,
+    0xbb07919aUL, 0x7854bcb1UL, 0x3965a7a8UL, 0x4b98833bUL, 0x0aa99822UL,
+    0xc9fab509UL, 0x88cbae10UL, 0x4f5def5fUL, 0x0e6cf446UL, 0xcd3fd96dUL,
+    0x8c0ec274UL, 0x43125af3UL, 0x022341eaUL, 0xc1706cc1UL, 0x804177d8UL,
+    0x47d73697UL, 0x06e62d8eUL, 0xc5b500a5UL, 0x84841bbcUL, 0x1a8a4171UL,
+    0x5bbb5a68UL, 0x98e87743UL, 0xd9d96c5aUL, 0x1e4f2d15UL, 0x5f7e360cUL,
+    0x9c2d1b27UL, 0xdd1c003eUL, 0x120098b9UL, 0x533183a0UL, 0x9062ae8bUL,
+    0xd153b592UL, 0x16c5f4ddUL, 0x57f4efc4UL, 0x94a7c2efUL, 0xd596d9f6UL,
+    0xe9bc07aeUL, 0xa88d1cb7UL, 0x6bde319cUL, 0x2aef2a85UL, 0xed796bcaUL,
+    0xac4870d3UL, 0x6f1b5df8UL, 0x2e2a46e1UL, 0xe136de66UL, 0xa007c57fUL,
+    0x6354e854UL, 0x2265f34dUL, 0xe5f3b202UL, 0xa4c2a91bUL, 0x67918430UL,
+    0x26a09f29UL, 0xb8aec5e4UL, 0xf99fdefdUL, 0x3accf3d6UL, 0x7bfde8cfUL,
+    0xbc6ba980UL, 0xfd5ab299UL, 0x3e099fb2UL, 0x7f3884abUL, 0xb0241c2cUL,
+    0xf1150735UL, 0x32462a1eUL, 0x73773107UL, 0xb4e17048UL, 0xf5d06b51UL,
+    0x3683467aUL, 0x77b25d63UL, 0x4ed7facbUL, 0x0fe6e1d2UL, 0xccb5ccf9UL,
+    0x8d84d7e0UL, 0x4a1296afUL, 0x0b238db6UL, 0xc870a09dUL, 0x8941bb84UL,
+    0x465d2303UL, 0x076c381aUL, 0xc43f1531UL, 0x850e0e28UL, 0x42984f67UL,
+    0x03a9547eUL, 0xc0fa7955UL, 0x81cb624cUL, 0x1fc53881UL, 0x5ef42398UL,
+    0x9da70eb3UL, 0xdc9615aaUL, 0x1b0054e5UL, 0x5a314ffcUL, 0x996262d7UL,
+    0xd85379ceUL, 0x174fe149UL, 0x567efa50UL, 0x952dd77bUL, 0xd41ccc62UL,
+    0x138a8d2dUL, 0x52bb9634UL, 0x91e8bb1fUL, 0xd0d9a006UL, 0xecf37e5eUL,
+    0xadc26547UL, 0x6e91486cUL, 0x2fa05375UL, 0xe836123aUL, 0xa9070923UL,
+    0x6a542408UL, 0x2b653f11UL, 0xe479a796UL, 0xa548bc8fUL, 0x661b91a4UL,
+    0x272a8abdUL, 0xe0bccbf2UL, 0xa18dd0ebUL, 0x62defdc0UL, 0x23efe6d9UL,
+    0xbde1bc14UL, 0xfcd0a70dUL, 0x3f838a26UL, 0x7eb2913fUL, 0xb924d070UL,
+    0xf815cb69UL, 0x3b46e642UL, 0x7a77fd5bUL, 0xb56b65dcUL, 0xf45a7ec5UL,
+    0x370953eeUL, 0x763848f7UL, 0xb1ae09b8UL, 0xf09f12a1UL, 0x33cc3f8aUL,
+    0x72fd2493UL
+  },
+  {
+    0x00000000UL, 0x376ac201UL, 0x6ed48403UL, 0x59be4602UL, 0xdca80907UL,
+    0xebc2cb06UL, 0xb27c8d04UL, 0x85164f05UL, 0xb851130eUL, 0x8f3bd10fUL,
+    0xd685970dUL, 0xe1ef550cUL, 0x64f91a09UL, 0x5393d808UL, 0x0a2d9e0aUL,
+    0x3d475c0bUL, 0x70a3261cUL, 0x47c9e41dUL, 0x1e77a21fUL, 0x291d601eUL,
+    0xac0b2f1bUL, 0x9b61ed1aUL, 0xc2dfab18UL, 0xf5b56919UL, 0xc8f23512UL,
+    0xff98f713UL, 0xa626b111UL, 0x914c7310UL, 0x145a3c15UL, 0x2330fe14UL,
+    0x7a8eb816UL, 0x4de47a17UL, 0xe0464d38UL, 0xd72c8f39UL, 0x8e92c93bUL,
+    0xb9f80b3aUL, 0x3cee443fUL, 0x0b84863eUL, 0x523ac03cUL, 0x6550023dUL,
+    0x58175e36UL, 0x6f7d9c37UL, 0x36c3da35UL, 0x01a91834UL, 0x84bf5731UL,
+    0xb3d59530UL, 0xea6bd332UL, 0xdd011133UL, 0x90e56b24UL, 0xa78fa925UL,
+    0xfe31ef27UL, 0xc95b2d26UL, 0x4c4d6223UL, 0x7b27a022UL, 0x2299e620UL,
+    0x15f32421UL, 0x28b4782aUL, 0x1fdeba2bUL, 0x4660fc29UL, 0x710a3e28UL,
+    0xf41c712dUL, 0xc376b32cUL, 0x9ac8f52eUL, 0xada2372fUL, 0xc08d9a70UL,
+    0xf7e75871UL, 0xae591e73UL, 0x9933dc72UL, 0x1c259377UL, 0x2b4f5176UL,
+    0x72f11774UL, 0x459bd575UL, 0x78dc897eUL, 0x4fb64b7fUL, 0x16080d7dUL,
+    0x2162cf7cUL, 0xa4748079UL, 0x931e4278UL, 0xcaa0047aUL, 0xfdcac67bUL,
+    0xb02ebc6cUL, 0x87447e6dUL, 0xdefa386fUL, 0xe990fa6eUL, 0x6c86b56bUL,
+    0x5bec776aUL, 0x02523168UL, 0x3538f369UL, 0x087faf62UL, 0x3f156d63UL,
+    0x66ab2b61UL, 0x51c1e960UL, 0xd4d7a665UL, 0xe3bd6464UL, 0xba032266UL,
+    0x8d69e067UL, 0x20cbd748UL, 0x17a11549UL, 0x4e1f534bUL, 0x7975914aUL,
+    0xfc63de4fUL, 0xcb091c4eUL, 0x92b75a4cUL, 0xa5dd984dUL, 0x989ac446UL,
+    0xaff00647UL, 0xf64e4045UL, 0xc1248244UL, 0x4432cd41UL, 0x73580f40UL,
+    0x2ae64942UL, 0x1d8c8b43UL, 0x5068f154UL, 0x67023355UL, 0x3ebc7557UL,
+    0x09d6b756UL, 0x8cc0f853UL, 0xbbaa3a52UL, 0xe2147c50UL, 0xd57ebe51UL,
+    0xe839e25aUL, 0xdf53205bUL, 0x86ed6659UL, 0xb187a458UL, 0x3491eb5dUL,
+    0x03fb295cUL, 0x5a456f5eUL, 0x6d2fad5fUL, 0x801b35e1UL, 0xb771f7e0UL,
+    0xeecfb1e2UL, 0xd9a573e3UL, 0x5cb33ce6UL, 0x6bd9fee7UL, 0x3267b8e5UL,
+    0x050d7ae4UL, 0x384a26efUL, 0x0f20e4eeUL, 0x569ea2ecUL, 0x61f460edUL,
+    0xe4e22fe8UL, 0xd388ede9UL, 0x8a36abebUL, 0xbd5c69eaUL, 0xf0b813fdUL,
+    0xc7d2d1fcUL, 0x9e6c97feUL, 0xa90655ffUL, 0x2c101afaUL, 0x1b7ad8fbUL,
+    0x42c49ef9UL, 0x75ae5cf8UL, 0x48e900f3UL, 0x7f83c2f2UL, 0x263d84f0UL,
+    0x115746f1UL, 0x944109f4UL, 0xa32bcbf5UL, 0xfa958df7UL, 0xcdff4ff6UL,
+    0x605d78d9UL, 0x5737bad8UL, 0x0e89fcdaUL, 0x39e33edbUL, 0xbcf571deUL,
+    0x8b9fb3dfUL, 0xd221f5ddUL, 0xe54b37dcUL, 0xd80c6bd7UL, 0xef66a9d6UL,
+    0xb6d8efd4UL, 0x81b22dd5UL, 0x04a462d0UL, 0x33cea0d1UL, 0x6a70e6d3UL,
+    0x5d1a24d2UL, 0x10fe5ec5UL, 0x27949cc4UL, 0x7e2adac6UL, 0x494018c7UL,
+    0xcc5657c2UL, 0xfb3c95c3UL, 0xa282d3c1UL, 0x95e811c0UL, 0xa8af4dcbUL,
+    0x9fc58fcaUL, 0xc67bc9c8UL, 0xf1110bc9UL, 0x740744ccUL, 0x436d86cdUL,
+    0x1ad3c0cfUL, 0x2db902ceUL, 0x4096af91UL, 0x77fc6d90UL, 0x2e422b92UL,
+    0x1928e993UL, 0x9c3ea696UL, 0xab546497UL, 0xf2ea2295UL, 0xc580e094UL,
+    0xf8c7bc9fUL, 0xcfad7e9eUL, 0x9613389cUL, 0xa179fa9dUL, 0x246fb598UL,
+    0x13057799UL, 0x4abb319bUL, 0x7dd1f39aUL, 0x3035898dUL, 0x075f4b8cUL,
+    0x5ee10d8eUL, 0x698bcf8fUL, 0xec9d808aUL, 0xdbf7428bUL, 0x82490489UL,
+    0xb523c688UL, 0x88649a83UL, 0xbf0e5882UL, 0xe6b01e80UL, 0xd1dadc81UL,
+    0x54cc9384UL, 0x63a65185UL, 0x3a181787UL, 0x0d72d586UL, 0xa0d0e2a9UL,
+    0x97ba20a8UL, 0xce0466aaUL, 0xf96ea4abUL, 0x7c78ebaeUL, 0x4b1229afUL,
+    0x12ac6fadUL, 0x25c6adacUL, 0x1881f1a7UL, 0x2feb33a6UL, 0x765575a4UL,
+    0x413fb7a5UL, 0xc429f8a0UL, 0xf3433aa1UL, 0xaafd7ca3UL, 0x9d97bea2UL,
+    0xd073c4b5UL, 0xe71906b4UL, 0xbea740b6UL, 0x89cd82b7UL, 0x0cdbcdb2UL,
+    0x3bb10fb3UL, 0x620f49b1UL, 0x55658bb0UL, 0x6822d7bbUL, 0x5f4815baUL,
+    0x06f653b8UL, 0x319c91b9UL, 0xb48adebcUL, 0x83e01cbdUL, 0xda5e5abfUL,
+    0xed3498beUL
+  },
+  {
+    0x00000000UL, 0x6567bcb8UL, 0x8bc809aaUL, 0xeeafb512UL, 0x5797628fUL,
+    0x32f0de37UL, 0xdc5f6b25UL, 0xb938d79dUL, 0xef28b4c5UL, 0x8a4f087dUL,
+    0x64e0bd6fUL, 0x018701d7UL, 0xb8bfd64aUL, 0xddd86af2UL, 0x3377dfe0UL,
+    0x56106358UL, 0x9f571950UL, 0xfa30a5e8UL, 0x149f10faUL, 0x71f8ac42UL,
+    0xc8c07bdfUL, 0xada7c767UL, 0x43087275UL, 0x266fcecdUL, 0x707fad95UL,
+    0x1518112dUL, 0xfbb7a43fUL, 0x9ed01887UL, 0x27e8cf1aUL, 0x428f73a2UL,
+    0xac20c6b0UL, 0xc9477a08UL, 0x3eaf32a0UL, 0x5bc88e18UL, 0xb5673b0aUL,
+    0xd00087b2UL, 0x6938502fUL, 0x0c5fec97UL, 0xe2f05985UL, 0x8797e53dUL,
+    0xd1878665UL, 0xb4e03addUL, 0x5a4f8fcfUL, 0x3f283377UL, 0x8610e4eaUL,
+    0xe3775852UL, 0x0dd8ed40UL, 0x68bf51f8UL, 0xa1f82bf0UL, 0xc49f9748UL,
+    0x2a30225aUL, 0x4f579ee2UL, 0xf66f497fUL, 0x9308f5c7UL, 0x7da740d5UL,
+    0x18c0fc6dUL, 0x4ed09f35UL, 0x2bb7238dUL, 0xc518969fUL, 0xa07f2a27UL,
+    0x1947fdbaUL, 0x7c204102UL, 0x928ff410UL, 0xf7e848a8UL, 0x3d58149bUL,
+    0x583fa823UL, 0xb6901d31UL, 0xd3f7a189UL, 0x6acf7614UL, 0x0fa8caacUL,
+    0xe1077fbeUL, 0x8460c306UL, 0xd270a05eUL, 0xb7171ce6UL, 0x59b8a9f4UL,
+    0x3cdf154cUL, 0x85e7c2d1UL, 0xe0807e69UL, 0x0e2fcb7bUL, 0x6b4877c3UL,
+    0xa20f0dcbUL, 0xc768b173UL, 0x29c70461UL, 0x4ca0b8d9UL, 0xf5986f44UL,
+    0x90ffd3fcUL, 0x7e5066eeUL, 0x1b37da56UL, 0x4d27b90eUL, 0x284005b6UL,
+    0xc6efb0a4UL, 0xa3880c1cUL, 0x1ab0db81UL, 0x7fd76739UL, 0x9178d22bUL,
+    0xf41f6e93UL, 0x03f7263bUL, 0x66909a83UL, 0x883f2f91UL, 0xed589329UL,
+    0x546044b4UL, 0x3107f80cUL, 0xdfa84d1eUL, 0xbacff1a6UL, 0xecdf92feUL,
+    0x89b82e46UL, 0x67179b54UL, 0x027027ecUL, 0xbb48f071UL, 0xde2f4cc9UL,
+    0x3080f9dbUL, 0x55e74563UL, 0x9ca03f6bUL, 0xf9c783d3UL, 0x176836c1UL,
+    0x720f8a79UL, 0xcb375de4UL, 0xae50e15cUL, 0x40ff544eUL, 0x2598e8f6UL,
+    0x73888baeUL, 0x16ef3716UL, 0xf8408204UL, 0x9d273ebcUL, 0x241fe921UL,
+    0x41785599UL, 0xafd7e08bUL, 0xcab05c33UL, 0x3bb659edUL, 0x5ed1e555UL,
+    0xb07e5047UL, 0xd519ecffUL, 0x6c213b62UL, 0x094687daUL, 0xe7e932c8UL,
+    0x828e8e70UL, 0xd49eed28UL, 0xb1f95190UL, 0x5f56e482UL, 0x3a31583aUL,
+    0x83098fa7UL, 0xe66e331fUL, 0x08c1860dUL, 0x6da63ab5UL, 0xa4e140bdUL,
+    0xc186fc05UL, 0x2f294917UL, 0x4a4ef5afUL, 0xf3762232UL, 0x96119e8aUL,
+    0x78be2b98UL, 0x1dd99720UL, 0x4bc9f478UL, 0x2eae48c0UL, 0xc001fdd2UL,
+    0xa566416aUL, 0x1c5e96f7UL, 0x79392a4fUL, 0x97969f5dUL, 0xf2f123e5UL,
+    0x05196b4dUL, 0x607ed7f5UL, 0x8ed162e7UL, 0xebb6de5fUL, 0x528e09c2UL,
+    0x37e9b57aUL, 0xd9460068UL, 0xbc21bcd0UL, 0xea31df88UL, 0x8f566330UL,
+    0x61f9d622UL, 0x049e6a9aUL, 0xbda6bd07UL, 0xd8c101bfUL, 0x366eb4adUL,
+    0x53090815UL, 0x9a4e721dUL, 0xff29cea5UL, 0x11867bb7UL, 0x74e1c70fUL,
+    0xcdd91092UL, 0xa8beac2aUL, 0x46111938UL, 0x2376a580UL, 0x7566c6d8UL,
+    0x10017a60UL, 0xfeaecf72UL, 0x9bc973caUL, 0x22f1a457UL, 0x479618efUL,
+    0xa939adfdUL, 0xcc5e1145UL, 0x06ee4d76UL, 0x6389f1ceUL, 0x8d2644dcUL,
+    0xe841f864UL, 0x51792ff9UL, 0x341e9341UL, 0xdab12653UL, 0xbfd69aebUL,
+    0xe9c6f9b3UL, 0x8ca1450bUL, 0x620ef019UL, 0x07694ca1UL, 0xbe519b3cUL,
+    0xdb362784UL, 0x35999296UL, 0x50fe2e2eUL, 0x99b95426UL, 0xfcdee89eUL,
+    0x12715d8cUL, 0x7716e134UL, 0xce2e36a9UL, 0xab498a11UL, 0x45e63f03UL,
+    0x208183bbUL, 0x7691e0e3UL, 0x13f65c5bUL, 0xfd59e949UL, 0x983e55f1UL,
+    0x2106826cUL, 0x44613ed4UL, 0xaace8bc6UL, 0xcfa9377eUL, 0x38417fd6UL,
+    0x5d26c36eUL, 0xb389767cUL, 0xd6eecac4UL, 0x6fd61d59UL, 0x0ab1a1e1UL,
+    0xe41e14f3UL, 0x8179a84bUL, 0xd769cb13UL, 0xb20e77abUL, 0x5ca1c2b9UL,
+    0x39c67e01UL, 0x80fea99cUL, 0xe5991524UL, 0x0b36a036UL, 0x6e511c8eUL,
+    0xa7166686UL, 0xc271da3eUL, 0x2cde6f2cUL, 0x49b9d394UL, 0xf0810409UL,
+    0x95e6b8b1UL, 0x7b490da3UL, 0x1e2eb11bUL, 0x483ed243UL, 0x2d596efbUL,
+    0xc3f6dbe9UL, 0xa6916751UL, 0x1fa9b0ccUL, 0x7ace0c74UL, 0x9461b966UL,
+    0xf10605deUL
+#endif
+  }
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/deflate.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,2187 @@
+/*
+ * 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.
+ */
+
+/* deflate.c -- compress data using the deflation algorithm
+ * Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+ *  ALGORITHM
+ *
+ *      The "deflation" process depends on being able to identify portions
+ *      of the input text which are identical to earlier input (within a
+ *      sliding window trailing behind the input currently being processed).
+ *
+ *      The most straightforward technique turns out to be the fastest for
+ *      most input files: try all possible matches and select the longest.
+ *      The key feature of this algorithm is that insertions into the string
+ *      dictionary are very simple and thus fast, and deletions are avoided
+ *      completely. Insertions are performed at each input character, whereas
+ *      string matches are performed only when the previous match ends. So it
+ *      is preferable to spend more time in matches to allow very fast string
+ *      insertions and avoid deletions. The matching algorithm for small
+ *      strings is inspired from that of Rabin & Karp. A brute force approach
+ *      is used to find longer strings when a small match has been found.
+ *      A similar algorithm is used in comic (by Jan-Mark Wams) and freeze
+ *      (by Leonid Broukhis).
+ *         A previous version of this file used a more sophisticated algorithm
+ *      (by Fiala and Greene) which is guaranteed to run in linear amortized
+ *      time, but has a larger average cost, uses more memory and is patented.
+ *      However the F&G algorithm may be faster for some highly redundant
+ *      files if the parameter max_chain_length (described below) is too large.
+ *
+ *  ACKNOWLEDGEMENTS
+ *
+ *      The idea of lazy evaluation of matches is due to Jan-Mark Wams, and
+ *      I found it in 'freeze' written by Leonid Broukhis.
+ *      Thanks to many people for bug reports and testing.
+ *
+ *  REFERENCES
+ *
+ *      Deutsch, L.P.,"DEFLATE Compressed Data Format Specification".
+ *      Available in http://tools.ietf.org/html/rfc1951
+ *
+ *      A description of the Rabin and Karp algorithm is given in the book
+ *         "Algorithms" by R. Sedgewick, Addison-Wesley, p252.
+ *
+ *      Fiala,E.R., and Greene,D.H.
+ *         Data Compression with Finite Windows, Comm.ACM, 32,4 (1989) 490-595
+ *
+ */
+
+/* @(#) $Id$ */
+
+#include "deflate.h"
+
+const char deflate_copyright[] =
+   " deflate 1.2.11 Copyright 1995-2017 Jean-loup Gailly and Mark Adler ";
+/*
+  If you use the zlib library in a product, an acknowledgment is welcome
+  in the documentation of your product. If for some reason you cannot
+  include such an acknowledgment, I would appreciate that you keep this
+  copyright string in the executable of your product.
+ */
+
+/* ===========================================================================
+ *  Function prototypes.
+ */
+typedef enum {
+    need_more,      /* block not completed, need more input or more output */
+    block_done,     /* block flush performed */
+    finish_started, /* finish started, need only more output at next deflate */
+    finish_done     /* finish done, accept no more input or output */
+} block_state;
+
+typedef block_state (*compress_func) OF((deflate_state *s, int flush));
+/* Compression function. Returns the block state after the call. */
+
+local int deflateStateCheck      OF((z_streamp strm));
+local void slide_hash     OF((deflate_state *s));
+local void fill_window    OF((deflate_state *s));
+local block_state deflate_stored OF((deflate_state *s, int flush));
+local block_state deflate_fast   OF((deflate_state *s, int flush));
+#ifndef FASTEST
+local block_state deflate_slow   OF((deflate_state *s, int flush));
+#endif
+local block_state deflate_rle    OF((deflate_state *s, int flush));
+local block_state deflate_huff   OF((deflate_state *s, int flush));
+local void lm_init        OF((deflate_state *s));
+local void putShortMSB    OF((deflate_state *s, uInt b));
+local void flush_pending  OF((z_streamp strm));
+local unsigned read_buf   OF((z_streamp strm, Bytef *buf, unsigned size));
+#ifdef ASMV
+#  pragma message("Assembler code may have bugs -- use at your own risk")
+      void match_init OF((void)); /* asm code initialization */
+      uInt longest_match  OF((deflate_state *s, IPos cur_match));
+#else
+local uInt longest_match  OF((deflate_state *s, IPos cur_match));
+#endif
+
+#ifdef ZLIB_DEBUG
+local  void check_match OF((deflate_state *s, IPos start, IPos match,
+                            int length));
+#endif
+
+/* ===========================================================================
+ * Local data
+ */
+
+#define NIL 0
+/* Tail of hash chains */
+
+#ifndef TOO_FAR
+#  define TOO_FAR 4096
+#endif
+/* Matches of length 3 are discarded if their distance exceeds TOO_FAR */
+
+/* Values for max_lazy_match, good_match and max_chain_length, depending on
+ * the desired pack level (0..9). The values given below have been tuned to
+ * exclude worst case performance for pathological files. Better values may be
+ * found for specific files.
+ */
+typedef struct config_s {
+   ush good_length; /* reduce lazy search above this match length */
+   ush max_lazy;    /* do not perform lazy search above this match length */
+   ush nice_length; /* quit search above this match length */
+   ush max_chain;
+   compress_func func;
+} config;
+
+#ifdef FASTEST
+local const config configuration_table[2] = {
+/*      good lazy nice chain */
+/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
+/* 1 */ {4,    4,  8,    4, deflate_fast}}; /* max speed, no lazy matches */
+#else
+local const config configuration_table[10] = {
+/*      good lazy nice chain */
+/* 0 */ {0,    0,  0,    0, deflate_stored},  /* store only */
+/* 1 */ {4,    4,  8,    4, deflate_fast}, /* max speed, no lazy matches */
+/* 2 */ {4,    5, 16,    8, deflate_fast},
+/* 3 */ {4,    6, 32,   32, deflate_fast},
+
+/* 4 */ {4,    4, 16,   16, deflate_slow},  /* lazy matches */
+/* 5 */ {8,   16, 32,   32, deflate_slow},
+/* 6 */ {8,   16, 128, 128, deflate_slow},
+/* 7 */ {8,   32, 128, 256, deflate_slow},
+/* 8 */ {32, 128, 258, 1024, deflate_slow},
+/* 9 */ {32, 258, 258, 4096, deflate_slow}}; /* max compression */
+#endif
+
+/* Note: the deflate() code requires max_lazy >= MIN_MATCH and max_chain >= 4
+ * For deflate_fast() (levels <= 3) good is ignored and lazy has a different
+ * meaning.
+ */
+
+/* rank Z_BLOCK between Z_NO_FLUSH and Z_PARTIAL_FLUSH */
+#define RANK(f) (((f) * 2) - ((f) > 4 ? 9 : 0))
+
+/* ===========================================================================
+ * Update a hash value with the given input byte
+ * IN  assertion: all calls to UPDATE_HASH are made with consecutive input
+ *    characters, so that a running hash key can be computed from the previous
+ *    key instead of complete recalculation each time.
+ */
+#define UPDATE_HASH(s,h,c) (h = (((h)<<s->hash_shift) ^ (c)) & s->hash_mask)
+
+
+/* ===========================================================================
+ * Insert string str in the dictionary and set match_head to the previous head
+ * of the hash chain (the most recent string with same hash key). Return
+ * the previous length of the hash chain.
+ * If this file is compiled with -DFASTEST, the compression level is forced
+ * to 1, and no hash chains are maintained.
+ * IN  assertion: all calls to INSERT_STRING are made with consecutive input
+ *    characters and the first MIN_MATCH bytes of str are valid (except for
+ *    the last MIN_MATCH-1 bytes of the input file).
+ */
+#ifdef FASTEST
+#define INSERT_STRING(s, str, match_head) \
+   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
+    match_head = s->head[s->ins_h], \
+    s->head[s->ins_h] = (Pos)(str))
+#else
+#define INSERT_STRING(s, str, match_head) \
+   (UPDATE_HASH(s, s->ins_h, s->window[(str) + (MIN_MATCH-1)]), \
+    match_head = s->prev[(str) & s->w_mask] = s->head[s->ins_h], \
+    s->head[s->ins_h] = (Pos)(str))
+#endif
+
+/* ===========================================================================
+ * Initialize the hash table (avoiding 64K overflow for 16 bit systems).
+ * prev[] will be initialized on the fly.
+ */
+#define CLEAR_HASH(s) \
+    s->head[s->hash_size-1] = NIL; \
+    zmemzero((Bytef *)s->head, (unsigned)(s->hash_size-1)*sizeof(*s->head));
+
+/* ===========================================================================
+ * Slide the hash table when sliding the window down (could be avoided with 32
+ * bit values at the expense of memory usage). We slide even when level == 0 to
+ * keep the hash table consistent if we switch back to level > 0 later.
+ */
+local void slide_hash(s)
+    deflate_state *s;
+{
+    unsigned n, m;
+    Posf *p;
+    uInt wsize = s->w_size;
+
+    n = s->hash_size;
+    p = &s->head[n];
+    do {
+        m = *--p;
+        *p = (Pos)(m >= wsize ? m - wsize : NIL);
+    } while (--n);
+    n = wsize;
+#ifndef FASTEST
+    p = &s->prev[n];
+    do {
+        m = *--p;
+        *p = (Pos)(m >= wsize ? m - wsize : NIL);
+        /* If n is not on any hash chain, prev[n] is garbage but
+         * its value will never be used.
+         */
+    } while (--n);
+#endif
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateInit_(strm, level, version, stream_size)
+    z_streamp strm;
+    int level;
+    const char *version;
+    int stream_size;
+{
+    return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
+                         Z_DEFAULT_STRATEGY, version, stream_size);
+    /* To do: ignore strm->next_in if we use it as window */
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
+                  version, stream_size)
+    z_streamp strm;
+    int  level;
+    int  method;
+    int  windowBits;
+    int  memLevel;
+    int  strategy;
+    const char *version;
+    int stream_size;
+{
+    deflate_state *s;
+    int wrap = 1;
+    static const char my_version[] = ZLIB_VERSION;
+
+    ushf *overlay;
+    /* We overlay pending_buf and d_buf+l_buf. This works since the average
+     * output size for (length,distance) codes is <= 24 bits.
+     */
+
+    if (version == Z_NULL || version[0] != my_version[0] ||
+        stream_size != sizeof(z_stream)) {
+        return Z_VERSION_ERROR;
+    }
+    if (strm == Z_NULL) return Z_STREAM_ERROR;
+
+    strm->msg = Z_NULL;
+    if (strm->zalloc == (alloc_func)0) {
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+        strm->zalloc = zcalloc;
+        strm->opaque = (voidpf)0;
+#endif
+    }
+    if (strm->zfree == (free_func)0)
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+        strm->zfree = zcfree;
+#endif
+
+#ifdef FASTEST
+    if (level != 0) level = 1;
+#else
+    if (level == Z_DEFAULT_COMPRESSION) level = 6;
+#endif
+
+    if (windowBits < 0) { /* suppress zlib wrapper */
+        wrap = 0;
+        windowBits = -windowBits;
+    }
+#ifdef GZIP
+    else if (windowBits > 15) {
+        wrap = 2;       /* write gzip wrapper instead */
+        windowBits -= 16;
+    }
+#endif
+    if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
+        windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
+        strategy < 0 || strategy > Z_FIXED || (windowBits == 8 && wrap != 1)) {
+        return Z_STREAM_ERROR;
+    }
+    if (windowBits == 8) windowBits = 9;  /* until 256-byte window bug fixed */
+    s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
+    if (s == Z_NULL) return Z_MEM_ERROR;
+    strm->state = (struct internal_state FAR *)s;
+    s->strm = strm;
+    s->status = INIT_STATE;     /* to pass state test in deflateReset() */
+
+    s->wrap = wrap;
+    s->gzhead = Z_NULL;
+    s->w_bits = (uInt)windowBits;
+    s->w_size = 1 << s->w_bits;
+    s->w_mask = s->w_size - 1;
+
+    s->hash_bits = (uInt)memLevel + 7;
+    s->hash_size = 1 << s->hash_bits;
+    s->hash_mask = s->hash_size - 1;
+    s->hash_shift =  ((s->hash_bits+MIN_MATCH-1)/MIN_MATCH);
+
+    s->window = (Bytef *) ZALLOC(strm, s->w_size, 2*sizeof(Byte));
+    s->prev   = (Posf *)  ZALLOC(strm, s->w_size, sizeof(Pos));
+    s->head   = (Posf *)  ZALLOC(strm, s->hash_size, sizeof(Pos));
+
+    s->high_water = 0;      /* nothing written to s->window yet */
+
+    s->lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
+
+    overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2);
+    s->pending_buf = (uchf *) overlay;
+    s->pending_buf_size = (ulg)s->lit_bufsize * (sizeof(ush)+2L);
+
+    if (s->window == Z_NULL || s->prev == Z_NULL || s->head == Z_NULL ||
+        s->pending_buf == Z_NULL) {
+        s->status = FINISH_STATE;
+        strm->msg = ERR_MSG(Z_MEM_ERROR);
+        deflateEnd (strm);
+        return Z_MEM_ERROR;
+    }
+    s->d_buf = overlay + s->lit_bufsize/sizeof(ush);
+    s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize;
+
+    s->level = level;
+    s->strategy = strategy;
+    s->method = (Byte)method;
+
+    return deflateReset(strm);
+}
+
+/* =========================================================================
+ * Check for a valid deflate stream state. Return 0 if ok, 1 if not.
+ */
+local int deflateStateCheck (strm)
+    z_streamp strm;
+{
+    deflate_state *s;
+    if (strm == Z_NULL ||
+        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
+        return 1;
+    s = strm->state;
+    if (s == Z_NULL || s->strm != strm || (s->status != INIT_STATE &&
+#ifdef GZIP
+                                           s->status != GZIP_STATE &&
+#endif
+                                           s->status != EXTRA_STATE &&
+                                           s->status != NAME_STATE &&
+                                           s->status != COMMENT_STATE &&
+                                           s->status != HCRC_STATE &&
+                                           s->status != BUSY_STATE &&
+                                           s->status != FINISH_STATE))
+        return 1;
+    return 0;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
+    z_streamp strm;
+    const Bytef *dictionary;
+    uInt  dictLength;
+{
+    deflate_state *s;
+    uInt str, n;
+    int wrap;
+    unsigned avail;
+    z_const unsigned char *next;
+
+    if (deflateStateCheck(strm) || dictionary == Z_NULL)
+        return Z_STREAM_ERROR;
+    s = strm->state;
+    wrap = s->wrap;
+    if (wrap == 2 || (wrap == 1 && s->status != INIT_STATE) || s->lookahead)
+        return Z_STREAM_ERROR;
+
+    /* when using zlib wrappers, compute Adler-32 for provided dictionary */
+    if (wrap == 1)
+        strm->adler = adler32(strm->adler, dictionary, dictLength);
+    s->wrap = 0;                    /* avoid computing Adler-32 in read_buf */
+
+    /* if dictionary would fill window, just replace the history */
+    if (dictLength >= s->w_size) {
+        if (wrap == 0) {            /* already empty otherwise */
+            CLEAR_HASH(s);
+            s->strstart = 0;
+            s->block_start = 0L;
+            s->insert = 0;
+        }
+        dictionary += dictLength - s->w_size;  /* use the tail */
+        dictLength = s->w_size;
+    }
+
+    /* insert dictionary into window and hash */
+    avail = strm->avail_in;
+    next = strm->next_in;
+    strm->avail_in = dictLength;
+    strm->next_in = (z_const Bytef *)dictionary;
+    fill_window(s);
+    while (s->lookahead >= MIN_MATCH) {
+        str = s->strstart;
+        n = s->lookahead - (MIN_MATCH-1);
+        do {
+            UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
+#ifndef FASTEST
+            s->prev[str & s->w_mask] = s->head[s->ins_h];
+#endif
+            s->head[s->ins_h] = (Pos)str;
+            str++;
+        } while (--n);
+        s->strstart = str;
+        s->lookahead = MIN_MATCH-1;
+        fill_window(s);
+    }
+    s->strstart += s->lookahead;
+    s->block_start = (long)s->strstart;
+    s->insert = s->lookahead;
+    s->lookahead = 0;
+    s->match_length = s->prev_length = MIN_MATCH-1;
+    s->match_available = 0;
+    strm->next_in = next;
+    strm->avail_in = avail;
+    s->wrap = wrap;
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateGetDictionary (strm, dictionary, dictLength)
+    z_streamp strm;
+    Bytef *dictionary;
+    uInt  *dictLength;
+{
+    deflate_state *s;
+    uInt len;
+
+    if (deflateStateCheck(strm))
+        return Z_STREAM_ERROR;
+    s = strm->state;
+    len = s->strstart + s->lookahead;
+    if (len > s->w_size)
+        len = s->w_size;
+    if (dictionary != Z_NULL && len)
+        zmemcpy(dictionary, s->window + s->strstart + s->lookahead - len, len);
+    if (dictLength != Z_NULL)
+        *dictLength = len;
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateResetKeep (strm)
+    z_streamp strm;
+{
+    deflate_state *s;
+
+    if (deflateStateCheck(strm)) {
+        return Z_STREAM_ERROR;
+    }
+
+    strm->total_in = strm->total_out = 0;
+    strm->msg = Z_NULL; /* use zfree if we ever allocate msg dynamically */
+    strm->data_type = Z_UNKNOWN;
+
+    s = (deflate_state *)strm->state;
+    s->pending = 0;
+    s->pending_out = s->pending_buf;
+
+    if (s->wrap < 0) {
+        s->wrap = -s->wrap; /* was made negative by deflate(..., Z_FINISH); */
+    }
+    s->status =
+#ifdef GZIP
+        s->wrap == 2 ? GZIP_STATE :
+#endif
+        s->wrap ? INIT_STATE : BUSY_STATE;
+    strm->adler =
+#ifdef GZIP
+        s->wrap == 2 ? crc32(0L, Z_NULL, 0) :
+#endif
+        adler32(0L, Z_NULL, 0);
+    s->last_flush = Z_NO_FLUSH;
+
+    _tr_init(s);
+
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateReset (strm)
+    z_streamp strm;
+{
+    int ret;
+
+    ret = deflateResetKeep(strm);
+    if (ret == Z_OK)
+        lm_init(strm->state);
+    return ret;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateSetHeader (strm, head)
+    z_streamp strm;
+    gz_headerp head;
+{
+    if (deflateStateCheck(strm) || strm->state->wrap != 2)
+        return Z_STREAM_ERROR;
+    strm->state->gzhead = head;
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflatePending (strm, pending, bits)
+    unsigned *pending;
+    int *bits;
+    z_streamp strm;
+{
+    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
+    if (pending != Z_NULL)
+        *pending = strm->state->pending;
+    if (bits != Z_NULL)
+        *bits = strm->state->bi_valid;
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflatePrime (strm, bits, value)
+    z_streamp strm;
+    int bits;
+    int value;
+{
+    deflate_state *s;
+    int put;
+
+    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
+    s = strm->state;
+    if ((Bytef *)(s->d_buf) < s->pending_out + ((Buf_size + 7) >> 3))
+        return Z_BUF_ERROR;
+    do {
+        put = Buf_size - s->bi_valid;
+        if (put > bits)
+            put = bits;
+        s->bi_buf |= (ush)((value & ((1 << put) - 1)) << s->bi_valid);
+        s->bi_valid += put;
+        _tr_flush_bits(s);
+        value >>= put;
+        bits -= put;
+    } while (bits);
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateParams(strm, level, strategy)
+    z_streamp strm;
+    int level;
+    int strategy;
+{
+    deflate_state *s;
+    compress_func func;
+
+    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
+    s = strm->state;
+
+#ifdef FASTEST
+    if (level != 0) level = 1;
+#else
+    if (level == Z_DEFAULT_COMPRESSION) level = 6;
+#endif
+    if (level < 0 || level > 9 || strategy < 0 || strategy > Z_FIXED) {
+        return Z_STREAM_ERROR;
+    }
+    func = configuration_table[s->level].func;
+
+    if ((strategy != s->strategy || func != configuration_table[level].func) &&
+        s->high_water) {
+        /* Flush the last buffer: */
+        int err = deflate(strm, Z_BLOCK);
+        if (err == Z_STREAM_ERROR)
+            return err;
+        if (strm->avail_out == 0)
+            return Z_BUF_ERROR;
+    }
+    if (s->level != level) {
+        if (s->level == 0 && s->matches != 0) {
+            if (s->matches == 1)
+                slide_hash(s);
+            else
+                CLEAR_HASH(s);
+            s->matches = 0;
+        }
+        s->level = level;
+        s->max_lazy_match   = configuration_table[level].max_lazy;
+        s->good_match       = configuration_table[level].good_length;
+        s->nice_match       = configuration_table[level].nice_length;
+        s->max_chain_length = configuration_table[level].max_chain;
+    }
+    s->strategy = strategy;
+    return Z_OK;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateTune(strm, good_length, max_lazy, nice_length, max_chain)
+    z_streamp strm;
+    int good_length;
+    int max_lazy;
+    int nice_length;
+    int max_chain;
+{
+    deflate_state *s;
+
+    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
+    s = strm->state;
+    s->good_match = (uInt)good_length;
+    s->max_lazy_match = (uInt)max_lazy;
+    s->nice_match = nice_length;
+    s->max_chain_length = (uInt)max_chain;
+    return Z_OK;
+}
+
+/* =========================================================================
+ * For the default windowBits of 15 and memLevel of 8, this function returns
+ * a close to exact, as well as small, upper bound on the compressed size.
+ * They are coded as constants here for a reason--if the #define's are
+ * changed, then this function needs to be changed as well.  The return
+ * value for 15 and 8 only works for those exact settings.
+ *
+ * For any setting other than those defaults for windowBits and memLevel,
+ * the value returned is a conservative worst case for the maximum expansion
+ * resulting from using fixed blocks instead of stored blocks, which deflate
+ * can emit on compressed data for some combinations of the parameters.
+ *
+ * This function could be more sophisticated to provide closer upper bounds for
+ * every combination of windowBits and memLevel.  But even the conservative
+ * upper bound of about 14% expansion does not seem onerous for output buffer
+ * allocation.
+ */
+uLong ZEXPORT deflateBound(strm, sourceLen)
+    z_streamp strm;
+    uLong sourceLen;
+{
+    deflate_state *s;
+    uLong complen, wraplen;
+
+    /* conservative upper bound for compressed data */
+    complen = sourceLen +
+              ((sourceLen + 7) >> 3) + ((sourceLen + 63) >> 6) + 5;
+
+    /* if can't get parameters, return conservative bound plus zlib wrapper */
+    if (deflateStateCheck(strm))
+        return complen + 6;
+
+    /* compute wrapper length */
+    s = strm->state;
+    switch (s->wrap) {
+    case 0:                                 /* raw deflate */
+        wraplen = 0;
+        break;
+    case 1:                                 /* zlib wrapper */
+        wraplen = 6 + (s->strstart ? 4 : 0);
+        break;
+#ifdef GZIP
+    case 2:                                 /* gzip wrapper */
+        wraplen = 18;
+        if (s->gzhead != Z_NULL) {          /* user-supplied gzip header */
+            Bytef *str;
+            if (s->gzhead->extra != Z_NULL)
+                wraplen += 2 + s->gzhead->extra_len;
+            str = s->gzhead->name;
+            if (str != Z_NULL)
+                do {
+                    wraplen++;
+                } while (*str++);
+            str = s->gzhead->comment;
+            if (str != Z_NULL)
+                do {
+                    wraplen++;
+                } while (*str++);
+            if (s->gzhead->hcrc)
+                wraplen += 2;
+        }
+        break;
+#endif
+    default:                                /* for compiler happiness */
+        wraplen = 6;
+    }
+
+    /* if not default parameters, return conservative bound */
+    if (s->w_bits != 15 || s->hash_bits != 8 + 7)
+        return complen + wraplen;
+
+    /* default settings: return tight bound for that case */
+    return sourceLen + (sourceLen >> 12) + (sourceLen >> 14) +
+           (sourceLen >> 25) + 13 - 6 + wraplen;
+}
+
+/* =========================================================================
+ * Put a short in the pending buffer. The 16-bit value is put in MSB order.
+ * IN assertion: the stream state is correct and there is enough room in
+ * pending_buf.
+ */
+local void putShortMSB (s, b)
+    deflate_state *s;
+    uInt b;
+{
+    put_byte(s, (Byte)(b >> 8));
+    put_byte(s, (Byte)(b & 0xff));
+}
+
+/* =========================================================================
+ * Flush as much pending output as possible. All deflate() output, except for
+ * some deflate_stored() output, goes through this function so some
+ * applications may wish to modify it to avoid allocating a large
+ * strm->next_out buffer and copying into it. (See also read_buf()).
+ */
+local void flush_pending(strm)
+    z_streamp strm;
+{
+    unsigned len;
+    deflate_state *s = strm->state;
+
+    _tr_flush_bits(s);
+    len = s->pending;
+    if (len > strm->avail_out) len = strm->avail_out;
+    if (len == 0) return;
+
+    zmemcpy(strm->next_out, s->pending_out, len);
+    strm->next_out  += len;
+    s->pending_out  += len;
+    strm->total_out += len;
+    strm->avail_out -= len;
+    s->pending      -= len;
+    if (s->pending == 0) {
+        s->pending_out = s->pending_buf;
+    }
+}
+
+/* ===========================================================================
+ * Update the header CRC with the bytes s->pending_buf[beg..s->pending - 1].
+ */
+#define HCRC_UPDATE(beg) \
+    do { \
+        if (s->gzhead->hcrc && s->pending > (beg)) \
+            strm->adler = crc32(strm->adler, s->pending_buf + (beg), \
+                                s->pending - (beg)); \
+    } while (0)
+
+/* ========================================================================= */
+int ZEXPORT deflate (strm, flush)
+    z_streamp strm;
+    int flush;
+{
+    int old_flush; /* value of flush param for previous deflate call */
+    deflate_state *s;
+
+    if (deflateStateCheck(strm) || flush > Z_BLOCK || flush < 0) {
+        return Z_STREAM_ERROR;
+    }
+    s = strm->state;
+
+    if (strm->next_out == Z_NULL ||
+        (strm->avail_in != 0 && strm->next_in == Z_NULL) ||
+        (s->status == FINISH_STATE && flush != Z_FINISH)) {
+        ERR_RETURN(strm, Z_STREAM_ERROR);
+    }
+    if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
+
+    old_flush = s->last_flush;
+    s->last_flush = flush;
+
+    /* Flush as much pending output as possible */
+    if (s->pending != 0) {
+        flush_pending(strm);
+        if (strm->avail_out == 0) {
+            /* Since avail_out is 0, deflate will be called again with
+             * more output space, but possibly with both pending and
+             * avail_in equal to zero. There won't be anything to do,
+             * but this is not an error situation so make sure we
+             * return OK instead of BUF_ERROR at next call of deflate:
+             */
+            s->last_flush = -1;
+            return Z_OK;
+        }
+
+    /* Make sure there is something to do and avoid duplicate consecutive
+     * flushes. For repeated and useless calls with Z_FINISH, we keep
+     * returning Z_STREAM_END instead of Z_BUF_ERROR.
+     */
+    } else if (strm->avail_in == 0 && RANK(flush) <= RANK(old_flush) &&
+               flush != Z_FINISH) {
+        ERR_RETURN(strm, Z_BUF_ERROR);
+    }
+
+    /* User must not provide more input after the first FINISH: */
+    if (s->status == FINISH_STATE && strm->avail_in != 0) {
+        ERR_RETURN(strm, Z_BUF_ERROR);
+    }
+
+    /* Write the header */
+    if (s->status == INIT_STATE) {
+        /* zlib header */
+        uInt header = (Z_DEFLATED + ((s->w_bits-8)<<4)) << 8;
+        uInt level_flags;
+
+        if (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2)
+            level_flags = 0;
+        else if (s->level < 6)
+            level_flags = 1;
+        else if (s->level == 6)
+            level_flags = 2;
+        else
+            level_flags = 3;
+        header |= (level_flags << 6);
+        if (s->strstart != 0) header |= PRESET_DICT;
+        header += 31 - (header % 31);
+
+        putShortMSB(s, header);
+
+        /* Save the adler32 of the preset dictionary: */
+        if (s->strstart != 0) {
+            putShortMSB(s, (uInt)(strm->adler >> 16));
+            putShortMSB(s, (uInt)(strm->adler & 0xffff));
+        }
+        strm->adler = adler32(0L, Z_NULL, 0);
+        s->status = BUSY_STATE;
+
+        /* Compression must start with an empty pending buffer */
+        flush_pending(strm);
+        if (s->pending != 0) {
+            s->last_flush = -1;
+            return Z_OK;
+        }
+    }
+#ifdef GZIP
+    if (s->status == GZIP_STATE) {
+        /* gzip header */
+        strm->adler = crc32(0L, Z_NULL, 0);
+        put_byte(s, 31);
+        put_byte(s, 139);
+        put_byte(s, 8);
+        if (s->gzhead == Z_NULL) {
+            put_byte(s, 0);
+            put_byte(s, 0);
+            put_byte(s, 0);
+            put_byte(s, 0);
+            put_byte(s, 0);
+            put_byte(s, s->level == 9 ? 2 :
+                     (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
+                      4 : 0));
+            put_byte(s, OS_CODE);
+            s->status = BUSY_STATE;
+
+            /* Compression must start with an empty pending buffer */
+            flush_pending(strm);
+            if (s->pending != 0) {
+                s->last_flush = -1;
+                return Z_OK;
+            }
+        }
+        else {
+            put_byte(s, (s->gzhead->text ? 1 : 0) +
+                     (s->gzhead->hcrc ? 2 : 0) +
+                     (s->gzhead->extra == Z_NULL ? 0 : 4) +
+                     (s->gzhead->name == Z_NULL ? 0 : 8) +
+                     (s->gzhead->comment == Z_NULL ? 0 : 16)
+                     );
+            put_byte(s, (Byte)(s->gzhead->time & 0xff));
+            put_byte(s, (Byte)((s->gzhead->time >> 8) & 0xff));
+            put_byte(s, (Byte)((s->gzhead->time >> 16) & 0xff));
+            put_byte(s, (Byte)((s->gzhead->time >> 24) & 0xff));
+            put_byte(s, s->level == 9 ? 2 :
+                     (s->strategy >= Z_HUFFMAN_ONLY || s->level < 2 ?
+                      4 : 0));
+            put_byte(s, s->gzhead->os & 0xff);
+            if (s->gzhead->extra != Z_NULL) {
+                put_byte(s, s->gzhead->extra_len & 0xff);
+                put_byte(s, (s->gzhead->extra_len >> 8) & 0xff);
+            }
+            if (s->gzhead->hcrc)
+                strm->adler = crc32(strm->adler, s->pending_buf,
+                                    s->pending);
+            s->gzindex = 0;
+            s->status = EXTRA_STATE;
+        }
+    }
+    if (s->status == EXTRA_STATE) {
+        if (s->gzhead->extra != Z_NULL) {
+            ulg beg = s->pending;   /* start of bytes to update crc */
+            uInt left = (s->gzhead->extra_len & 0xffff) - s->gzindex;
+            while (s->pending + left > s->pending_buf_size) {
+                uInt copy = s->pending_buf_size - s->pending;
+                zmemcpy(s->pending_buf + s->pending,
+                        s->gzhead->extra + s->gzindex, copy);
+                s->pending = s->pending_buf_size;
+                HCRC_UPDATE(beg);
+                s->gzindex += copy;
+                flush_pending(strm);
+                if (s->pending != 0) {
+                    s->last_flush = -1;
+                    return Z_OK;
+                }
+                beg = 0;
+                left -= copy;
+            }
+            zmemcpy(s->pending_buf + s->pending,
+                    s->gzhead->extra + s->gzindex, left);
+            s->pending += left;
+            HCRC_UPDATE(beg);
+            s->gzindex = 0;
+        }
+        s->status = NAME_STATE;
+    }
+    if (s->status == NAME_STATE) {
+        if (s->gzhead->name != Z_NULL) {
+            ulg beg = s->pending;   /* start of bytes to update crc */
+            int val;
+            do {
+                if (s->pending == s->pending_buf_size) {
+                    HCRC_UPDATE(beg);
+                    flush_pending(strm);
+                    if (s->pending != 0) {
+                        s->last_flush = -1;
+                        return Z_OK;
+                    }
+                    beg = 0;
+                }
+                val = s->gzhead->name[s->gzindex++];
+                put_byte(s, val);
+            } while (val != 0);
+            HCRC_UPDATE(beg);
+            s->gzindex = 0;
+        }
+        s->status = COMMENT_STATE;
+    }
+    if (s->status == COMMENT_STATE) {
+        if (s->gzhead->comment != Z_NULL) {
+            ulg beg = s->pending;   /* start of bytes to update crc */
+            int val;
+            do {
+                if (s->pending == s->pending_buf_size) {
+                    HCRC_UPDATE(beg);
+                    flush_pending(strm);
+                    if (s->pending != 0) {
+                        s->last_flush = -1;
+                        return Z_OK;
+                    }
+                    beg = 0;
+                }
+                val = s->gzhead->comment[s->gzindex++];
+                put_byte(s, val);
+            } while (val != 0);
+            HCRC_UPDATE(beg);
+        }
+        s->status = HCRC_STATE;
+    }
+    if (s->status == HCRC_STATE) {
+        if (s->gzhead->hcrc) {
+            if (s->pending + 2 > s->pending_buf_size) {
+                flush_pending(strm);
+                if (s->pending != 0) {
+                    s->last_flush = -1;
+                    return Z_OK;
+                }
+            }
+            put_byte(s, (Byte)(strm->adler & 0xff));
+            put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
+            strm->adler = crc32(0L, Z_NULL, 0);
+        }
+        s->status = BUSY_STATE;
+
+        /* Compression must start with an empty pending buffer */
+        flush_pending(strm);
+        if (s->pending != 0) {
+            s->last_flush = -1;
+            return Z_OK;
+        }
+    }
+#endif
+
+    /* Start a new block or continue the current one.
+     */
+    if (strm->avail_in != 0 || s->lookahead != 0 ||
+        (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
+        block_state bstate;
+
+        bstate = s->level == 0 ? deflate_stored(s, flush) :
+                 s->strategy == Z_HUFFMAN_ONLY ? deflate_huff(s, flush) :
+                 s->strategy == Z_RLE ? deflate_rle(s, flush) :
+                 (*(configuration_table[s->level].func))(s, flush);
+
+        if (bstate == finish_started || bstate == finish_done) {
+            s->status = FINISH_STATE;
+        }
+        if (bstate == need_more || bstate == finish_started) {
+            if (strm->avail_out == 0) {
+                s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
+            }
+            return Z_OK;
+            /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
+             * of deflate should use the same flush parameter to make sure
+             * that the flush is complete. So we don't have to output an
+             * empty block here, this will be done at next call. This also
+             * ensures that for a very small output buffer, we emit at most
+             * one empty block.
+             */
+        }
+        if (bstate == block_done) {
+            if (flush == Z_PARTIAL_FLUSH) {
+                _tr_align(s);
+            } else if (flush != Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
+                _tr_stored_block(s, (char*)0, 0L, 0);
+                /* For a full flush, this empty block will be recognized
+                 * as a special marker by inflate_sync().
+                 */
+                if (flush == Z_FULL_FLUSH) {
+                    CLEAR_HASH(s);             /* forget history */
+                    if (s->lookahead == 0) {
+                        s->strstart = 0;
+                        s->block_start = 0L;
+                        s->insert = 0;
+                    }
+                }
+            }
+            flush_pending(strm);
+            if (strm->avail_out == 0) {
+              s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
+              return Z_OK;
+            }
+        }
+    }
+
+    if (flush != Z_FINISH) return Z_OK;
+    if (s->wrap <= 0) return Z_STREAM_END;
+
+    /* Write the trailer */
+#ifdef GZIP
+    if (s->wrap == 2) {
+        put_byte(s, (Byte)(strm->adler & 0xff));
+        put_byte(s, (Byte)((strm->adler >> 8) & 0xff));
+        put_byte(s, (Byte)((strm->adler >> 16) & 0xff));
+        put_byte(s, (Byte)((strm->adler >> 24) & 0xff));
+        put_byte(s, (Byte)(strm->total_in & 0xff));
+        put_byte(s, (Byte)((strm->total_in >> 8) & 0xff));
+        put_byte(s, (Byte)((strm->total_in >> 16) & 0xff));
+        put_byte(s, (Byte)((strm->total_in >> 24) & 0xff));
+    }
+    else
+#endif
+    {
+        putShortMSB(s, (uInt)(strm->adler >> 16));
+        putShortMSB(s, (uInt)(strm->adler & 0xffff));
+    }
+    flush_pending(strm);
+    /* If avail_out is zero, the application will call deflate again
+     * to flush the rest.
+     */
+    if (s->wrap > 0) s->wrap = -s->wrap; /* write the trailer only once! */
+    return s->pending != 0 ? Z_OK : Z_STREAM_END;
+}
+
+/* ========================================================================= */
+int ZEXPORT deflateEnd (strm)
+    z_streamp strm;
+{
+    int status;
+
+    if (deflateStateCheck(strm)) return Z_STREAM_ERROR;
+
+    status = strm->state->status;
+
+    /* Deallocate in reverse order of allocations: */
+    TRY_FREE(strm, strm->state->pending_buf);
+    TRY_FREE(strm, strm->state->head);
+    TRY_FREE(strm, strm->state->prev);
+    TRY_FREE(strm, strm->state->window);
+
+    ZFREE(strm, strm->state);
+    strm->state = Z_NULL;
+
+    return status == BUSY_STATE ? Z_DATA_ERROR : Z_OK;
+}
+
+/* =========================================================================
+ * Copy the source state to the destination state.
+ * To simplify the source, this is not supported for 16-bit MSDOS (which
+ * doesn't have enough memory anyway to duplicate compression states).
+ */
+int ZEXPORT deflateCopy (dest, source)
+    z_streamp dest;
+    z_streamp source;
+{
+#ifdef MAXSEG_64K
+    return Z_STREAM_ERROR;
+#else
+    deflate_state *ds;
+    deflate_state *ss;
+    ushf *overlay;
+
+
+    if (deflateStateCheck(source) || dest == Z_NULL) {
+        return Z_STREAM_ERROR;
+    }
+
+    ss = source->state;
+
+    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
+
+    ds = (deflate_state *) ZALLOC(dest, 1, sizeof(deflate_state));
+    if (ds == Z_NULL) return Z_MEM_ERROR;
+    dest->state = (struct internal_state FAR *) ds;
+    zmemcpy((voidpf)ds, (voidpf)ss, sizeof(deflate_state));
+    ds->strm = dest;
+
+    ds->window = (Bytef *) ZALLOC(dest, ds->w_size, 2*sizeof(Byte));
+    ds->prev   = (Posf *)  ZALLOC(dest, ds->w_size, sizeof(Pos));
+    ds->head   = (Posf *)  ZALLOC(dest, ds->hash_size, sizeof(Pos));
+    overlay = (ushf *) ZALLOC(dest, ds->lit_bufsize, sizeof(ush)+2);
+    ds->pending_buf = (uchf *) overlay;
+
+    if (ds->window == Z_NULL || ds->prev == Z_NULL || ds->head == Z_NULL ||
+        ds->pending_buf == Z_NULL) {
+        deflateEnd (dest);
+        return Z_MEM_ERROR;
+    }
+    /* following zmemcpy do not work for 16-bit MSDOS */
+    zmemcpy(ds->window, ss->window, ds->w_size * 2 * sizeof(Byte));
+    zmemcpy((voidpf)ds->prev, (voidpf)ss->prev, ds->w_size * sizeof(Pos));
+    zmemcpy((voidpf)ds->head, (voidpf)ss->head, ds->hash_size * sizeof(Pos));
+    zmemcpy(ds->pending_buf, ss->pending_buf, (uInt)ds->pending_buf_size);
+
+    ds->pending_out = ds->pending_buf + (ss->pending_out - ss->pending_buf);
+    ds->d_buf = overlay + ds->lit_bufsize/sizeof(ush);
+    ds->l_buf = ds->pending_buf + (1+sizeof(ush))*ds->lit_bufsize;
+
+    ds->l_desc.dyn_tree = ds->dyn_ltree;
+    ds->d_desc.dyn_tree = ds->dyn_dtree;
+    ds->bl_desc.dyn_tree = ds->bl_tree;
+
+    return Z_OK;
+#endif /* MAXSEG_64K */
+}
+
+/* ===========================================================================
+ * Read a new buffer from the current input stream, update the adler32
+ * and total number of bytes read.  All deflate() input goes through
+ * this function so some applications may wish to modify it to avoid
+ * allocating a large strm->next_in buffer and copying from it.
+ * (See also flush_pending()).
+ */
+local unsigned read_buf(strm, buf, size)
+    z_streamp strm;
+    Bytef *buf;
+    unsigned size;
+{
+    unsigned len = strm->avail_in;
+
+    if (len > size) len = size;
+    if (len == 0) return 0;
+
+    strm->avail_in  -= len;
+
+    zmemcpy(buf, strm->next_in, len);
+    if (strm->state->wrap == 1) {
+        strm->adler = adler32(strm->adler, buf, len);
+    }
+#ifdef GZIP
+    else if (strm->state->wrap == 2) {
+        strm->adler = crc32(strm->adler, buf, len);
+    }
+#endif
+    strm->next_in  += len;
+    strm->total_in += len;
+
+    return len;
+}
+
+/* ===========================================================================
+ * Initialize the "longest match" routines for a new zlib stream
+ */
+local void lm_init (s)
+    deflate_state *s;
+{
+    s->window_size = (ulg)2L*s->w_size;
+
+    CLEAR_HASH(s);
+
+    /* Set the default configuration parameters:
+     */
+    s->max_lazy_match   = configuration_table[s->level].max_lazy;
+    s->good_match       = configuration_table[s->level].good_length;
+    s->nice_match       = configuration_table[s->level].nice_length;
+    s->max_chain_length = configuration_table[s->level].max_chain;
+
+    s->strstart = 0;
+    s->block_start = 0L;
+    s->lookahead = 0;
+    s->insert = 0;
+    s->match_length = s->prev_length = MIN_MATCH-1;
+    s->match_available = 0;
+    s->ins_h = 0;
+#ifndef FASTEST
+#ifdef ASMV
+    match_init(); /* initialize the asm code */
+#endif
+#endif
+}
+
+#ifndef FASTEST
+/* ===========================================================================
+ * Set match_start to the longest match starting at the given string and
+ * return its length. Matches shorter or equal to prev_length are discarded,
+ * in which case the result is equal to prev_length and match_start is
+ * garbage.
+ * IN assertions: cur_match is the head of the hash chain for the current
+ *   string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
+ * OUT assertion: the match length is not greater than s->lookahead.
+ */
+#ifndef ASMV
+/* For 80x86 and 680x0, an optimized version will be provided in match.asm or
+ * match.S. The code will be functionally equivalent.
+ */
+local uInt longest_match(s, cur_match)
+    deflate_state *s;
+    IPos cur_match;                             /* current match */
+{
+    unsigned chain_length = s->max_chain_length;/* max hash chain length */
+    register Bytef *scan = s->window + s->strstart; /* current string */
+    register Bytef *match;                      /* matched string */
+    register int len;                           /* length of current match */
+    int best_len = (int)s->prev_length;         /* best match length so far */
+    int nice_match = s->nice_match;             /* stop if match long enough */
+    IPos limit = s->strstart > (IPos)MAX_DIST(s) ?
+        s->strstart - (IPos)MAX_DIST(s) : NIL;
+    /* Stop when cur_match becomes <= limit. To simplify the code,
+     * we prevent matches with the string of window index 0.
+     */
+    Posf *prev = s->prev;
+    uInt wmask = s->w_mask;
+
+#ifdef UNALIGNED_OK
+    /* Compare two bytes at a time. Note: this is not always beneficial.
+     * Try with and without -DUNALIGNED_OK to check.
+     */
+    register Bytef *strend = s->window + s->strstart + MAX_MATCH - 1;
+    register ush scan_start = *(ushf*)scan;
+    register ush scan_end   = *(ushf*)(scan+best_len-1);
+#else
+    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
+    register Byte scan_end1  = scan[best_len-1];
+    register Byte scan_end   = scan[best_len];
+#endif
+
+    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
+     * It is easy to get rid of this optimization if necessary.
+     */
+    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
+
+    /* Do not waste too much time if we already have a good match: */
+    if (s->prev_length >= s->good_match) {
+        chain_length >>= 2;
+    }
+    /* Do not look for matches beyond the end of the input. This is necessary
+     * to make deflate deterministic.
+     */
+    if ((uInt)nice_match > s->lookahead) nice_match = (int)s->lookahead;
+
+    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
+
+    do {
+        Assert(cur_match < s->strstart, "no future");
+        match = s->window + cur_match;
+
+        /* Skip to next match if the match length cannot increase
+         * or if the match length is less than 2.  Note that the checks below
+         * for insufficient lookahead only occur occasionally for performance
+         * reasons.  Therefore uninitialized memory will be accessed, and
+         * conditional jumps will be made that depend on those values.
+         * However the length of the match is limited to the lookahead, so
+         * the output of deflate is not affected by the uninitialized values.
+         */
+#if (defined(UNALIGNED_OK) && MAX_MATCH == 258)
+        /* This code assumes sizeof(unsigned short) == 2. Do not use
+         * UNALIGNED_OK if your compiler uses a different size.
+         */
+        if (*(ushf*)(match+best_len-1) != scan_end ||
+            *(ushf*)match != scan_start) continue;
+
+        /* It is not necessary to compare scan[2] and match[2] since they are
+         * always equal when the other bytes match, given that the hash keys
+         * are equal and that HASH_BITS >= 8. Compare 2 bytes at a time at
+         * strstart+3, +5, ... up to strstart+257. We check for insufficient
+         * lookahead only every 4th comparison; the 128th check will be made
+         * at strstart+257. If MAX_MATCH-2 is not a multiple of 8, it is
+         * necessary to put more guard bytes at the end of the window, or
+         * to check more often for insufficient lookahead.
+         */
+        Assert(scan[2] == match[2], "scan[2]?");
+        scan++, match++;
+        do {
+        } while (*(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
+                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
+                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
+                 *(ushf*)(scan+=2) == *(ushf*)(match+=2) &&
+                 scan < strend);
+        /* The funny "do {}" generates better code on most compilers */
+
+        /* Here, scan <= window+strstart+257 */
+        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
+        if (*scan == *match) scan++;
+
+        len = (MAX_MATCH - 1) - (int)(strend-scan);
+        scan = strend - (MAX_MATCH-1);
+
+#else /* UNALIGNED_OK */
+
+        if (match[best_len]   != scan_end  ||
+            match[best_len-1] != scan_end1 ||
+            *match            != *scan     ||
+            *++match          != scan[1])      continue;
+
+        /* The check at best_len-1 can be removed because it will be made
+         * again later. (This heuristic is not always a win.)
+         * It is not necessary to compare scan[2] and match[2] since they
+         * are always equal when the other bytes match, given that
+         * the hash keys are equal and that HASH_BITS >= 8.
+         */
+        scan += 2, match++;
+        Assert(*scan == *match, "match[2]?");
+
+        /* We check for insufficient lookahead only every 8th comparison;
+         * the 256th check will be made at strstart+258.
+         */
+        do {
+        } while (*++scan == *++match && *++scan == *++match &&
+                 *++scan == *++match && *++scan == *++match &&
+                 *++scan == *++match && *++scan == *++match &&
+                 *++scan == *++match && *++scan == *++match &&
+                 scan < strend);
+
+        Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
+
+        len = MAX_MATCH - (int)(strend - scan);
+        scan = strend - MAX_MATCH;
+
+#endif /* UNALIGNED_OK */
+
+        if (len > best_len) {
+            s->match_start = cur_match;
+            best_len = len;
+            if (len >= nice_match) break;
+#ifdef UNALIGNED_OK
+            scan_end = *(ushf*)(scan+best_len-1);
+#else
+            scan_end1  = scan[best_len-1];
+            scan_end   = scan[best_len];
+#endif
+        }
+    } while ((cur_match = prev[cur_match & wmask]) > limit
+             && --chain_length != 0);
+
+    if ((uInt)best_len <= s->lookahead) return (uInt)best_len;
+    return s->lookahead;
+}
+#endif /* ASMV */
+
+#else /* FASTEST */
+
+/* ---------------------------------------------------------------------------
+ * Optimized version for FASTEST only
+ */
+local uInt longest_match(s, cur_match)
+    deflate_state *s;
+    IPos cur_match;                             /* current match */
+{
+    register Bytef *scan = s->window + s->strstart; /* current string */
+    register Bytef *match;                       /* matched string */
+    register int len;                           /* length of current match */
+    register Bytef *strend = s->window + s->strstart + MAX_MATCH;
+
+    /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
+     * It is easy to get rid of this optimization if necessary.
+     */
+    Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
+
+    Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
+
+    Assert(cur_match < s->strstart, "no future");
+
+    match = s->window + cur_match;
+
+    /* Return failure if the match length is less than 2:
+     */
+    if (match[0] != scan[0] || match[1] != scan[1]) return MIN_MATCH-1;
+
+    /* The check at best_len-1 can be removed because it will be made
+     * again later. (This heuristic is not always a win.)
+     * It is not necessary to compare scan[2] and match[2] since they
+     * are always equal when the other bytes match, given that
+     * the hash keys are equal and that HASH_BITS >= 8.
+     */
+    scan += 2, match += 2;
+    Assert(*scan == *match, "match[2]?");
+
+    /* We check for insufficient lookahead only every 8th comparison;
+     * the 256th check will be made at strstart+258.
+     */
+    do {
+    } while (*++scan == *++match && *++scan == *++match &&
+             *++scan == *++match && *++scan == *++match &&
+             *++scan == *++match && *++scan == *++match &&
+             *++scan == *++match && *++scan == *++match &&
+             scan < strend);
+
+    Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
+
+    len = MAX_MATCH - (int)(strend - scan);
+
+    if (len < MIN_MATCH) return MIN_MATCH - 1;
+
+    s->match_start = cur_match;
+    return (uInt)len <= s->lookahead ? (uInt)len : s->lookahead;
+}
+
+#endif /* FASTEST */
+
+#ifdef ZLIB_DEBUG
+
+#define EQUAL 0
+/* result of memcmp for equal strings */
+
+/* ===========================================================================
+ * Check that the match at match_start is indeed a match.
+ */
+local void check_match(s, start, match, length)
+    deflate_state *s;
+    IPos start, match;
+    int length;
+{
+    /* check that the match is indeed a match */
+    if (zmemcmp(s->window + match,
+                s->window + start, length) != EQUAL) {
+        fprintf(stderr, " start %u, match %u, length %d\n",
+                start, match, length);
+        do {
+            fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
+        } while (--length != 0);
+        z_error("invalid match");
+    }
+    if (z_verbose > 1) {
+        fprintf(stderr,"\\[%d,%d]", start-match, length);
+        do { putc(s->window[start++], stderr); } while (--length != 0);
+    }
+}
+#else
+#  define check_match(s, start, match, length)
+#endif /* ZLIB_DEBUG */
+
+/* ===========================================================================
+ * Fill the window when the lookahead becomes insufficient.
+ * Updates strstart and lookahead.
+ *
+ * IN assertion: lookahead < MIN_LOOKAHEAD
+ * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
+ *    At least one byte has been read, or avail_in == 0; reads are
+ *    performed for at least two bytes (required for the zip translate_eol
+ *    option -- not supported here).
+ */
+local void fill_window(s)
+    deflate_state *s;
+{
+    unsigned n;
+    unsigned more;    /* Amount of free space at the end of the window. */
+    uInt wsize = s->w_size;
+
+    Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
+
+    do {
+        more = (unsigned)(s->window_size -(ulg)s->lookahead -(ulg)s->strstart);
+
+        /* Deal with !@#$% 64K limit: */
+        if (sizeof(int) <= 2) {
+            if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
+                more = wsize;
+
+            } else if (more == (unsigned)(-1)) {
+                /* Very unlikely, but possible on 16 bit machine if
+                 * strstart == 0 && lookahead == 1 (input done a byte at time)
+                 */
+                more--;
+            }
+        }
+
+        /* If the window is almost full and there is insufficient lookahead,
+         * move the upper half to the lower one to make room in the upper half.
+         */
+        if (s->strstart >= wsize+MAX_DIST(s)) {
+
+            zmemcpy(s->window, s->window+wsize, (unsigned)wsize - more);
+            s->match_start -= wsize;
+            s->strstart    -= wsize; /* we now have strstart >= MAX_DIST */
+            s->block_start -= (long) wsize;
+            slide_hash(s);
+            more += wsize;
+        }
+        if (s->strm->avail_in == 0) break;
+
+        /* If there was no sliding:
+         *    strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
+         *    more == window_size - lookahead - strstart
+         * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
+         * => more >= window_size - 2*WSIZE + 2
+         * In the BIG_MEM or MMAP case (not yet supported),
+         *   window_size == input_size + MIN_LOOKAHEAD  &&
+         *   strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
+         * Otherwise, window_size == 2*WSIZE so more >= 2.
+         * If there was sliding, more >= WSIZE. So in all cases, more >= 2.
+         */
+        Assert(more >= 2, "more < 2");
+
+        n = read_buf(s->strm, s->window + s->strstart + s->lookahead, more);
+        s->lookahead += n;
+
+        /* Initialize the hash value now that we have some input: */
+        if (s->lookahead + s->insert >= MIN_MATCH) {
+            uInt str = s->strstart - s->insert;
+            s->ins_h = s->window[str];
+            UPDATE_HASH(s, s->ins_h, s->window[str + 1]);
+#if MIN_MATCH != 3
+            Call UPDATE_HASH() MIN_MATCH-3 more times
+#endif
+            while (s->insert) {
+                UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]);
+#ifndef FASTEST
+                s->prev[str & s->w_mask] = s->head[s->ins_h];
+#endif
+                s->head[s->ins_h] = (Pos)str;
+                str++;
+                s->insert--;
+                if (s->lookahead + s->insert < MIN_MATCH)
+                    break;
+            }
+        }
+        /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
+         * but this is not important since only literal bytes will be emitted.
+         */
+
+    } while (s->lookahead < MIN_LOOKAHEAD && s->strm->avail_in != 0);
+
+    /* If the WIN_INIT bytes after the end of the current data have never been
+     * written, then zero those bytes in order to avoid memory check reports of
+     * the use of uninitialized (or uninitialised as Julian writes) bytes by
+     * the longest match routines.  Update the high water mark for the next
+     * time through here.  WIN_INIT is set to MAX_MATCH since the longest match
+     * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
+     */
+    if (s->high_water < s->window_size) {
+        ulg curr = s->strstart + (ulg)(s->lookahead);
+        ulg init;
+
+        if (s->high_water < curr) {
+            /* Previous high water mark below current data -- zero WIN_INIT
+             * bytes or up to end of window, whichever is less.
+             */
+            init = s->window_size - curr;
+            if (init > WIN_INIT)
+                init = WIN_INIT;
+            zmemzero(s->window + curr, (unsigned)init);
+            s->high_water = curr + init;
+        }
+        else if (s->high_water < (ulg)curr + WIN_INIT) {
+            /* High water mark at or above current data, but below current data
+             * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
+             * to end of window, whichever is less.
+             */
+            init = (ulg)curr + WIN_INIT - s->high_water;
+            if (init > s->window_size - s->high_water)
+                init = s->window_size - s->high_water;
+            zmemzero(s->window + s->high_water, (unsigned)init);
+            s->high_water += init;
+        }
+    }
+
+    Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
+           "not enough room for search");
+}
+
+/* ===========================================================================
+ * Flush the current block, with given end-of-file flag.
+ * IN assertion: strstart is set to the end of the current match.
+ */
+#define FLUSH_BLOCK_ONLY(s, last) { \
+   _tr_flush_block(s, (s->block_start >= 0L ? \
+                   (charf *)&s->window[(unsigned)s->block_start] : \
+                   (charf *)Z_NULL), \
+                (ulg)((long)s->strstart - s->block_start), \
+                (last)); \
+   s->block_start = s->strstart; \
+   flush_pending(s->strm); \
+   Tracev((stderr,"[FLUSH]")); \
+}
+
+/* Same but force premature exit if necessary. */
+#define FLUSH_BLOCK(s, last) { \
+   FLUSH_BLOCK_ONLY(s, last); \
+   if (s->strm->avail_out == 0) return (last) ? finish_started : need_more; \
+}
+
+/* Maximum stored block length in deflate format (not including header). */
+#define MAX_STORED 65535
+
+/* Minimum of a and b. */
+#define MIN(a, b) ((a) > (b) ? (b) : (a))
+
+/* ===========================================================================
+ * Copy without compression as much as possible from the input stream, return
+ * the current block state.
+ *
+ * In case deflateParams() is used to later switch to a non-zero compression
+ * level, s->matches (otherwise unused when storing) keeps track of the number
+ * of hash table slides to perform. If s->matches is 1, then one hash table
+ * slide will be done when switching. If s->matches is 2, the maximum value
+ * allowed here, then the hash table will be cleared, since two or more slides
+ * is the same as a clear.
+ *
+ * deflate_stored() is written to minimize the number of times an input byte is
+ * copied. It is most efficient with large input and output buffers, which
+ * maximizes the opportunites to have a single copy from next_in to next_out.
+ */
+local block_state deflate_stored(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    /* Smallest worthy block size when not flushing or finishing. By default
+     * this is 32K. This can be as small as 507 bytes for memLevel == 1. For
+     * large input and output buffers, the stored block size will be larger.
+     */
+    unsigned min_block = MIN(s->pending_buf_size - 5, s->w_size);
+
+    /* Copy as many min_block or larger stored blocks directly to next_out as
+     * possible. If flushing, copy the remaining available input to next_out as
+     * stored blocks, if there is enough space.
+     */
+    unsigned len, left, have, last = 0;
+    unsigned used = s->strm->avail_in;
+    do {
+        /* Set len to the maximum size block that we can copy directly with the
+         * available input data and output space. Set left to how much of that
+         * would be copied from what's left in the window.
+         */
+        len = MAX_STORED;       /* maximum deflate stored block length */
+        have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
+        if (s->strm->avail_out < have)          /* need room for header */
+            break;
+            /* maximum stored block length that will fit in avail_out: */
+        have = s->strm->avail_out - have;
+        left = s->strstart - s->block_start;    /* bytes left in window */
+        if (len > (ulg)left + s->strm->avail_in)
+            len = left + s->strm->avail_in;     /* limit len to the input */
+        if (len > have)
+            len = have;                         /* limit len to the output */
+
+        /* If the stored block would be less than min_block in length, or if
+         * unable to copy all of the available input when flushing, then try
+         * copying to the window and the pending buffer instead. Also don't
+         * write an empty block when flushing -- deflate() does that.
+         */
+        if (len < min_block && ((len == 0 && flush != Z_FINISH) ||
+                                flush == Z_NO_FLUSH ||
+                                len != left + s->strm->avail_in))
+            break;
+
+        /* Make a dummy stored block in pending to get the header bytes,
+         * including any pending bits. This also updates the debugging counts.
+         */
+        last = flush == Z_FINISH && len == left + s->strm->avail_in ? 1 : 0;
+        _tr_stored_block(s, (char *)0, 0L, last);
+
+        /* Replace the lengths in the dummy stored block with len. */
+        s->pending_buf[s->pending - 4] = len;
+        s->pending_buf[s->pending - 3] = len >> 8;
+        s->pending_buf[s->pending - 2] = ~len;
+        s->pending_buf[s->pending - 1] = ~len >> 8;
+
+        /* Write the stored block header bytes. */
+        flush_pending(s->strm);
+
+#ifdef ZLIB_DEBUG
+        /* Update debugging counts for the data about to be copied. */
+        s->compressed_len += len << 3;
+        s->bits_sent += len << 3;
+#endif
+
+        /* Copy uncompressed bytes from the window to next_out. */
+        if (left) {
+            if (left > len)
+                left = len;
+            zmemcpy(s->strm->next_out, s->window + s->block_start, left);
+            s->strm->next_out += left;
+            s->strm->avail_out -= left;
+            s->strm->total_out += left;
+            s->block_start += left;
+            len -= left;
+        }
+
+        /* Copy uncompressed bytes directly from next_in to next_out, updating
+         * the check value.
+         */
+        if (len) {
+            read_buf(s->strm, s->strm->next_out, len);
+            s->strm->next_out += len;
+            s->strm->avail_out -= len;
+            s->strm->total_out += len;
+        }
+    } while (last == 0);
+
+    /* Update the sliding window with the last s->w_size bytes of the copied
+     * data, or append all of the copied data to the existing window if less
+     * than s->w_size bytes were copied. Also update the number of bytes to
+     * insert in the hash tables, in the event that deflateParams() switches to
+     * a non-zero compression level.
+     */
+    used -= s->strm->avail_in;      /* number of input bytes directly copied */
+    if (used) {
+        /* If any input was used, then no unused input remains in the window,
+         * therefore s->block_start == s->strstart.
+         */
+        if (used >= s->w_size) {    /* supplant the previous history */
+            s->matches = 2;         /* clear hash */
+            zmemcpy(s->window, s->strm->next_in - s->w_size, s->w_size);
+            s->strstart = s->w_size;
+        }
+        else {
+            if (s->window_size - s->strstart <= used) {
+                /* Slide the window down. */
+                s->strstart -= s->w_size;
+                zmemcpy(s->window, s->window + s->w_size, s->strstart);
+                if (s->matches < 2)
+                    s->matches++;   /* add a pending slide_hash() */
+            }
+            zmemcpy(s->window + s->strstart, s->strm->next_in - used, used);
+            s->strstart += used;
+        }
+        s->block_start = s->strstart;
+        s->insert += MIN(used, s->w_size - s->insert);
+    }
+    if (s->high_water < s->strstart)
+        s->high_water = s->strstart;
+
+    /* If the last block was written to next_out, then done. */
+    if (last)
+        return finish_done;
+
+    /* If flushing and all input has been consumed, then done. */
+    if (flush != Z_NO_FLUSH && flush != Z_FINISH &&
+        s->strm->avail_in == 0 && (long)s->strstart == s->block_start)
+        return block_done;
+
+    /* Fill the window with any remaining input. */
+    have = s->window_size - s->strstart - 1;
+    if (s->strm->avail_in > have && s->block_start >= (long)s->w_size) {
+        /* Slide the window down. */
+        s->block_start -= s->w_size;
+        s->strstart -= s->w_size;
+        zmemcpy(s->window, s->window + s->w_size, s->strstart);
+        if (s->matches < 2)
+            s->matches++;           /* add a pending slide_hash() */
+        have += s->w_size;          /* more space now */
+    }
+    if (have > s->strm->avail_in)
+        have = s->strm->avail_in;
+    if (have) {
+        read_buf(s->strm, s->window + s->strstart, have);
+        s->strstart += have;
+    }
+    if (s->high_water < s->strstart)
+        s->high_water = s->strstart;
+
+    /* There was not enough avail_out to write a complete worthy or flushed
+     * stored block to next_out. Write a stored block to pending instead, if we
+     * have enough input for a worthy block, or if flushing and there is enough
+     * room for the remaining input as a stored block in the pending buffer.
+     */
+    have = (s->bi_valid + 42) >> 3;         /* number of header bytes */
+        /* maximum stored block length that will fit in pending: */
+    have = MIN(s->pending_buf_size - have, MAX_STORED);
+    min_block = MIN(have, s->w_size);
+    left = s->strstart - s->block_start;
+    if (left >= min_block ||
+        ((left || flush == Z_FINISH) && flush != Z_NO_FLUSH &&
+         s->strm->avail_in == 0 && left <= have)) {
+        len = MIN(left, have);
+        last = flush == Z_FINISH && s->strm->avail_in == 0 &&
+               len == left ? 1 : 0;
+        _tr_stored_block(s, (charf *)s->window + s->block_start, len, last);
+        s->block_start += len;
+        flush_pending(s->strm);
+    }
+
+    /* We've done all we can with the available input and output. */
+    return last ? finish_started : need_more;
+}
+
+/* ===========================================================================
+ * Compress as much as possible from the input stream, return the current
+ * block state.
+ * This function does not perform lazy evaluation of matches and inserts
+ * new strings in the dictionary only for unmatched strings or for short
+ * matches. It is used only for the fast compression options.
+ */
+local block_state deflate_fast(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    IPos hash_head;       /* head of the hash chain */
+    int bflush;           /* set if current block must be flushed */
+
+    for (;;) {
+        /* Make sure that we always have enough lookahead, except
+         * at the end of the input file. We need MAX_MATCH bytes
+         * for the next match, plus MIN_MATCH bytes to insert the
+         * string following the next match.
+         */
+        if (s->lookahead < MIN_LOOKAHEAD) {
+            fill_window(s);
+            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
+                return need_more;
+            }
+            if (s->lookahead == 0) break; /* flush the current block */
+        }
+
+        /* Insert the string window[strstart .. strstart+2] in the
+         * dictionary, and set hash_head to the head of the hash chain:
+         */
+        hash_head = NIL;
+        if (s->lookahead >= MIN_MATCH) {
+            INSERT_STRING(s, s->strstart, hash_head);
+        }
+
+        /* Find the longest match, discarding those <= prev_length.
+         * At this point we have always match_length < MIN_MATCH
+         */
+        if (hash_head != NIL && s->strstart - hash_head <= MAX_DIST(s)) {
+            /* To simplify the code, we prevent matches with the string
+             * of window index 0 (in particular we have to avoid a match
+             * of the string with itself at the start of the input file).
+             */
+            s->match_length = longest_match (s, hash_head);
+            /* longest_match() sets match_start */
+        }
+        if (s->match_length >= MIN_MATCH) {
+            check_match(s, s->strstart, s->match_start, s->match_length);
+
+            _tr_tally_dist(s, s->strstart - s->match_start,
+                           s->match_length - MIN_MATCH, bflush);
+
+            s->lookahead -= s->match_length;
+
+            /* Insert new strings in the hash table only if the match length
+             * is not too large. This saves time but degrades compression.
+             */
+#ifndef FASTEST
+            if (s->match_length <= s->max_insert_length &&
+                s->lookahead >= MIN_MATCH) {
+                s->match_length--; /* string at strstart already in table */
+                do {
+                    s->strstart++;
+                    INSERT_STRING(s, s->strstart, hash_head);
+                    /* strstart never exceeds WSIZE-MAX_MATCH, so there are
+                     * always MIN_MATCH bytes ahead.
+                     */
+                } while (--s->match_length != 0);
+                s->strstart++;
+            } else
+#endif
+            {
+                s->strstart += s->match_length;
+                s->match_length = 0;
+                s->ins_h = s->window[s->strstart];
+                UPDATE_HASH(s, s->ins_h, s->window[s->strstart+1]);
+#if MIN_MATCH != 3
+                Call UPDATE_HASH() MIN_MATCH-3 more times
+#endif
+                /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
+                 * matter since it will be recomputed at next deflate call.
+                 */
+            }
+        } else {
+            /* No match, output a literal byte */
+            Tracevv((stderr,"%c", s->window[s->strstart]));
+            _tr_tally_lit (s, s->window[s->strstart], bflush);
+            s->lookahead--;
+            s->strstart++;
+        }
+        if (bflush) FLUSH_BLOCK(s, 0);
+    }
+    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
+    if (flush == Z_FINISH) {
+        FLUSH_BLOCK(s, 1);
+        return finish_done;
+    }
+    if (s->last_lit)
+        FLUSH_BLOCK(s, 0);
+    return block_done;
+}
+
+#ifndef FASTEST
+/* ===========================================================================
+ * Same as above, but achieves better compression. We use a lazy
+ * evaluation for matches: a match is finally adopted only if there is
+ * no better match at the next window position.
+ */
+local block_state deflate_slow(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    IPos hash_head;          /* head of hash chain */
+    int bflush;              /* set if current block must be flushed */
+
+    /* Process the input block. */
+    for (;;) {
+        /* Make sure that we always have enough lookahead, except
+         * at the end of the input file. We need MAX_MATCH bytes
+         * for the next match, plus MIN_MATCH bytes to insert the
+         * string following the next match.
+         */
+        if (s->lookahead < MIN_LOOKAHEAD) {
+            fill_window(s);
+            if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
+                return need_more;
+            }
+            if (s->lookahead == 0) break; /* flush the current block */
+        }
+
+        /* Insert the string window[strstart .. strstart+2] in the
+         * dictionary, and set hash_head to the head of the hash chain:
+         */
+        hash_head = NIL;
+        if (s->lookahead >= MIN_MATCH) {
+            INSERT_STRING(s, s->strstart, hash_head);
+        }
+
+        /* Find the longest match, discarding those <= prev_length.
+         */
+        s->prev_length = s->match_length, s->prev_match = s->match_start;
+        s->match_length = MIN_MATCH-1;
+
+        if (hash_head != NIL && s->prev_length < s->max_lazy_match &&
+            s->strstart - hash_head <= MAX_DIST(s)) {
+            /* To simplify the code, we prevent matches with the string
+             * of window index 0 (in particular we have to avoid a match
+             * of the string with itself at the start of the input file).
+             */
+            s->match_length = longest_match (s, hash_head);
+            /* longest_match() sets match_start */
+
+            if (s->match_length <= 5 && (s->strategy == Z_FILTERED
+#if TOO_FAR <= 32767
+                || (s->match_length == MIN_MATCH &&
+                    s->strstart - s->match_start > TOO_FAR)
+#endif
+                )) {
+
+                /* If prev_match is also MIN_MATCH, match_start is garbage
+                 * but we will ignore the current match anyway.
+                 */
+                s->match_length = MIN_MATCH-1;
+            }
+        }
+        /* If there was a match at the previous step and the current
+         * match is not better, output the previous match:
+         */
+        if (s->prev_length >= MIN_MATCH && s->match_length <= s->prev_length) {
+            uInt max_insert = s->strstart + s->lookahead - MIN_MATCH;
+            /* Do not insert strings in hash table beyond this. */
+
+            check_match(s, s->strstart-1, s->prev_match, s->prev_length);
+
+            _tr_tally_dist(s, s->strstart -1 - s->prev_match,
+                           s->prev_length - MIN_MATCH, bflush);
+
+            /* Insert in hash table all strings up to the end of the match.
+             * strstart-1 and strstart are already inserted. If there is not
+             * enough lookahead, the last two strings are not inserted in
+             * the hash table.
+             */
+            s->lookahead -= s->prev_length-1;
+            s->prev_length -= 2;
+            do {
+                if (++s->strstart <= max_insert) {
+                    INSERT_STRING(s, s->strstart, hash_head);
+                }
+            } while (--s->prev_length != 0);
+            s->match_available = 0;
+            s->match_length = MIN_MATCH-1;
+            s->strstart++;
+
+            if (bflush) FLUSH_BLOCK(s, 0);
+
+        } else if (s->match_available) {
+            /* If there was no match at the previous position, output a
+             * single literal. If there was a match but the current match
+             * is longer, truncate the previous match to a single literal.
+             */
+            Tracevv((stderr,"%c", s->window[s->strstart-1]));
+            _tr_tally_lit(s, s->window[s->strstart-1], bflush);
+            if (bflush) {
+                FLUSH_BLOCK_ONLY(s, 0);
+            }
+            s->strstart++;
+            s->lookahead--;
+            if (s->strm->avail_out == 0) return need_more;
+        } else {
+            /* There is no previous match to compare with, wait for
+             * the next step to decide.
+             */
+            s->match_available = 1;
+            s->strstart++;
+            s->lookahead--;
+        }
+    }
+    Assert (flush != Z_NO_FLUSH, "no flush?");
+    if (s->match_available) {
+        Tracevv((stderr,"%c", s->window[s->strstart-1]));
+        _tr_tally_lit(s, s->window[s->strstart-1], bflush);
+        s->match_available = 0;
+    }
+    s->insert = s->strstart < MIN_MATCH-1 ? s->strstart : MIN_MATCH-1;
+    if (flush == Z_FINISH) {
+        FLUSH_BLOCK(s, 1);
+        return finish_done;
+    }
+    if (s->last_lit)
+        FLUSH_BLOCK(s, 0);
+    return block_done;
+}
+#endif /* FASTEST */
+
+/* ===========================================================================
+ * For Z_RLE, simply look for runs of bytes, generate matches only of distance
+ * one.  Do not maintain a hash table.  (It will be regenerated if this run of
+ * deflate switches away from Z_RLE.)
+ */
+local block_state deflate_rle(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    int bflush;             /* set if current block must be flushed */
+    uInt prev;              /* byte at distance one to match */
+    Bytef *scan, *strend;   /* scan goes up to strend for length of run */
+
+    for (;;) {
+        /* Make sure that we always have enough lookahead, except
+         * at the end of the input file. We need MAX_MATCH bytes
+         * for the longest run, plus one for the unrolled loop.
+         */
+        if (s->lookahead <= MAX_MATCH) {
+            fill_window(s);
+            if (s->lookahead <= MAX_MATCH && flush == Z_NO_FLUSH) {
+                return need_more;
+            }
+            if (s->lookahead == 0) break; /* flush the current block */
+        }
+
+        /* See how many times the previous byte repeats */
+        s->match_length = 0;
+        if (s->lookahead >= MIN_MATCH && s->strstart > 0) {
+            scan = s->window + s->strstart - 1;
+            prev = *scan;
+            if (prev == *++scan && prev == *++scan && prev == *++scan) {
+                strend = s->window + s->strstart + MAX_MATCH;
+                do {
+                } while (prev == *++scan && prev == *++scan &&
+                         prev == *++scan && prev == *++scan &&
+                         prev == *++scan && prev == *++scan &&
+                         prev == *++scan && prev == *++scan &&
+                         scan < strend);
+                s->match_length = MAX_MATCH - (uInt)(strend - scan);
+                if (s->match_length > s->lookahead)
+                    s->match_length = s->lookahead;
+            }
+            Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
+        }
+
+        /* Emit match if have run of MIN_MATCH or longer, else emit literal */
+        if (s->match_length >= MIN_MATCH) {
+            check_match(s, s->strstart, s->strstart - 1, s->match_length);
+
+            _tr_tally_dist(s, 1, s->match_length - MIN_MATCH, bflush);
+
+            s->lookahead -= s->match_length;
+            s->strstart += s->match_length;
+            s->match_length = 0;
+        } else {
+            /* No match, output a literal byte */
+            Tracevv((stderr,"%c", s->window[s->strstart]));
+            _tr_tally_lit (s, s->window[s->strstart], bflush);
+            s->lookahead--;
+            s->strstart++;
+        }
+        if (bflush) FLUSH_BLOCK(s, 0);
+    }
+    s->insert = 0;
+    if (flush == Z_FINISH) {
+        FLUSH_BLOCK(s, 1);
+        return finish_done;
+    }
+    if (s->last_lit)
+        FLUSH_BLOCK(s, 0);
+    return block_done;
+}
+
+/* ===========================================================================
+ * For Z_HUFFMAN_ONLY, do not look for matches.  Do not maintain a hash table.
+ * (It will be regenerated if this run of deflate switches away from Huffman.)
+ */
+local block_state deflate_huff(s, flush)
+    deflate_state *s;
+    int flush;
+{
+    int bflush;             /* set if current block must be flushed */
+
+    for (;;) {
+        /* Make sure that we have a literal to write. */
+        if (s->lookahead == 0) {
+            fill_window(s);
+            if (s->lookahead == 0) {
+                if (flush == Z_NO_FLUSH)
+                    return need_more;
+                break;      /* flush the current block */
+            }
+        }
+
+        /* Output a literal byte */
+        s->match_length = 0;
+        Tracevv((stderr,"%c", s->window[s->strstart]));
+        _tr_tally_lit (s, s->window[s->strstart], bflush);
+        s->lookahead--;
+        s->strstart++;
+        if (bflush) FLUSH_BLOCK(s, 0);
+    }
+    s->insert = 0;
+    if (flush == Z_FINISH) {
+        FLUSH_BLOCK(s, 1);
+        return finish_done;
+    }
+    if (s->last_lit)
+        FLUSH_BLOCK(s, 0);
+    return block_done;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/deflate.h	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,373 @@
+/*
+ * 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.
+ */
+
+/* deflate.h -- internal compression state
+ * Copyright (C) 1995-2016 Jean-loup Gailly
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* @(#) $Id$ */
+
+#ifndef DEFLATE_H
+#define DEFLATE_H
+
+#include "zutil.h"
+
+/* define NO_GZIP when compiling if you want to disable gzip header and
+   trailer creation by deflate().  NO_GZIP would be used to avoid linking in
+   the crc code when it is not needed.  For shared libraries, gzip encoding
+   should be left enabled. */
+#ifndef NO_GZIP
+#  define GZIP
+#endif
+
+/* ===========================================================================
+ * Internal compression state.
+ */
+
+#define LENGTH_CODES 29
+/* number of length codes, not counting the special END_BLOCK code */
+
+#define LITERALS  256
+/* number of literal bytes 0..255 */
+
+#define L_CODES (LITERALS+1+LENGTH_CODES)
+/* number of Literal or Length codes, including the END_BLOCK code */
+
+#define D_CODES   30
+/* number of distance codes */
+
+#define BL_CODES  19
+/* number of codes used to transfer the bit lengths */
+
+#define HEAP_SIZE (2*L_CODES+1)
+/* maximum heap size */
+
+#define MAX_BITS 15
+/* All codes must not exceed MAX_BITS bits */
+
+#define Buf_size 16
+/* size of bit buffer in bi_buf */
+
+#define INIT_STATE    42    /* zlib header -> BUSY_STATE */
+#ifdef GZIP
+#  define GZIP_STATE  57    /* gzip header -> BUSY_STATE | EXTRA_STATE */
+#endif
+#define EXTRA_STATE   69    /* gzip extra block -> NAME_STATE */
+#define NAME_STATE    73    /* gzip file name -> COMMENT_STATE */
+#define COMMENT_STATE 91    /* gzip comment -> HCRC_STATE */
+#define HCRC_STATE   103    /* gzip header CRC -> BUSY_STATE */
+#define BUSY_STATE   113    /* deflate -> FINISH_STATE */
+#define FINISH_STATE 666    /* stream complete */
+/* Stream status */
+
+
+/* Data structure describing a single value and its code string. */
+typedef struct ct_data_s {
+    union {
+        ush  freq;       /* frequency count */
+        ush  code;       /* bit string */
+    } fc;
+    union {
+        ush  dad;        /* father node in Huffman tree */
+        ush  len;        /* length of bit string */
+    } dl;
+} FAR ct_data;
+
+#define Freq fc.freq
+#define Code fc.code
+#define Dad  dl.dad
+#define Len  dl.len
+
+typedef struct static_tree_desc_s  static_tree_desc;
+
+typedef struct tree_desc_s {
+    ct_data *dyn_tree;           /* the dynamic tree */
+    int     max_code;            /* largest code with non zero frequency */
+    const static_tree_desc *stat_desc;  /* the corresponding static tree */
+} FAR tree_desc;
+
+typedef ush Pos;
+typedef Pos FAR Posf;
+typedef unsigned IPos;
+
+/* A Pos is an index in the character window. We use short instead of int to
+ * save space in the various tables. IPos is used only for parameter passing.
+ */
+
+typedef struct internal_state {
+    z_streamp strm;      /* pointer back to this zlib stream */
+    int   status;        /* as the name implies */
+    Bytef *pending_buf;  /* output still pending */
+    ulg   pending_buf_size; /* size of pending_buf */
+    Bytef *pending_out;  /* next pending byte to output to the stream */
+    ulg   pending;       /* nb of bytes in the pending buffer */
+    int   wrap;          /* bit 0 true for zlib, bit 1 true for gzip */
+    gz_headerp  gzhead;  /* gzip header information to write */
+    ulg   gzindex;       /* where in extra, name, or comment */
+    Byte  method;        /* can only be DEFLATED */
+    int   last_flush;    /* value of flush param for previous deflate call */
+
+                /* used by deflate.c: */
+
+    uInt  w_size;        /* LZ77 window size (32K by default) */
+    uInt  w_bits;        /* log2(w_size)  (8..16) */
+    uInt  w_mask;        /* w_size - 1 */
+
+    Bytef *window;
+    /* Sliding window. Input bytes are read into the second half of the window,
+     * and move to the first half later to keep a dictionary of at least wSize
+     * bytes. With this organization, matches are limited to a distance of
+     * wSize-MAX_MATCH bytes, but this ensures that IO is always
+     * performed with a length multiple of the block size. Also, it limits
+     * the window size to 64K, which is quite useful on MSDOS.
+     * To do: use the user input buffer as sliding window.
+     */
+
+    ulg window_size;
+    /* Actual size of window: 2*wSize, except when the user input buffer
+     * is directly used as sliding window.
+     */
+
+    Posf *prev;
+    /* Link to older string with same hash index. To limit the size of this
+     * array to 64K, this link is maintained only for the last 32K strings.
+     * An index in this array is thus a window index modulo 32K.
+     */
+
+    Posf *head; /* Heads of the hash chains or NIL. */
+
+    uInt  ins_h;          /* hash index of string to be inserted */
+    uInt  hash_size;      /* number of elements in hash table */
+    uInt  hash_bits;      /* log2(hash_size) */
+    uInt  hash_mask;      /* hash_size-1 */
+
+    uInt  hash_shift;
+    /* Number of bits by which ins_h must be shifted at each input
+     * step. It must be such that after MIN_MATCH steps, the oldest
+     * byte no longer takes part in the hash key, that is:
+     *   hash_shift * MIN_MATCH >= hash_bits
+     */
+
+    long block_start;
+    /* Window position at the beginning of the current output block. Gets
+     * negative when the window is moved backwards.
+     */
+
+    uInt match_length;           /* length of best match */
+    IPos prev_match;             /* previous match */
+    int match_available;         /* set if previous match exists */
+    uInt strstart;               /* start of string to insert */
+    uInt match_start;            /* start of matching string */
+    uInt lookahead;              /* number of valid bytes ahead in window */
+
+    uInt prev_length;
+    /* Length of the best match at previous step. Matches not greater than this
+     * are discarded. This is used in the lazy match evaluation.
+     */
+
+    uInt max_chain_length;
+    /* To speed up deflation, hash chains are never searched beyond this
+     * length.  A higher limit improves compression ratio but degrades the
+     * speed.
+     */
+
+    uInt max_lazy_match;
+    /* Attempt to find a better match only when the current match is strictly
+     * smaller than this value. This mechanism is used only for compression
+     * levels >= 4.
+     */
+#   define max_insert_length  max_lazy_match
+    /* Insert new strings in the hash table only if the match length is not
+     * greater than this length. This saves time but degrades compression.
+     * max_insert_length is used only for compression levels <= 3.
+     */
+
+    int level;    /* compression level (1..9) */
+    int strategy; /* favor or force Huffman coding*/
+
+    uInt good_match;
+    /* Use a faster search when the previous match is longer than this */
+
+    int nice_match; /* Stop searching when current match exceeds this */
+
+                /* used by trees.c: */
+    /* Didn't use ct_data typedef below to suppress compiler warning */
+    struct ct_data_s dyn_ltree[HEAP_SIZE];   /* literal and length tree */
+    struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
+    struct ct_data_s bl_tree[2*BL_CODES+1];  /* Huffman tree for bit lengths */
+
+    struct tree_desc_s l_desc;               /* desc. for literal tree */
+    struct tree_desc_s d_desc;               /* desc. for distance tree */
+    struct tree_desc_s bl_desc;              /* desc. for bit length tree */
+
+    ush bl_count[MAX_BITS+1];
+    /* number of codes at each bit length for an optimal tree */
+
+    int heap[2*L_CODES+1];      /* heap used to build the Huffman trees */
+    int heap_len;               /* number of elements in the heap */
+    int heap_max;               /* element of largest frequency */
+    /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
+     * The same heap array is used to build all trees.
+     */
+
+    uch depth[2*L_CODES+1];
+    /* Depth of each subtree used as tie breaker for trees of equal frequency
+     */
+
+    uchf *l_buf;          /* buffer for literals or lengths */
+
+    uInt  lit_bufsize;
+    /* Size of match buffer for literals/lengths.  There are 4 reasons for
+     * limiting lit_bufsize to 64K:
+     *   - frequencies can be kept in 16 bit counters
+     *   - if compression is not successful for the first block, all input
+     *     data is still in the window so we can still emit a stored block even
+     *     when input comes from standard input.  (This can also be done for
+     *     all blocks if lit_bufsize is not greater than 32K.)
+     *   - if compression is not successful for a file smaller than 64K, we can
+     *     even emit a stored file instead of a stored block (saving 5 bytes).
+     *     This is applicable only for zip (not gzip or zlib).
+     *   - creating new Huffman trees less frequently may not provide fast
+     *     adaptation to changes in the input data statistics. (Take for
+     *     example a binary file with poorly compressible code followed by
+     *     a highly compressible string table.) Smaller buffer sizes give
+     *     fast adaptation but have of course the overhead of transmitting
+     *     trees more frequently.
+     *   - I can't count above 4
+     */
+
+    uInt last_lit;      /* running index in l_buf */
+
+    ushf *d_buf;
+    /* Buffer for distances. To simplify the code, d_buf and l_buf have
+     * the same number of elements. To use different lengths, an extra flag
+     * array would be necessary.
+     */
+
+    ulg opt_len;        /* bit length of current block with optimal trees */
+    ulg static_len;     /* bit length of current block with static trees */
+    uInt matches;       /* number of string matches in current block */
+    uInt insert;        /* bytes at end of window left to insert */
+
+#ifdef ZLIB_DEBUG
+    ulg compressed_len; /* total bit length of compressed file mod 2^32 */
+    ulg bits_sent;      /* bit length of compressed data sent mod 2^32 */
+#endif
+
+    ush bi_buf;
+    /* Output buffer. bits are inserted starting at the bottom (least
+     * significant bits).
+     */
+    int bi_valid;
+    /* Number of valid bits in bi_buf.  All bits above the last valid bit
+     * are always zero.
+     */
+
+    ulg high_water;
+    /* High water mark offset in window for initialized bytes -- bytes above
+     * this are set to zero in order to avoid memory check warnings when
+     * longest match routines access bytes past the input.  This is then
+     * updated to the new high water mark.
+     */
+
+} FAR deflate_state;
+
+/* Output a byte on the stream.
+ * IN assertion: there is enough room in pending_buf.
+ */
+#define put_byte(s, c) {s->pending_buf[s->pending++] = (Bytef)(c);}
+
+
+#define MIN_LOOKAHEAD (MAX_MATCH+MIN_MATCH+1)
+/* Minimum amount of lookahead, except at the end of the input file.
+ * See deflate.c for comments about the MIN_MATCH+1.
+ */
+
+#define MAX_DIST(s)  ((s)->w_size-MIN_LOOKAHEAD)
+/* In order to simplify the code, particularly on 16 bit machines, match
+ * distances are limited to MAX_DIST instead of WSIZE.
+ */
+
+#define WIN_INIT MAX_MATCH
+/* Number of bytes after end of data in window to initialize in order to avoid
+   memory checker errors from longest match routines */
+
+        /* in trees.c */
+void ZLIB_INTERNAL _tr_init OF((deflate_state *s));
+int ZLIB_INTERNAL _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
+void ZLIB_INTERNAL _tr_flush_block OF((deflate_state *s, charf *buf,
+                        ulg stored_len, int last));
+void ZLIB_INTERNAL _tr_flush_bits OF((deflate_state *s));
+void ZLIB_INTERNAL _tr_align OF((deflate_state *s));
+void ZLIB_INTERNAL _tr_stored_block OF((deflate_state *s, charf *buf,
+                        ulg stored_len, int last));
+
+#define d_code(dist) \
+   ((dist) < 256 ? _dist_code[dist] : _dist_code[256+((dist)>>7)])
+/* Mapping from a distance to a distance code. dist is the distance - 1 and
+ * must not have side effects. _dist_code[256] and _dist_code[257] are never
+ * used.
+ */
+
+#ifndef ZLIB_DEBUG
+/* Inline versions of _tr_tally for speed: */
+
+#if defined(GEN_TREES_H) || !defined(STDC)
+  extern uch ZLIB_INTERNAL _length_code[];
+  extern uch ZLIB_INTERNAL _dist_code[];
+#else
+  extern const uch ZLIB_INTERNAL _length_code[];
+  extern const uch ZLIB_INTERNAL _dist_code[];
+#endif
+
+# define _tr_tally_lit(s, c, flush) \
+  { uch cc = (c); \
+    s->d_buf[s->last_lit] = 0; \
+    s->l_buf[s->last_lit++] = cc; \
+    s->dyn_ltree[cc].Freq++; \
+    flush = (s->last_lit == s->lit_bufsize-1); \
+   }
+# define _tr_tally_dist(s, distance, length, flush) \
+  { uch len = (uch)(length); \
+    ush dist = (ush)(distance); \
+    s->d_buf[s->last_lit] = dist; \
+    s->l_buf[s->last_lit++] = len; \
+    dist--; \
+    s->dyn_ltree[_length_code[len]+LITERALS+1].Freq++; \
+    s->dyn_dtree[d_code(dist)].Freq++; \
+    flush = (s->last_lit == s->lit_bufsize-1); \
+  }
+#else
+# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
+# define _tr_tally_dist(s, distance, length, flush) \
+              flush = _tr_tally(s, distance, length)
+#endif
+
+#endif /* DEFLATE_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/gzclose.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,49 @@
+/*
+ * 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.
+ */
+
+/* gzclose.c -- zlib gzclose() function
+ * Copyright (C) 2004, 2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "gzguts.h"
+
+/* gzclose() is in a separate file so that it is linked in only if it is used.
+   That way the other gzclose functions can be used instead to avoid linking in
+   unneeded compression or decompression routines. */
+int ZEXPORT gzclose(file)
+    gzFile file;
+{
+#ifndef NO_GZCOMPRESS
+    gz_statep state;
+
+    if (file == NULL)
+        return Z_STREAM_ERROR;
+    state = (gz_statep)file;
+
+    return state->mode == GZ_READ ? gzclose_r(file) : gzclose_w(file);
+#else
+    return gzclose_r(file);
+#endif
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/gzguts.h	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,242 @@
+/*
+ * 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.
+ */
+
+/* gzguts.h -- zlib internal header definitions for gz* operations
+ * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#ifdef _LARGEFILE64_SOURCE
+#  ifndef _LARGEFILE_SOURCE
+#    define _LARGEFILE_SOURCE 1
+#  endif
+#  ifdef _FILE_OFFSET_BITS
+#    undef _FILE_OFFSET_BITS
+#  endif
+#endif
+
+#ifdef HAVE_HIDDEN
+#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
+#else
+#  define ZLIB_INTERNAL
+#endif
+
+#include <stdio.h>
+#include "zlib.h"
+#ifdef STDC
+#  include <string.h>
+#  include <stdlib.h>
+#  include <limits.h>
+#endif
+
+#ifndef _POSIX_SOURCE
+#  define _POSIX_SOURCE
+#endif
+#include <fcntl.h>
+
+#ifdef _WIN32
+#  include <stddef.h>
+#endif
+
+#if defined(__TURBOC__) || defined(_MSC_VER) || defined(_WIN32)
+#  include <io.h>
+#endif
+
+#if defined(_WIN32) || defined(__CYGWIN__)
+#  define WIDECHAR
+#endif
+
+#ifdef WINAPI_FAMILY
+#  define open _open
+#  define read _read
+#  define write _write
+#  define close _close
+#endif
+
+#ifdef NO_DEFLATE       /* for compatibility with old definition */
+#  define NO_GZCOMPRESS
+#endif
+
+#if defined(STDC99) || (defined(__TURBOC__) && __TURBOC__ >= 0x550)
+#  ifndef HAVE_VSNPRINTF
+#    define HAVE_VSNPRINTF
+#  endif
+#endif
+
+#if defined(__CYGWIN__)
+#  ifndef HAVE_VSNPRINTF
+#    define HAVE_VSNPRINTF
+#  endif
+#endif
+
+#if defined(MSDOS) && defined(__BORLANDC__) && (BORLANDC > 0x410)
+#  ifndef HAVE_VSNPRINTF
+#    define HAVE_VSNPRINTF
+#  endif
+#endif
+
+#ifndef HAVE_VSNPRINTF
+#  ifdef MSDOS
+/* vsnprintf may exist on some MS-DOS compilers (DJGPP?),
+   but for now we just assume it doesn't. */
+#    define NO_vsnprintf
+#  endif
+#  ifdef __TURBOC__
+#    define NO_vsnprintf
+#  endif
+#  ifdef WIN32
+/* In Win32, vsnprintf is available as the "non-ANSI" _vsnprintf. */
+#    if !defined(vsnprintf) && !defined(NO_vsnprintf)
+#      if !defined(_MSC_VER) || ( defined(_MSC_VER) && _MSC_VER < 1500 )
+#         define vsnprintf _vsnprintf
+#      endif
+#    endif
+#  endif
+#  ifdef __SASC
+#    define NO_vsnprintf
+#  endif
+#  ifdef VMS
+#    define NO_vsnprintf
+#  endif
+#  ifdef __OS400__
+#    define NO_vsnprintf
+#  endif
+#  ifdef __MVS__
+#    define NO_vsnprintf
+#  endif
+#endif
+
+/* unlike snprintf (which is required in C99), _snprintf does not guarantee
+   null termination of the result -- however this is only used in gzlib.c where
+   the result is assured to fit in the space provided */
+#if defined(_MSC_VER) && _MSC_VER < 1900
+#  define snprintf _snprintf
+#endif
+
+#ifndef local
+#  define local static
+#endif
+/* since "static" is used to mean two completely different things in C, we
+   define "local" for the non-static meaning of "static", for readability
+   (compile with -Dlocal if your debugger can't find static symbols) */
+
+/* gz* functions always use library allocation functions */
+#ifndef STDC
+  extern voidp  malloc OF((uInt size));
+  extern void   free   OF((voidpf ptr));
+#endif
+
+/* get errno and strerror definition */
+#if defined UNDER_CE
+#  include <windows.h>
+#  define zstrerror() gz_strwinerror((DWORD)GetLastError())
+#else
+#  ifndef NO_STRERROR
+#    include <errno.h>
+#    define zstrerror() strerror(errno)
+#  else
+#    define zstrerror() "stdio error (consult errno)"
+#  endif
+#endif
+
+/* provide prototypes for these when building zlib without LFS */
+#if !defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0
+    ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+    ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
+    ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
+    ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
+#endif
+
+/* default memLevel */
+#if MAX_MEM_LEVEL >= 8
+#  define DEF_MEM_LEVEL 8
+#else
+#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
+#endif
+
+/* default i/o buffer size -- double this for output when reading (this and
+   twice this must be able to fit in an unsigned type) */
+#define GZBUFSIZE 8192
+
+/* gzip modes, also provide a little integrity check on the passed structure */
+#define GZ_NONE 0
+#define GZ_READ 7247
+#define GZ_WRITE 31153
+#define GZ_APPEND 1     /* mode set to GZ_WRITE after the file is opened */
+
+/* values for gz_state how */
+#define LOOK 0      /* look for a gzip header */
+#define COPY 1      /* copy input directly */
+#define GZIP 2      /* decompress a gzip stream */
+
+/* internal gzip file state data structure */
+typedef struct {
+        /* exposed contents for gzgetc() macro */
+    struct gzFile_s x;      /* "x" for exposed */
+                            /* x.have: number of bytes available at x.next */
+                            /* x.next: next output data to deliver or write */
+                            /* x.pos: current position in uncompressed data */
+        /* used for both reading and writing */
+    int mode;               /* see gzip modes above */
+    int fd;                 /* file descriptor */
+    char *path;             /* path or fd for error messages */
+    unsigned size;          /* buffer size, zero if not allocated yet */
+    unsigned want;          /* requested buffer size, default is GZBUFSIZE */
+    unsigned char *in;      /* input buffer (double-sized when writing) */
+    unsigned char *out;     /* output buffer (double-sized when reading) */
+    int direct;             /* 0 if processing gzip, 1 if transparent */
+        /* just for reading */
+    int how;                /* 0: get header, 1: copy, 2: decompress */
+    z_off64_t start;        /* where the gzip data started, for rewinding */
+    int eof;                /* true if end of input file reached */
+    int past;               /* true if read requested past end */
+        /* just for writing */
+    int level;              /* compression level */
+    int strategy;           /* compression strategy */
+        /* seek request */
+    z_off64_t skip;         /* amount to skip (already rewound if backwards) */
+    int seek;               /* true if seek request pending */
+        /* error information */
+    int err;                /* error code */
+    char *msg;              /* error message */
+        /* zlib inflate or deflate stream */
+    z_stream strm;          /* stream structure in-place (not a pointer) */
+} gz_state;
+typedef gz_state FAR *gz_statep;
+
+/* shared functions */
+void ZLIB_INTERNAL gz_error OF((gz_statep, int, const char *));
+#if defined UNDER_CE
+char ZLIB_INTERNAL *gz_strwinerror OF((DWORD error));
+#endif
+
+/* GT_OFF(x), where x is an unsigned value, is true if x > maximum z_off64_t
+   value -- needed when comparing unsigned to z_off64_t, which is signed
+   (possible z_off64_t types off_t, off64_t, and long are all signed) */
+#ifdef INT_MAX
+#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > INT_MAX)
+#else
+unsigned ZLIB_INTERNAL gz_intmax OF((void));
+#  define GT_OFF(x) (sizeof(int) == sizeof(z_off64_t) && (x) > gz_intmax())
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/gzlib.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,661 @@
+/*
+ * 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.
+ */
+
+/* gzlib.c -- zlib functions common to reading and writing gzip files
+ * Copyright (C) 2004-2017 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "gzguts.h"
+
+#if defined(_WIN32) && !defined(__BORLANDC__) && !defined(__MINGW32__)
+#  define LSEEK _lseeki64
+#else
+#if defined(_LARGEFILE64_SOURCE) && _LFS64_LARGEFILE-0
+#  define LSEEK lseek64
+#else
+#  define LSEEK lseek
+#endif
+#endif
+
+/* Local functions */
+local void gz_reset OF((gz_statep));
+local gzFile gz_open OF((const void *, int, const char *));
+
+#if defined UNDER_CE
+
+/* Map the Windows error number in ERROR to a locale-dependent error message
+   string and return a pointer to it.  Typically, the values for ERROR come
+   from GetLastError.
+
+   The string pointed to shall not be modified by the application, but may be
+   overwritten by a subsequent call to gz_strwinerror
+
+   The gz_strwinerror function does not change the current setting of
+   GetLastError. */
+char ZLIB_INTERNAL *gz_strwinerror (error)
+     DWORD error;
+{
+    static char buf[1024];
+
+    wchar_t *msgbuf;
+    DWORD lasterr = GetLastError();
+    DWORD chars = FormatMessage(FORMAT_MESSAGE_FROM_SYSTEM
+        | FORMAT_MESSAGE_ALLOCATE_BUFFER,
+        NULL,
+        error,
+        0, /* Default language */
+        (LPVOID)&msgbuf,
+        0,
+        NULL);
+    if (chars != 0) {
+        /* If there is an \r\n appended, zap it.  */
+        if (chars >= 2
+            && msgbuf[chars - 2] == '\r' && msgbuf[chars - 1] == '\n') {
+            chars -= 2;
+            msgbuf[chars] = 0;
+        }
+
+        if (chars > sizeof (buf) - 1) {
+            chars = sizeof (buf) - 1;
+            msgbuf[chars] = 0;
+        }
+
+        wcstombs(buf, msgbuf, chars + 1);
+        LocalFree(msgbuf);
+    }
+    else {
+        sprintf(buf, "unknown win32 error (%ld)", error);
+    }
+
+    SetLastError(lasterr);
+    return buf;
+}
+
+#endif /* UNDER_CE */
+
+/* Reset gzip file state */
+local void gz_reset(state)
+    gz_statep state;
+{
+    state->x.have = 0;              /* no output data available */
+    if (state->mode == GZ_READ) {   /* for reading ... */
+        state->eof = 0;             /* not at end of file */
+        state->past = 0;            /* have not read past end yet */
+        state->how = LOOK;          /* look for gzip header */
+    }
+    state->seek = 0;                /* no seek request pending */
+    gz_error(state, Z_OK, NULL);    /* clear error */
+    state->x.pos = 0;               /* no uncompressed data yet */
+    state->strm.avail_in = 0;       /* no input data yet */
+}
+
+/* Open a gzip file either by name or file descriptor. */
+local gzFile gz_open(path, fd, mode)
+    const void *path;
+    int fd;
+    const char *mode;
+{
+    gz_statep state;
+    z_size_t len;
+    int oflag;
+#ifdef O_CLOEXEC
+    int cloexec = 0;
+#endif
+#ifdef O_EXCL
+    int exclusive = 0;
+#endif
+
+    /* check input */
+    if (path == NULL)
+        return NULL;
+
+    /* allocate gzFile structure to return */
+    state = (gz_statep)malloc(sizeof(gz_state));
+    if (state == NULL)
+        return NULL;
+    state->size = 0;            /* no buffers allocated yet */
+    state->want = GZBUFSIZE;    /* requested buffer size */
+    state->msg = NULL;          /* no error message yet */
+
+    /* interpret mode */
+    state->mode = GZ_NONE;
+    state->level = Z_DEFAULT_COMPRESSION;
+    state->strategy = Z_DEFAULT_STRATEGY;
+    state->direct = 0;
+    while (*mode) {
+        if (*mode >= '0' && *mode <= '9')
+            state->level = *mode - '0';
+        else
+            switch (*mode) {
+            case 'r':
+                state->mode = GZ_READ;
+                break;
+#ifndef NO_GZCOMPRESS
+            case 'w':
+                state->mode = GZ_WRITE;
+                break;
+            case 'a':
+                state->mode = GZ_APPEND;
+                break;
+#endif
+            case '+':       /* can't read and write at the same time */
+                free(state);
+                return NULL;
+            case 'b':       /* ignore -- will request binary anyway */
+                break;
+#ifdef O_CLOEXEC
+            case 'e':
+                cloexec = 1;
+                break;
+#endif
+#ifdef O_EXCL
+            case 'x':
+                exclusive = 1;
+                break;
+#endif
+            case 'f':
+                state->strategy = Z_FILTERED;
+                break;
+            case 'h':
+                state->strategy = Z_HUFFMAN_ONLY;
+                break;
+            case 'R':
+                state->strategy = Z_RLE;
+                break;
+            case 'F':
+                state->strategy = Z_FIXED;
+                break;
+            case 'T':
+                state->direct = 1;
+                break;
+            default:        /* could consider as an error, but just ignore */
+                ;
+            }
+        mode++;
+    }
+
+    /* must provide an "r", "w", or "a" */
+    if (state->mode == GZ_NONE) {
+        free(state);
+        return NULL;
+    }
+
+    /* can't force transparent read */
+    if (state->mode == GZ_READ) {
+        if (state->direct) {
+            free(state);
+            return NULL;
+        }
+        state->direct = 1;      /* for empty file */
+    }
+
+    /* save the path name for error messages */
+#ifdef WIDECHAR
+    if (fd == -2) {
+        len = wcstombs(NULL, path, 0);
+        if (len == (z_size_t)-1)
+            len = 0;
+    }
+    else
+#endif
+        len = strlen((const char *)path);
+    state->path = (char *)malloc(len + 1);
+    if (state->path == NULL) {
+        free(state);
+        return NULL;
+    }
+#ifdef WIDECHAR
+    if (fd == -2)
+        if (len)
+            wcstombs(state->path, path, len + 1);
+        else
+            *(state->path) = 0;
+    else
+#endif
+#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
+        (void)snprintf(state->path, len + 1, "%s", (const char *)path);
+#else
+        strcpy(state->path, path);
+#endif
+
+    /* compute the flags for open() */
+    oflag =
+#ifdef O_LARGEFILE
+        O_LARGEFILE |
+#endif
+#ifdef O_BINARY
+        O_BINARY |
+#endif
+#ifdef O_CLOEXEC
+        (cloexec ? O_CLOEXEC : 0) |
+#endif
+        (state->mode == GZ_READ ?
+         O_RDONLY :
+         (O_WRONLY | O_CREAT |
+#ifdef O_EXCL
+          (exclusive ? O_EXCL : 0) |
+#endif
+          (state->mode == GZ_WRITE ?
+           O_TRUNC :
+           O_APPEND)));
+
+    /* open the file with the appropriate flags (or just use fd) */
+    state->fd = fd > -1 ? fd : (
+#ifdef WIDECHAR
+        fd == -2 ? _wopen(path, oflag, 0666) :
+#endif
+        open((const char *)path, oflag, 0666));
+    if (state->fd == -1) {
+        free(state->path);
+        free(state);
+        return NULL;
+    }
+    if (state->mode == GZ_APPEND) {
+        LSEEK(state->fd, 0, SEEK_END);  /* so gzoffset() is correct */
+        state->mode = GZ_WRITE;         /* simplify later checks */
+    }
+
+    /* save the current position for rewinding (only if reading) */
+    if (state->mode == GZ_READ) {
+        state->start = LSEEK(state->fd, 0, SEEK_CUR);
+        if (state->start == -1) state->start = 0;
+    }
+
+    /* initialize stream */
+    gz_reset(state);
+
+    /* return stream */
+    return (gzFile)state;
+}
+
+/* -- see zlib.h -- */
+gzFile ZEXPORT gzopen(path, mode)
+    const char *path;
+    const char *mode;
+{
+    return gz_open(path, -1, mode);
+}
+
+/* -- see zlib.h -- */
+gzFile ZEXPORT gzopen64(path, mode)
+    const char *path;
+    const char *mode;
+{
+    return gz_open(path, -1, mode);
+}
+
+/* -- see zlib.h -- */
+gzFile ZEXPORT gzdopen(fd, mode)
+    int fd;
+    const char *mode;
+{
+    char *path;         /* identifier for error messages */
+    gzFile gz;
+
+    if (fd == -1 || (path = (char *)malloc(7 + 3 * sizeof(int))) == NULL)
+        return NULL;
+#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
+    (void)snprintf(path, 7 + 3 * sizeof(int), "<fd:%d>", fd);
+#else
+    sprintf(path, "<fd:%d>", fd);   /* for debugging */
+#endif
+    gz = gz_open(path, fd, mode);
+    free(path);
+    return gz;
+}
+
+/* -- see zlib.h -- */
+#ifdef WIDECHAR
+gzFile ZEXPORT gzopen_w(path, mode)
+    const wchar_t *path;
+    const char *mode;
+{
+    return gz_open(path, -2, mode);
+}
+#endif
+
+/* -- see zlib.h -- */
+int ZEXPORT gzbuffer(file, size)
+    gzFile file;
+    unsigned size;
+{
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return -1;
+
+    /* make sure we haven't already allocated memory */
+    if (state->size != 0)
+        return -1;
+
+    /* check and set requested size */
+    if ((size << 1) < size)
+        return -1;              /* need to be able to double it */
+    if (size < 2)
+        size = 2;               /* need two bytes to check magic header */
+    state->want = size;
+    return 0;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzrewind(file)
+    gzFile file;
+{
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+
+    /* check that we're reading and that there's no error */
+    if (state->mode != GZ_READ ||
+            (state->err != Z_OK && state->err != Z_BUF_ERROR))
+        return -1;
+
+    /* back up and start over */
+    if (LSEEK(state->fd, state->start, SEEK_SET) == -1)
+        return -1;
+    gz_reset(state);
+    return 0;
+}
+
+/* -- see zlib.h -- */
+z_off64_t ZEXPORT gzseek64(file, offset, whence)
+    gzFile file;
+    z_off64_t offset;
+    int whence;
+{
+    unsigned n;
+    z_off64_t ret;
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return -1;
+
+    /* check that there's no error */
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR)
+        return -1;
+
+    /* can only seek from start or relative to current position */
+    if (whence != SEEK_SET && whence != SEEK_CUR)
+        return -1;
+
+    /* normalize offset to a SEEK_CUR specification */
+    if (whence == SEEK_SET)
+        offset -= state->x.pos;
+    else if (state->seek)
+        offset += state->skip;
+    state->seek = 0;
+
+    /* if within raw area while reading, just go there */
+    if (state->mode == GZ_READ && state->how == COPY &&
+            state->x.pos + offset >= 0) {
+        ret = LSEEK(state->fd, offset - state->x.have, SEEK_CUR);
+        if (ret == -1)
+            return -1;
+        state->x.have = 0;
+        state->eof = 0;
+        state->past = 0;
+        state->seek = 0;
+        gz_error(state, Z_OK, NULL);
+        state->strm.avail_in = 0;
+        state->x.pos += offset;
+        return state->x.pos;
+    }
+
+    /* calculate skip amount, rewinding if needed for back seek when reading */
+    if (offset < 0) {
+        if (state->mode != GZ_READ)         /* writing -- can't go backwards */
+            return -1;
+        offset += state->x.pos;
+        if (offset < 0)                     /* before start of file! */
+            return -1;
+        if (gzrewind(file) == -1)           /* rewind, then skip to offset */
+            return -1;
+    }
+
+    /* if reading, skip what's in output buffer (one less gzgetc() check) */
+    if (state->mode == GZ_READ) {
+        n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > offset ?
+            (unsigned)offset : state->x.have;
+        state->x.have -= n;
+        state->x.next += n;
+        state->x.pos += n;
+        offset -= n;
+    }
+
+    /* request skip (if not zero) */
+    if (offset) {
+        state->seek = 1;
+        state->skip = offset;
+    }
+    return state->x.pos + offset;
+}
+
+/* -- see zlib.h -- */
+z_off_t ZEXPORT gzseek(file, offset, whence)
+    gzFile file;
+    z_off_t offset;
+    int whence;
+{
+    z_off64_t ret;
+
+    ret = gzseek64(file, (z_off64_t)offset, whence);
+    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
+}
+
+/* -- see zlib.h -- */
+z_off64_t ZEXPORT gztell64(file)
+    gzFile file;
+{
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return -1;
+
+    /* return position */
+    return state->x.pos + (state->seek ? state->skip : 0);
+}
+
+/* -- see zlib.h -- */
+z_off_t ZEXPORT gztell(file)
+    gzFile file;
+{
+    z_off64_t ret;
+
+    ret = gztell64(file);
+    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
+}
+
+/* -- see zlib.h -- */
+z_off64_t ZEXPORT gzoffset64(file)
+    gzFile file;
+{
+    z_off64_t offset;
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return -1;
+
+    /* compute and return effective offset in file */
+    offset = LSEEK(state->fd, 0, SEEK_CUR);
+    if (offset == -1)
+        return -1;
+    if (state->mode == GZ_READ)             /* reading */
+        offset -= state->strm.avail_in;     /* don't count buffered input */
+    return offset;
+}
+
+/* -- see zlib.h -- */
+z_off_t ZEXPORT gzoffset(file)
+    gzFile file;
+{
+    z_off64_t ret;
+
+    ret = gzoffset64(file);
+    return ret == (z_off_t)ret ? (z_off_t)ret : -1;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzeof(file)
+    gzFile file;
+{
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return 0;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return 0;
+
+    /* return end-of-file state */
+    return state->mode == GZ_READ ? state->past : 0;
+}
+
+/* -- see zlib.h -- */
+const char * ZEXPORT gzerror(file, errnum)
+    gzFile file;
+    int *errnum;
+{
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return NULL;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return NULL;
+
+    /* return error information */
+    if (errnum != NULL)
+        *errnum = state->err;
+    return state->err == Z_MEM_ERROR ? "out of memory" :
+                                       (state->msg == NULL ? "" : state->msg);
+}
+
+/* -- see zlib.h -- */
+void ZEXPORT gzclearerr(file)
+    gzFile file;
+{
+    gz_statep state;
+
+    /* get internal structure and check integrity */
+    if (file == NULL)
+        return;
+    state = (gz_statep)file;
+    if (state->mode != GZ_READ && state->mode != GZ_WRITE)
+        return;
+
+    /* clear error and end-of-file */
+    if (state->mode == GZ_READ) {
+        state->eof = 0;
+        state->past = 0;
+    }
+    gz_error(state, Z_OK, NULL);
+}
+
+/* Create an error message in allocated memory and set state->err and
+   state->msg accordingly.  Free any previous error message already there.  Do
+   not try to free or allocate space if the error is Z_MEM_ERROR (out of
+   memory).  Simply save the error message as a static string.  If there is an
+   allocation failure constructing the error message, then convert the error to
+   out of memory. */
+void ZLIB_INTERNAL gz_error(state, err, msg)
+    gz_statep state;
+    int err;
+    const char *msg;
+{
+    /* free previously allocated message and clear */
+    if (state->msg != NULL) {
+        if (state->err != Z_MEM_ERROR)
+            free(state->msg);
+        state->msg = NULL;
+    }
+
+    /* if fatal, set state->x.have to 0 so that the gzgetc() macro fails */
+    if (err != Z_OK && err != Z_BUF_ERROR)
+        state->x.have = 0;
+
+    /* set error code, and if no message, then done */
+    state->err = err;
+    if (msg == NULL)
+        return;
+
+    /* for an out of memory error, return literal string when requested */
+    if (err == Z_MEM_ERROR)
+        return;
+
+    /* construct error message with path */
+    if ((state->msg = (char *)malloc(strlen(state->path) + strlen(msg) + 3)) ==
+            NULL) {
+        state->err = Z_MEM_ERROR;
+        return;
+    }
+#if !defined(NO_snprintf) && !defined(NO_vsnprintf)
+    (void)snprintf(state->msg, strlen(state->path) + strlen(msg) + 3,
+                   "%s%s%s", state->path, ": ", msg);
+#else
+    strcpy(state->msg, state->path);
+    strcat(state->msg, ": ");
+    strcat(state->msg, msg);
+#endif
+}
+
+#ifndef INT_MAX
+/* portably return maximum value for an int (when limits.h presumed not
+   available) -- we need to do this to cover cases where 2's complement not
+   used, since C standard permits 1's complement and sign-bit representations,
+   otherwise we could just use ((unsigned)-1) >> 1 */
+unsigned ZLIB_INTERNAL gz_intmax()
+{
+    unsigned p, q;
+
+    p = 1;
+    do {
+        q = p;
+        p <<= 1;
+        p++;
+    } while (p > q);
+    return q >> 1;
+}
+#endif
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/gzread.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,678 @@
+/*
+ * 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.
+ */
+
+/* gzread.c -- zlib functions for reading gzip files
+ * Copyright (C) 2004, 2005, 2010, 2011, 2012, 2013, 2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "gzguts.h"
+
+/* Local functions */
+local int gz_load OF((gz_statep, unsigned char *, unsigned, unsigned *));
+local int gz_avail OF((gz_statep));
+local int gz_look OF((gz_statep));
+local int gz_decomp OF((gz_statep));
+local int gz_fetch OF((gz_statep));
+local int gz_skip OF((gz_statep, z_off64_t));
+local z_size_t gz_read OF((gz_statep, voidp, z_size_t));
+
+/* Use read() to load a buffer -- return -1 on error, otherwise 0.  Read from
+   state->fd, and update state->eof, state->err, and state->msg as appropriate.
+   This function needs to loop on read(), since read() is not guaranteed to
+   read the number of bytes requested, depending on the type of descriptor. */
+local int gz_load(state, buf, len, have)
+    gz_statep state;
+    unsigned char *buf;
+    unsigned len;
+    unsigned *have;
+{
+    int ret;
+    unsigned get, max = ((unsigned)-1 >> 2) + 1;
+
+    *have = 0;
+    do {
+        get = len - *have;
+        if (get > max)
+            get = max;
+        ret = read(state->fd, buf + *have, get);
+        if (ret <= 0)
+            break;
+        *have += (unsigned)ret;
+    } while (*have < len);
+    if (ret < 0) {
+        gz_error(state, Z_ERRNO, zstrerror());
+        return -1;
+    }
+    if (ret == 0)
+        state->eof = 1;
+    return 0;
+}
+
+/* Load up input buffer and set eof flag if last data loaded -- return -1 on
+   error, 0 otherwise.  Note that the eof flag is set when the end of the input
+   file is reached, even though there may be unused data in the buffer.  Once
+   that data has been used, no more attempts will be made to read the file.
+   If strm->avail_in != 0, then the current data is moved to the beginning of
+   the input buffer, and then the remainder of the buffer is loaded with the
+   available data from the input file. */
+local int gz_avail(state)
+    gz_statep state;
+{
+    unsigned got;
+    z_streamp strm = &(state->strm);
+
+    if (state->err != Z_OK && state->err != Z_BUF_ERROR)
+        return -1;
+    if (state->eof == 0) {
+        if (strm->avail_in) {       /* copy what's there to the start */
+            unsigned char *p = state->in;
+            unsigned const char *q = strm->next_in;
+            unsigned n = strm->avail_in;
+            do {
+                *p++ = *q++;
+            } while (--n);
+        }
+        if (gz_load(state, state->in + strm->avail_in,
+                    state->size - strm->avail_in, &got) == -1)
+            return -1;
+        strm->avail_in += got;
+        strm->next_in = state->in;
+    }
+    return 0;
+}
+
+/* Look for gzip header, set up for inflate or copy.  state->x.have must be 0.
+   If this is the first time in, allocate required memory.  state->how will be
+   left unchanged if there is no more input data available, will be set to COPY
+   if there is no gzip header and direct copying will be performed, or it will
+   be set to GZIP for decompression.  If direct copying, then leftover input
+   data from the input buffer will be copied to the output buffer.  In that
+   case, all further file reads will be directly to either the output buffer or
+   a user buffer.  If decompressing, the inflate state will be initialized.
+   gz_look() will return 0 on success or -1 on failure. */
+local int gz_look(state)
+    gz_statep state;
+{
+    z_streamp strm = &(state->strm);
+
+    /* allocate read buffers and inflate memory */
+    if (state->size == 0) {
+        /* allocate buffers */
+        state->in = (unsigned char *)malloc(state->want);
+        state->out = (unsigned char *)malloc(state->want << 1);
+        if (state->in == NULL || state->out == NULL) {
+            free(state->out);
+            free(state->in);
+            gz_error(state, Z_MEM_ERROR, "out of memory");
+            return -1;
+        }
+        state->size = state->want;
+
+        /* allocate inflate memory */
+        state->strm.zalloc = Z_NULL;
+        state->strm.zfree = Z_NULL;
+        state->strm.opaque = Z_NULL;
+        state->strm.avail_in = 0;
+        state->strm.next_in = Z_NULL;
+        if (inflateInit2(&(state->strm), 15 + 16) != Z_OK) {    /* gunzip */
+            free(state->out);
+            free(state->in);
+            state->size = 0;
+            gz_error(state, Z_MEM_ERROR, "out of memory");
+            return -1;
+        }
+    }
+
+    /* get at least the magic bytes in the input buffer */
+    if (strm->avail_in < 2) {
+        if (gz_avail(state) == -1)
+            return -1;
+        if (strm->avail_in == 0)
+            return 0;
+    }
+
+    /* look for gzip magic bytes -- if there, do gzip decoding (note: there is
+       a logical dilemma here when considering the case of a partially written
+       gzip file, to wit, if a single 31 byte is written, then we cannot tell
+       whether this is a single-byte file, or just a partially written gzip
+       file -- for here we assume that if a gzip file is being written, then
+       the header will be written in a single operation, so that reading a
+       single byte is sufficient indication that it is not a gzip file) */
+    if (strm->avail_in > 1 &&
+            strm->next_in[0] == 31 && strm->next_in[1] == 139) {
+        inflateReset(strm);
+        state->how = GZIP;
+        state->direct = 0;
+        return 0;
+    }
+
+    /* no gzip header -- if we were decoding gzip before, then this is trailing
+       garbage.  Ignore the trailing garbage and finish. */
+    if (state->direct == 0) {
+        strm->avail_in = 0;
+        state->eof = 1;
+        state->x.have = 0;
+        return 0;
+    }
+
+    /* doing raw i/o, copy any leftover input to output -- this assumes that
+       the output buffer is larger than the input buffer, which also assures
+       space for gzungetc() */
+    state->x.next = state->out;
+    if (strm->avail_in) {
+        memcpy(state->x.next, strm->next_in, strm->avail_in);
+        state->x.have = strm->avail_in;
+        strm->avail_in = 0;
+    }
+    state->how = COPY;
+    state->direct = 1;
+    return 0;
+}
+
+/* Decompress from input to the provided next_out and avail_out in the state.
+   On return, state->x.have and state->x.next point to the just decompressed
+   data.  If the gzip stream completes, state->how is reset to LOOK to look for
+   the next gzip stream or raw data, once state->x.have is depleted.  Returns 0
+   on success, -1 on failure. */
+local int gz_decomp(state)
+    gz_statep state;
+{
+    int ret = Z_OK;
+    unsigned had;
+    z_streamp strm = &(state->strm);
+
+    /* fill output buffer up to end of deflate stream */
+    had = strm->avail_out;
+    do {
+        /* get more input for inflate() */
+        if (strm->avail_in == 0 && gz_avail(state) == -1)
+            return -1;
+        if (strm->avail_in == 0) {
+            gz_error(state, Z_BUF_ERROR, "unexpected end of file");
+            break;
+        }
+
+        /* decompress and handle errors */
+        ret = inflate(strm, Z_NO_FLUSH);
+        if (ret == Z_STREAM_ERROR || ret == Z_NEED_DICT) {
+            gz_error(state, Z_STREAM_ERROR,
+                     "internal error: inflate stream corrupt");
+            return -1;
+        }
+        if (ret == Z_MEM_ERROR) {
+            gz_error(state, Z_MEM_ERROR, "out of memory");
+            return -1;
+        }
+        if (ret == Z_DATA_ERROR) {              /* deflate stream invalid */
+            gz_error(state, Z_DATA_ERROR,
+                     strm->msg == NULL ? "compressed data error" : strm->msg);
+            return -1;
+        }
+    } while (strm->avail_out && ret != Z_STREAM_END);
+
+    /* update available output */
+    state->x.have = had - strm->avail_out;
+    state->x.next = strm->next_out - state->x.have;
+
+    /* if the gzip stream completed successfully, look for another */
+    if (ret == Z_STREAM_END)
+        state->how = LOOK;
+
+    /* good decompression */
+    return 0;
+}
+
+/* Fetch data and put it in the output buffer.  Assumes state->x.have is 0.
+   Data is either copied from the input file or decompressed from the input
+   file depending on state->how.  If state->how is LOOK, then a gzip header is
+   looked for to determine whether to copy or decompress.  Returns -1 on error,
+   otherwise 0.  gz_fetch() will leave state->how as COPY or GZIP unless the
+   end of the input file has been reached and all data has been processed.  */
+local int gz_fetch(state)
+    gz_statep state;
+{
+    z_streamp strm = &(state->strm);
+
+    do {
+        switch(state->how) {
+        case LOOK:      /* -> LOOK, COPY (only if never GZIP), or GZIP */
+            if (gz_look(state) == -1)
+                return -1;
+            if (state->how == LOOK)
+                return 0;
+            break;
+        case COPY:      /* -> COPY */
+            if (gz_load(state, state->out, state->size << 1, &(state->x.have))
+                    == -1)
+                return -1;
+            state->x.next = state->out;
+            return 0;
+        case GZIP:      /* -> GZIP or LOOK (if end of gzip stream) */
+            strm->avail_out = state->size << 1;
+            strm->next_out = state->out;
+            if (gz_decomp(state) == -1)
+                return -1;
+        }
+    } while (state->x.have == 0 && (!state->eof || strm->avail_in));
+    return 0;
+}
+
+/* Skip len uncompressed bytes of output.  Return -1 on error, 0 on success. */
+local int gz_skip(state, len)
+    gz_statep state;
+    z_off64_t len;
+{
+    unsigned n;
+
+    /* skip over len bytes or reach end-of-file, whichever comes first */
+    while (len)
+        /* skip over whatever is in output buffer */
+        if (state->x.have) {
+            n = GT_OFF(state->x.have) || (z_off64_t)state->x.have > len ?
+                (unsigned)len : state->x.have;
+            state->x.have -= n;
+            state->x.next += n;
+            state->x.pos += n;
+            len -= n;
+        }
+
+        /* output buffer empty -- return if we're at the end of the input */
+        else if (state->eof && state->strm.avail_in == 0)
+            break;
+
+        /* need more data to skip -- load up output buffer */
+        else {
+            /* get more output, looking for header if required */
+            if (gz_fetch(state) == -1)
+                return -1;
+        }
+    return 0;
+}
+
+/* Read len bytes into buf from file, or less than len up to the end of the
+   input.  Return the number of bytes read.  If zero is returned, either the
+   end of file was reached, or there was an error.  state->err must be
+   consulted in that case to determine which. */
+local z_size_t gz_read(state, buf, len)
+    gz_statep state;
+    voidp buf;
+    z_size_t len;
+{
+    z_size_t got;
+    unsigned n;
+
+    /* if len is zero, avoid unnecessary operations */
+    if (len == 0)
+        return 0;
+
+    /* process a skip request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_skip(state, state->skip) == -1)
+            return 0;
+    }
+
+    /* get len bytes to buf, or less than len if at the end */
+    got = 0;
+    do {
+        /* set n to the maximum amount of len that fits in an unsigned int */
+        n = -1;
+        if (n > len)
+            n = (unsigned)len;
+
+        /* first just try copying data from the output buffer */
+        if (state->x.have) {
+            if (state->x.have < n)
+                n = state->x.have;
+            memcpy(buf, state->x.next, n);
+            state->x.next += n;
+            state->x.have -= n;
+        }
+
+        /* output buffer empty -- return if we're at the end of the input */
+        else if (state->eof && state->strm.avail_in == 0) {
+            state->past = 1;        /* tried to read past end */
+            break;
+        }
+
+        /* need output data -- for small len or new stream load up our output
+           buffer */
+        else if (state->how == LOOK || n < (state->size << 1)) {
+            /* get more output, looking for header if required */
+            if (gz_fetch(state) == -1)
+                return 0;
+            continue;       /* no progress yet -- go back to copy above */
+            /* the copy above assures that we will leave with space in the
+               output buffer, allowing at least one gzungetc() to succeed */
+        }
+
+        /* large len -- read directly into user buffer */
+        else if (state->how == COPY) {      /* read directly */
+            if (gz_load(state, (unsigned char *)buf, n, &n) == -1)
+                return 0;
+        }
+
+        /* large len -- decompress directly into user buffer */
+        else {  /* state->how == GZIP */
+            state->strm.avail_out = n;
+            state->strm.next_out = (unsigned char *)buf;
+            if (gz_decomp(state) == -1)
+                return 0;
+            n = state->x.have;
+            state->x.have = 0;
+        }
+
+        /* update progress */
+        len -= n;
+        buf = (char *)buf + n;
+        got += n;
+        state->x.pos += n;
+    } while (len);
+
+    /* return number of bytes read into user buffer */
+    return got;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzread(file, buf, len)
+    gzFile file;
+    voidp buf;
+    unsigned len;
+{
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+
+    /* check that we're reading and that there's no (serious) error */
+    if (state->mode != GZ_READ ||
+            (state->err != Z_OK && state->err != Z_BUF_ERROR))
+        return -1;
+
+    /* since an int is returned, make sure len fits in one, otherwise return
+       with an error (this avoids a flaw in the interface) */
+    if ((int)len < 0) {
+        gz_error(state, Z_STREAM_ERROR, "request does not fit in an int");
+        return -1;
+    }
+
+    /* read len or fewer bytes to buf */
+    len = (unsigned)gz_read(state, buf, len);
+
+    /* check for an error */
+    if (len == 0 && state->err != Z_OK && state->err != Z_BUF_ERROR)
+        return -1;
+
+    /* return the number of bytes read (this is assured to fit in an int) */
+    return (int)len;
+}
+
+/* -- see zlib.h -- */
+z_size_t ZEXPORT gzfread(buf, size, nitems, file)
+    voidp buf;
+    z_size_t size;
+    z_size_t nitems;
+    gzFile file;
+{
+    z_size_t len;
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return 0;
+    state = (gz_statep)file;
+
+    /* check that we're reading and that there's no (serious) error */
+    if (state->mode != GZ_READ ||
+            (state->err != Z_OK && state->err != Z_BUF_ERROR))
+        return 0;
+
+    /* compute bytes to read -- error on overflow */
+    len = nitems * size;
+    if (size && len / size != nitems) {
+        gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t");
+        return 0;
+    }
+
+    /* read len or fewer bytes to buf, return the number of full items read */
+    return len ? gz_read(state, buf, len) / size : 0;
+}
+
+/* -- see zlib.h -- */
+#ifdef Z_PREFIX_SET
+#  undef z_gzgetc
+#else
+#  undef gzgetc
+#endif
+int ZEXPORT gzgetc(file)
+    gzFile file;
+{
+    int ret;
+    unsigned char buf[1];
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+
+    /* check that we're reading and that there's no (serious) error */
+    if (state->mode != GZ_READ ||
+        (state->err != Z_OK && state->err != Z_BUF_ERROR))
+        return -1;
+
+    /* try output buffer (no need to check for skip request) */
+    if (state->x.have) {
+        state->x.have--;
+        state->x.pos++;
+        return *(state->x.next)++;
+    }
+
+    /* nothing there -- try gz_read() */
+    ret = (int)gz_read(state, buf, 1);
+    return ret < 1 ? -1 : buf[0];
+}
+
+int ZEXPORT gzgetc_(file)
+gzFile file;
+{
+    return gzgetc(file);
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzungetc(c, file)
+    int c;
+    gzFile file;
+{
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+
+    /* check that we're reading and that there's no (serious) error */
+    if (state->mode != GZ_READ ||
+        (state->err != Z_OK && state->err != Z_BUF_ERROR))
+        return -1;
+
+    /* process a skip request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_skip(state, state->skip) == -1)
+            return -1;
+    }
+
+    /* can't push EOF */
+    if (c < 0)
+        return -1;
+
+    /* if output buffer empty, put byte at end (allows more pushing) */
+    if (state->x.have == 0) {
+        state->x.have = 1;
+        state->x.next = state->out + (state->size << 1) - 1;
+        state->x.next[0] = (unsigned char)c;
+        state->x.pos--;
+        state->past = 0;
+        return c;
+    }
+
+    /* if no room, give up (must have already done a gzungetc()) */
+    if (state->x.have == (state->size << 1)) {
+        gz_error(state, Z_DATA_ERROR, "out of room to push characters");
+        return -1;
+    }
+
+    /* slide output data if needed and insert byte before existing data */
+    if (state->x.next == state->out) {
+        unsigned char *src = state->out + state->x.have;
+        unsigned char *dest = state->out + (state->size << 1);
+        while (src > state->out)
+            *--dest = *--src;
+        state->x.next = dest;
+    }
+    state->x.have++;
+    state->x.next--;
+    state->x.next[0] = (unsigned char)c;
+    state->x.pos--;
+    state->past = 0;
+    return c;
+}
+
+/* -- see zlib.h -- */
+char * ZEXPORT gzgets(file, buf, len)
+    gzFile file;
+    char *buf;
+    int len;
+{
+    unsigned left, n;
+    char *str;
+    unsigned char *eol;
+    gz_statep state;
+
+    /* check parameters and get internal structure */
+    if (file == NULL || buf == NULL || len < 1)
+        return NULL;
+    state = (gz_statep)file;
+
+    /* check that we're reading and that there's no (serious) error */
+    if (state->mode != GZ_READ ||
+        (state->err != Z_OK && state->err != Z_BUF_ERROR))
+        return NULL;
+
+    /* process a skip request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_skip(state, state->skip) == -1)
+            return NULL;
+    }
+
+    /* copy output bytes up to new line or len - 1, whichever comes first --
+       append a terminating zero to the string (we don't check for a zero in
+       the contents, let the user worry about that) */
+    str = buf;
+    left = (unsigned)len - 1;
+    if (left) do {
+        /* assure that something is in the output buffer */
+        if (state->x.have == 0 && gz_fetch(state) == -1)
+            return NULL;                /* error */
+        if (state->x.have == 0) {       /* end of file */
+            state->past = 1;            /* read past end */
+            break;                      /* return what we have */
+        }
+
+        /* look for end-of-line in current output buffer */
+        n = state->x.have > left ? left : state->x.have;
+        eol = (unsigned char *)memchr(state->x.next, '\n', n);
+        if (eol != NULL)
+            n = (unsigned)(eol - state->x.next) + 1;
+
+        /* copy through end-of-line, or remainder if not found */
+        memcpy(buf, state->x.next, n);
+        state->x.have -= n;
+        state->x.next += n;
+        state->x.pos += n;
+        left -= n;
+        buf += n;
+    } while (left && eol == NULL);
+
+    /* return terminated string, or if nothing, end of file */
+    if (buf == str)
+        return NULL;
+    buf[0] = 0;
+    return str;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzdirect(file)
+    gzFile file;
+{
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return 0;
+    state = (gz_statep)file;
+
+    /* if the state is not known, but we can find out, then do so (this is
+       mainly for right after a gzopen() or gzdopen()) */
+    if (state->mode == GZ_READ && state->how == LOOK && state->x.have == 0)
+        (void)gz_look(state);
+
+    /* return 1 if transparent, 0 if processing a gzip stream */
+    return state->direct;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzclose_r(file)
+    gzFile file;
+{
+    int ret, err;
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return Z_STREAM_ERROR;
+    state = (gz_statep)file;
+
+    /* check that we're reading */
+    if (state->mode != GZ_READ)
+        return Z_STREAM_ERROR;
+
+    /* free memory and close file */
+    if (state->size) {
+        inflateEnd(&(state->strm));
+        free(state->out);
+        free(state->in);
+    }
+    err = state->err == Z_BUF_ERROR ? Z_BUF_ERROR : Z_OK;
+    gz_error(state, Z_OK, NULL);
+    free(state->path);
+    ret = close(state->fd);
+    free(state);
+    return ret ? Z_ERRNO : err;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/gzwrite.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,689 @@
+/*
+ * 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.
+ */
+
+/* gzwrite.c -- zlib functions for writing gzip files
+ * Copyright (C) 2004-2017 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "gzguts.h"
+
+/* Local functions */
+local int gz_init OF((gz_statep));
+local int gz_comp OF((gz_statep, int));
+local int gz_zero OF((gz_statep, z_off64_t));
+local z_size_t gz_write OF((gz_statep, voidpc, z_size_t));
+
+/* Initialize state for writing a gzip file.  Mark initialization by setting
+   state->size to non-zero.  Return -1 on a memory allocation failure, or 0 on
+   success. */
+local int gz_init(state)
+    gz_statep state;
+{
+    int ret;
+    z_streamp strm = &(state->strm);
+
+    /* allocate input buffer (double size for gzprintf) */
+    state->in = (unsigned char *)malloc(state->want << 1);
+    if (state->in == NULL) {
+        gz_error(state, Z_MEM_ERROR, "out of memory");
+        return -1;
+    }
+
+    /* only need output buffer and deflate state if compressing */
+    if (!state->direct) {
+        /* allocate output buffer */
+        state->out = (unsigned char *)malloc(state->want);
+        if (state->out == NULL) {
+            free(state->in);
+            gz_error(state, Z_MEM_ERROR, "out of memory");
+            return -1;
+        }
+
+        /* allocate deflate memory, set up for gzip compression */
+        strm->zalloc = Z_NULL;
+        strm->zfree = Z_NULL;
+        strm->opaque = Z_NULL;
+        ret = deflateInit2(strm, state->level, Z_DEFLATED,
+                           MAX_WBITS + 16, DEF_MEM_LEVEL, state->strategy);
+        if (ret != Z_OK) {
+            free(state->out);
+            free(state->in);
+            gz_error(state, Z_MEM_ERROR, "out of memory");
+            return -1;
+        }
+        strm->next_in = NULL;
+    }
+
+    /* mark state as initialized */
+    state->size = state->want;
+
+    /* initialize write buffer if compressing */
+    if (!state->direct) {
+        strm->avail_out = state->size;
+        strm->next_out = state->out;
+        state->x.next = strm->next_out;
+    }
+    return 0;
+}
+
+/* Compress whatever is at avail_in and next_in and write to the output file.
+   Return -1 if there is an error writing to the output file or if gz_init()
+   fails to allocate memory, otherwise 0.  flush is assumed to be a valid
+   deflate() flush value.  If flush is Z_FINISH, then the deflate() state is
+   reset to start a new gzip stream.  If gz->direct is true, then simply write
+   to the output file without compressing, and ignore flush. */
+local int gz_comp(state, flush)
+    gz_statep state;
+    int flush;
+{
+    int ret, writ;
+    unsigned have, put, max = ((unsigned)-1 >> 2) + 1;
+    z_streamp strm = &(state->strm);
+
+    /* allocate memory if this is the first time through */
+    if (state->size == 0 && gz_init(state) == -1)
+        return -1;
+
+    /* write directly if requested */
+    if (state->direct) {
+        while (strm->avail_in) {
+            put = strm->avail_in > max ? max : strm->avail_in;
+            writ = write(state->fd, strm->next_in, put);
+            if (writ < 0) {
+                gz_error(state, Z_ERRNO, zstrerror());
+                return -1;
+            }
+            strm->avail_in -= (unsigned)writ;
+            strm->next_in += writ;
+        }
+        return 0;
+    }
+
+    /* run deflate() on provided input until it produces no more output */
+    ret = Z_OK;
+    do {
+        /* write out current buffer contents if full, or if flushing, but if
+           doing Z_FINISH then don't write until we get to Z_STREAM_END */
+        if (strm->avail_out == 0 || (flush != Z_NO_FLUSH &&
+            (flush != Z_FINISH || ret == Z_STREAM_END))) {
+            while (strm->next_out > state->x.next) {
+                put = strm->next_out - state->x.next > (int)max ? max :
+                      (unsigned)(strm->next_out - state->x.next);
+                writ = write(state->fd, state->x.next, put);
+                if (writ < 0) {
+                    gz_error(state, Z_ERRNO, zstrerror());
+                    return -1;
+                }
+                state->x.next += writ;
+            }
+            if (strm->avail_out == 0) {
+                strm->avail_out = state->size;
+                strm->next_out = state->out;
+                state->x.next = state->out;
+            }
+        }
+
+        /* compress */
+        have = strm->avail_out;
+        ret = deflate(strm, flush);
+        if (ret == Z_STREAM_ERROR) {
+            gz_error(state, Z_STREAM_ERROR,
+                      "internal error: deflate stream corrupt");
+            return -1;
+        }
+        have -= strm->avail_out;
+    } while (have);
+
+    /* if that completed a deflate stream, allow another to start */
+    if (flush == Z_FINISH)
+        deflateReset(strm);
+
+    /* all done, no errors */
+    return 0;
+}
+
+/* Compress len zeros to output.  Return -1 on a write error or memory
+   allocation failure by gz_comp(), or 0 on success. */
+local int gz_zero(state, len)
+    gz_statep state;
+    z_off64_t len;
+{
+    int first;
+    unsigned n;
+    z_streamp strm = &(state->strm);
+
+    /* consume whatever's left in the input buffer */
+    if (strm->avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
+        return -1;
+
+    /* compress len zeros (len guaranteed > 0) */
+    first = 1;
+    while (len) {
+        n = GT_OFF(state->size) || (z_off64_t)state->size > len ?
+            (unsigned)len : state->size;
+        if (first) {
+            memset(state->in, 0, n);
+            first = 0;
+        }
+        strm->avail_in = n;
+        strm->next_in = state->in;
+        state->x.pos += n;
+        if (gz_comp(state, Z_NO_FLUSH) == -1)
+            return -1;
+        len -= n;
+    }
+    return 0;
+}
+
+/* Write len bytes from buf to file.  Return the number of bytes written.  If
+   the returned value is less than len, then there was an error. */
+local z_size_t gz_write(state, buf, len)
+    gz_statep state;
+    voidpc buf;
+    z_size_t len;
+{
+    z_size_t put = len;
+
+    /* if len is zero, avoid unnecessary operations */
+    if (len == 0)
+        return 0;
+
+    /* allocate memory if this is the first time through */
+    if (state->size == 0 && gz_init(state) == -1)
+        return 0;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            return 0;
+    }
+
+    /* for small len, copy to input buffer, otherwise compress directly */
+    if (len < state->size) {
+        /* copy to input buffer, compress when full */
+        do {
+            unsigned have, copy;
+
+            if (state->strm.avail_in == 0)
+                state->strm.next_in = state->in;
+            have = (unsigned)((state->strm.next_in + state->strm.avail_in) -
+                              state->in);
+            copy = state->size - have;
+            if (copy > len)
+                copy = (unsigned)len;
+            memcpy(state->in + have, buf, copy);
+            state->strm.avail_in += copy;
+            state->x.pos += copy;
+            buf = (const char *)buf + copy;
+            len -= copy;
+            if (len && gz_comp(state, Z_NO_FLUSH) == -1)
+                return 0;
+        } while (len);
+    }
+    else {
+        /* consume whatever's left in the input buffer */
+        if (state->strm.avail_in && gz_comp(state, Z_NO_FLUSH) == -1)
+            return 0;
+
+        /* directly compress user buffer to file */
+        state->strm.next_in = (z_const Bytef *)buf;
+        do {
+            unsigned n = (unsigned)-1;
+            if (n > len)
+                n = (unsigned)len;
+            state->strm.avail_in = n;
+            state->x.pos += n;
+            if (gz_comp(state, Z_NO_FLUSH) == -1)
+                return 0;
+            len -= n;
+        } while (len);
+    }
+
+    /* input was all buffered or compressed */
+    return put;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzwrite(file, buf, len)
+    gzFile file;
+    voidpc buf;
+    unsigned len;
+{
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return 0;
+    state = (gz_statep)file;
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return 0;
+
+    /* since an int is returned, make sure len fits in one, otherwise return
+       with an error (this avoids a flaw in the interface) */
+    if ((int)len < 0) {
+        gz_error(state, Z_DATA_ERROR, "requested length does not fit in int");
+        return 0;
+    }
+
+    /* write len bytes from buf (the return value will fit in an int) */
+    return (int)gz_write(state, buf, len);
+}
+
+/* -- see zlib.h -- */
+z_size_t ZEXPORT gzfwrite(buf, size, nitems, file)
+    voidpc buf;
+    z_size_t size;
+    z_size_t nitems;
+    gzFile file;
+{
+    z_size_t len;
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return 0;
+    state = (gz_statep)file;
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return 0;
+
+    /* compute bytes to read -- error on overflow */
+    len = nitems * size;
+    if (size && len / size != nitems) {
+        gz_error(state, Z_STREAM_ERROR, "request does not fit in a size_t");
+        return 0;
+    }
+
+    /* write len bytes to buf, return the number of full items written */
+    return len ? gz_write(state, buf, len) / size : 0;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzputc(file, c)
+    gzFile file;
+    int c;
+{
+    unsigned have;
+    unsigned char buf[1];
+    gz_statep state;
+    z_streamp strm;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+    strm = &(state->strm);
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return -1;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            return -1;
+    }
+
+    /* try writing to input buffer for speed (state->size == 0 if buffer not
+       initialized) */
+    if (state->size) {
+        if (strm->avail_in == 0)
+            strm->next_in = state->in;
+        have = (unsigned)((strm->next_in + strm->avail_in) - state->in);
+        if (have < state->size) {
+            state->in[have] = (unsigned char)c;
+            strm->avail_in++;
+            state->x.pos++;
+            return c & 0xff;
+        }
+    }
+
+    /* no room in buffer or not initialized, use gz_write() */
+    buf[0] = (unsigned char)c;
+    if (gz_write(state, buf, 1) != 1)
+        return -1;
+    return c & 0xff;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzputs(file, str)
+    gzFile file;
+    const char *str;
+{
+    int ret;
+    z_size_t len;
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return -1;
+    state = (gz_statep)file;
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return -1;
+
+    /* write string */
+    len = strlen(str);
+    ret = (int)gz_write(state, str, len);
+    return ret == 0 && len != 0 ? -1 : ret;
+}
+
+#if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#include <stdarg.h>
+
+/* -- see zlib.h -- */
+int ZEXPORTVA gzvprintf(gzFile file, const char *format, va_list va)
+{
+    int len;
+    unsigned left;
+    char *next;
+    gz_statep state;
+    z_streamp strm;
+
+    /* get internal structure */
+    if (file == NULL)
+        return Z_STREAM_ERROR;
+    state = (gz_statep)file;
+    strm = &(state->strm);
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return Z_STREAM_ERROR;
+
+    /* make sure we have some buffer space */
+    if (state->size == 0 && gz_init(state) == -1)
+        return state->err;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            return state->err;
+    }
+
+    /* do the printf() into the input buffer, put length in len -- the input
+       buffer is double-sized just for this function, so there is guaranteed to
+       be state->size bytes available after the current contents */
+    if (strm->avail_in == 0)
+        strm->next_in = state->in;
+    next = (char *)(state->in + (strm->next_in - state->in) + strm->avail_in);
+    next[state->size - 1] = 0;
+#ifdef NO_vsnprintf
+#  ifdef HAS_vsprintf_void
+    (void)vsprintf(next, format, va);
+    for (len = 0; len < state->size; len++)
+        if (next[len] == 0) break;
+#  else
+    len = vsprintf(next, format, va);
+#  endif
+#else
+#  ifdef HAS_vsnprintf_void
+    (void)vsnprintf(next, state->size, format, va);
+    len = strlen(next);
+#  else
+    len = vsnprintf(next, state->size, format, va);
+#  endif
+#endif
+
+    /* check that printf() results fit in buffer */
+    if (len == 0 || (unsigned)len >= state->size || next[state->size - 1] != 0)
+        return 0;
+
+    /* update buffer and position, compress first half if past that */
+    strm->avail_in += (unsigned)len;
+    state->x.pos += len;
+    if (strm->avail_in >= state->size) {
+        left = strm->avail_in - state->size;
+        strm->avail_in = state->size;
+        if (gz_comp(state, Z_NO_FLUSH) == -1)
+            return state->err;
+        memcpy(state->in, state->in + state->size, left);
+        strm->next_in = state->in;
+        strm->avail_in = left;
+    }
+    return len;
+}
+
+int ZEXPORTVA gzprintf(gzFile file, const char *format, ...)
+{
+    va_list va;
+    int ret;
+
+    va_start(va, format);
+    ret = gzvprintf(file, format, va);
+    va_end(va);
+    return ret;
+}
+
+#else /* !STDC && !Z_HAVE_STDARG_H */
+
+/* -- see zlib.h -- */
+int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
+                       a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
+    gzFile file;
+    const char *format;
+    int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
+        a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
+{
+    unsigned len, left;
+    char *next;
+    gz_statep state;
+    z_streamp strm;
+
+    /* get internal structure */
+    if (file == NULL)
+        return Z_STREAM_ERROR;
+    state = (gz_statep)file;
+    strm = &(state->strm);
+
+    /* check that can really pass pointer in ints */
+    if (sizeof(int) != sizeof(void *))
+        return Z_STREAM_ERROR;
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return Z_STREAM_ERROR;
+
+    /* make sure we have some buffer space */
+    if (state->size == 0 && gz_init(state) == -1)
+        return state->error;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            return state->error;
+    }
+
+    /* do the printf() into the input buffer, put length in len -- the input
+       buffer is double-sized just for this function, so there is guaranteed to
+       be state->size bytes available after the current contents */
+    if (strm->avail_in == 0)
+        strm->next_in = state->in;
+    next = (char *)(strm->next_in + strm->avail_in);
+    next[state->size - 1] = 0;
+#ifdef NO_snprintf
+#  ifdef HAS_sprintf_void
+    sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12,
+            a13, a14, a15, a16, a17, a18, a19, a20);
+    for (len = 0; len < size; len++)
+        if (next[len] == 0)
+            break;
+#  else
+    len = sprintf(next, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11,
+                  a12, a13, a14, a15, a16, a17, a18, a19, a20);
+#  endif
+#else
+#  ifdef HAS_snprintf_void
+    snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8, a9,
+             a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
+    len = strlen(next);
+#  else
+    len = snprintf(next, state->size, format, a1, a2, a3, a4, a5, a6, a7, a8,
+                   a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
+#  endif
+#endif
+
+    /* check that printf() results fit in buffer */
+    if (len == 0 || len >= state->size || next[state->size - 1] != 0)
+        return 0;
+
+    /* update buffer and position, compress first half if past that */
+    strm->avail_in += len;
+    state->x.pos += len;
+    if (strm->avail_in >= state->size) {
+        left = strm->avail_in - state->size;
+        strm->avail_in = state->size;
+        if (gz_comp(state, Z_NO_FLUSH) == -1)
+            return state->err;
+        memcpy(state->in, state->in + state->size, left);
+        strm->next_in = state->in;
+        strm->avail_in = left;
+    }
+    return (int)len;
+}
+
+#endif
+
+/* -- see zlib.h -- */
+int ZEXPORT gzflush(file, flush)
+    gzFile file;
+    int flush;
+{
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return Z_STREAM_ERROR;
+    state = (gz_statep)file;
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return Z_STREAM_ERROR;
+
+    /* check flush parameter */
+    if (flush < 0 || flush > Z_FINISH)
+        return Z_STREAM_ERROR;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            return state->err;
+    }
+
+    /* compress remaining data with requested flush */
+    (void)gz_comp(state, flush);
+    return state->err;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzsetparams(file, level, strategy)
+    gzFile file;
+    int level;
+    int strategy;
+{
+    gz_statep state;
+    z_streamp strm;
+
+    /* get internal structure */
+    if (file == NULL)
+        return Z_STREAM_ERROR;
+    state = (gz_statep)file;
+    strm = &(state->strm);
+
+    /* check that we're writing and that there's no error */
+    if (state->mode != GZ_WRITE || state->err != Z_OK)
+        return Z_STREAM_ERROR;
+
+    /* if no change is requested, then do nothing */
+    if (level == state->level && strategy == state->strategy)
+        return Z_OK;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            return state->err;
+    }
+
+    /* change compression parameters for subsequent input */
+    if (state->size) {
+        /* flush previous input with previous parameters before changing */
+        if (strm->avail_in && gz_comp(state, Z_BLOCK) == -1)
+            return state->err;
+        deflateParams(strm, level, strategy);
+    }
+    state->level = level;
+    state->strategy = strategy;
+    return Z_OK;
+}
+
+/* -- see zlib.h -- */
+int ZEXPORT gzclose_w(file)
+    gzFile file;
+{
+    int ret = Z_OK;
+    gz_statep state;
+
+    /* get internal structure */
+    if (file == NULL)
+        return Z_STREAM_ERROR;
+    state = (gz_statep)file;
+
+    /* check that we're writing */
+    if (state->mode != GZ_WRITE)
+        return Z_STREAM_ERROR;
+
+    /* check for seek request */
+    if (state->seek) {
+        state->seek = 0;
+        if (gz_zero(state, state->skip) == -1)
+            ret = state->err;
+    }
+
+    /* flush, free memory, and close file */
+    if (gz_comp(state, Z_FINISH) == -1)
+        ret = state->err;
+    if (state->size) {
+        if (!state->direct) {
+            (void)deflateEnd(&(state->strm));
+            free(state->out);
+        }
+        free(state->in);
+    }
+    gz_error(state, Z_OK, NULL);
+    free(state->path);
+    if (close(state->fd) == -1)
+        ret = Z_ERRNO;
+    free(state);
+    return ret;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/infback.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,664 @@
+/*
+ * 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.
+ */
+
+/* infback.c -- inflate using a call-back interface
+ * Copyright (C) 1995-2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+   This code is largely copied from inflate.c.  Normally either infback.o or
+   inflate.o would be linked into an application--not both.  The interface
+   with inffast.c is retained so that optimized assembler-coded versions of
+   inflate_fast() can be used with either inflate.c or infback.c.
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+#include "inflate.h"
+#include "inffast.h"
+
+/* function prototypes */
+local void fixedtables OF((struct inflate_state FAR *state));
+
+/*
+   strm provides memory allocation functions in zalloc and zfree, or
+   Z_NULL to use the library memory allocation functions.
+
+   windowBits is in the range 8..15, and window is a user-supplied
+   window and output buffer that is 2**windowBits bytes.
+ */
+int ZEXPORT inflateBackInit_(strm, windowBits, window, version, stream_size)
+z_streamp strm;
+int windowBits;
+unsigned char FAR *window;
+const char *version;
+int stream_size;
+{
+    struct inflate_state FAR *state;
+
+    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
+        stream_size != (int)(sizeof(z_stream)))
+        return Z_VERSION_ERROR;
+    if (strm == Z_NULL || window == Z_NULL ||
+        windowBits < 8 || windowBits > 15)
+        return Z_STREAM_ERROR;
+    strm->msg = Z_NULL;                 /* in case we return an error */
+    if (strm->zalloc == (alloc_func)0) {
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+        strm->zalloc = zcalloc;
+        strm->opaque = (voidpf)0;
+#endif
+    }
+    if (strm->zfree == (free_func)0)
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+    strm->zfree = zcfree;
+#endif
+    state = (struct inflate_state FAR *)ZALLOC(strm, 1,
+                                               sizeof(struct inflate_state));
+    if (state == Z_NULL) return Z_MEM_ERROR;
+    Tracev((stderr, "inflate: allocated\n"));
+    strm->state = (struct internal_state FAR *)state;
+    state->dmax = 32768U;
+    state->wbits = (uInt)windowBits;
+    state->wsize = 1U << windowBits;
+    state->window = window;
+    state->wnext = 0;
+    state->whave = 0;
+    return Z_OK;
+}
+
+/*
+   Return state with length and distance decoding tables and index sizes set to
+   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
+   If BUILDFIXED is defined, then instead this routine builds the tables the
+   first time it's called, and returns those tables the first time and
+   thereafter.  This reduces the size of the code by about 2K bytes, in
+   exchange for a little execution time.  However, BUILDFIXED should not be
+   used for threaded applications, since the rewriting of the tables and virgin
+   may not be thread-safe.
+ */
+local void fixedtables(state)
+struct inflate_state FAR *state;
+{
+#ifdef BUILDFIXED
+    static int virgin = 1;
+    static code *lenfix, *distfix;
+    static code fixed[544];
+
+    /* build fixed huffman tables if first call (may not be thread safe) */
+    if (virgin) {
+        unsigned sym, bits;
+        static code *next;
+
+        /* literal/length table */
+        sym = 0;
+        while (sym < 144) state->lens[sym++] = 8;
+        while (sym < 256) state->lens[sym++] = 9;
+        while (sym < 280) state->lens[sym++] = 7;
+        while (sym < 288) state->lens[sym++] = 8;
+        next = fixed;
+        lenfix = next;
+        bits = 9;
+        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
+
+        /* distance table */
+        sym = 0;
+        while (sym < 32) state->lens[sym++] = 5;
+        distfix = next;
+        bits = 5;
+        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
+
+        /* do this just once */
+        virgin = 0;
+    }
+#else /* !BUILDFIXED */
+#   include "inffixed.h"
+#endif /* BUILDFIXED */
+    state->lencode = lenfix;
+    state->lenbits = 9;
+    state->distcode = distfix;
+    state->distbits = 5;
+}
+
+/* Macros for inflateBack(): */
+
+/* Load returned state from inflate_fast() */
+#define LOAD() \
+    do { \
+        put = strm->next_out; \
+        left = strm->avail_out; \
+        next = strm->next_in; \
+        have = strm->avail_in; \
+        hold = state->hold; \
+        bits = state->bits; \
+    } while (0)
+
+/* Set state from registers for inflate_fast() */
+#define RESTORE() \
+    do { \
+        strm->next_out = put; \
+        strm->avail_out = left; \
+        strm->next_in = next; \
+        strm->avail_in = have; \
+        state->hold = hold; \
+        state->bits = bits; \
+    } while (0)
+
+/* Clear the input bit accumulator */
+#define INITBITS() \
+    do { \
+        hold = 0; \
+        bits = 0; \
+    } while (0)
+
+/* Assure that some input is available.  If input is requested, but denied,
+   then return a Z_BUF_ERROR from inflateBack(). */
+#define PULL() \
+    do { \
+        if (have == 0) { \
+            have = in(in_desc, &next); \
+            if (have == 0) { \
+                next = Z_NULL; \
+                ret = Z_BUF_ERROR; \
+                goto inf_leave; \
+            } \
+        } \
+    } while (0)
+
+/* Get a byte of input into the bit accumulator, or return from inflateBack()
+   with an error if there is no input available. */
+#define PULLBYTE() \
+    do { \
+        PULL(); \
+        have--; \
+        hold += (unsigned long)(*next++) << bits; \
+        bits += 8; \
+    } while (0)
+
+/* Assure that there are at least n bits in the bit accumulator.  If there is
+   not enough available input to do that, then return from inflateBack() with
+   an error. */
+#define NEEDBITS(n) \
+    do { \
+        while (bits < (unsigned)(n)) \
+            PULLBYTE(); \
+    } while (0)
+
+/* Return the low n bits of the bit accumulator (n < 16) */
+#define BITS(n) \
+    ((unsigned)hold & ((1U << (n)) - 1))
+
+/* Remove n bits from the bit accumulator */
+#define DROPBITS(n) \
+    do { \
+        hold >>= (n); \
+        bits -= (unsigned)(n); \
+    } while (0)
+
+/* Remove zero to seven bits as needed to go to a byte boundary */
+#define BYTEBITS() \
+    do { \
+        hold >>= bits & 7; \
+        bits -= bits & 7; \
+    } while (0)
+
+/* Assure that some output space is available, by writing out the window
+   if it's full.  If the write fails, return from inflateBack() with a
+   Z_BUF_ERROR. */
+#define ROOM() \
+    do { \
+        if (left == 0) { \
+            put = state->window; \
+            left = state->wsize; \
+            state->whave = left; \
+            if (out(out_desc, put, left)) { \
+                ret = Z_BUF_ERROR; \
+                goto inf_leave; \
+            } \
+        } \
+    } while (0)
+
+/*
+   strm provides the memory allocation functions and window buffer on input,
+   and provides information on the unused input on return.  For Z_DATA_ERROR
+   returns, strm will also provide an error message.
+
+   in() and out() are the call-back input and output functions.  When
+   inflateBack() needs more input, it calls in().  When inflateBack() has
+   filled the window with output, or when it completes with data in the
+   window, it calls out() to write out the data.  The application must not
+   change the provided input until in() is called again or inflateBack()
+   returns.  The application must not change the window/output buffer until
+   inflateBack() returns.
+
+   in() and out() are called with a descriptor parameter provided in the
+   inflateBack() call.  This parameter can be a structure that provides the
+   information required to do the read or write, as well as accumulated
+   information on the input and output such as totals and check values.
+
+   in() should return zero on failure.  out() should return non-zero on
+   failure.  If either in() or out() fails, than inflateBack() returns a
+   Z_BUF_ERROR.  strm->next_in can be checked for Z_NULL to see whether it
+   was in() or out() that caused in the error.  Otherwise,  inflateBack()
+   returns Z_STREAM_END on success, Z_DATA_ERROR for an deflate format
+   error, or Z_MEM_ERROR if it could not allocate memory for the state.
+   inflateBack() can also return Z_STREAM_ERROR if the input parameters
+   are not correct, i.e. strm is Z_NULL or the state was not initialized.
+ */
+int ZEXPORT inflateBack(strm, in, in_desc, out, out_desc)
+z_streamp strm;
+in_func in;
+void FAR *in_desc;
+out_func out;
+void FAR *out_desc;
+{
+    struct inflate_state FAR *state;
+    z_const unsigned char FAR *next;    /* next input */
+    unsigned char FAR *put;     /* next output */
+    unsigned have, left;        /* available input and output */
+    unsigned long hold;         /* bit buffer */
+    unsigned bits;              /* bits in bit buffer */
+    unsigned copy;              /* number of stored or match bytes to copy */
+    unsigned char FAR *from;    /* where to copy match bytes from */
+    code here;                  /* current decoding table entry */
+    code last;                  /* parent table entry */
+    unsigned len;               /* length to copy for repeats, bits to drop */
+    int ret;                    /* return code */
+    static const unsigned short order[19] = /* permutation of code lengths */
+        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+
+    /* Check that the strm exists and that the state was initialized */
+    if (strm == Z_NULL || strm->state == Z_NULL)
+        return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+
+    /* Reset the state */
+    strm->msg = Z_NULL;
+    state->mode = TYPE;
+    state->last = 0;
+    state->whave = 0;
+    next = strm->next_in;
+    have = next != Z_NULL ? strm->avail_in : 0;
+    hold = 0;
+    bits = 0;
+    put = state->window;
+    left = state->wsize;
+
+    /* Inflate until end of block marked as last */
+    for (;;)
+        switch (state->mode) {
+        case TYPE:
+            /* determine and dispatch block type */
+            if (state->last) {
+                BYTEBITS();
+                state->mode = DONE;
+                break;
+            }
+            NEEDBITS(3);
+            state->last = BITS(1);
+            DROPBITS(1);
+            switch (BITS(2)) {
+            case 0:                             /* stored block */
+                Tracev((stderr, "inflate:     stored block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = STORED;
+                break;
+            case 1:                             /* fixed block */
+                fixedtables(state);
+                Tracev((stderr, "inflate:     fixed codes block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = LEN;              /* decode codes */
+                break;
+            case 2:                             /* dynamic block */
+                Tracev((stderr, "inflate:     dynamic codes block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = TABLE;
+                break;
+            case 3:
+                strm->msg = (char *)"invalid block type";
+                state->mode = BAD;
+            }
+            DROPBITS(2);
+            break;
+
+        case STORED:
+            /* get and verify stored block length */
+            BYTEBITS();                         /* go to byte boundary */
+            NEEDBITS(32);
+            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
+                strm->msg = (char *)"invalid stored block lengths";
+                state->mode = BAD;
+                break;
+            }
+            state->length = (unsigned)hold & 0xffff;
+            Tracev((stderr, "inflate:       stored length %u\n",
+                    state->length));
+            INITBITS();
+
+            /* copy stored block from input to output */
+            while (state->length != 0) {
+                copy = state->length;
+                PULL();
+                ROOM();
+                if (copy > have) copy = have;
+                if (copy > left) copy = left;
+                zmemcpy(put, next, copy);
+                have -= copy;
+                next += copy;
+                left -= copy;
+                put += copy;
+                state->length -= copy;
+            }
+            Tracev((stderr, "inflate:       stored end\n"));
+            state->mode = TYPE;
+            break;
+
+        case TABLE:
+            /* get dynamic table entries descriptor */
+            NEEDBITS(14);
+            state->nlen = BITS(5) + 257;
+            DROPBITS(5);
+            state->ndist = BITS(5) + 1;
+            DROPBITS(5);
+            state->ncode = BITS(4) + 4;
+            DROPBITS(4);
+#ifndef PKZIP_BUG_WORKAROUND
+            if (state->nlen > 286 || state->ndist > 30) {
+                strm->msg = (char *)"too many length or distance symbols";
+                state->mode = BAD;
+                break;
+            }
+#endif
+            Tracev((stderr, "inflate:       table sizes ok\n"));
+
+            /* get code length code lengths (not a typo) */
+            state->have = 0;
+            while (state->have < state->ncode) {
+                NEEDBITS(3);
+                state->lens[order[state->have++]] = (unsigned short)BITS(3);
+                DROPBITS(3);
+            }
+            while (state->have < 19)
+                state->lens[order[state->have++]] = 0;
+            state->next = state->codes;
+            state->lencode = (code const FAR *)(state->next);
+            state->lenbits = 7;
+            ret = inflate_table(CODES, state->lens, 19, &(state->next),
+                                &(state->lenbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid code lengths set";
+                state->mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       code lengths ok\n"));
+
+            /* get length and distance code code lengths */
+            state->have = 0;
+            while (state->have < state->nlen + state->ndist) {
+                for (;;) {
+                    here = state->lencode[BITS(state->lenbits)];
+                    if ((unsigned)(here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                if (here.val < 16) {
+                    DROPBITS(here.bits);
+                    state->lens[state->have++] = here.val;
+                }
+                else {
+                    if (here.val == 16) {
+                        NEEDBITS(here.bits + 2);
+                        DROPBITS(here.bits);
+                        if (state->have == 0) {
+                            strm->msg = (char *)"invalid bit length repeat";
+                            state->mode = BAD;
+                            break;
+                        }
+                        len = (unsigned)(state->lens[state->have - 1]);
+                        copy = 3 + BITS(2);
+                        DROPBITS(2);
+                    }
+                    else if (here.val == 17) {
+                        NEEDBITS(here.bits + 3);
+                        DROPBITS(here.bits);
+                        len = 0;
+                        copy = 3 + BITS(3);
+                        DROPBITS(3);
+                    }
+                    else {
+                        NEEDBITS(here.bits + 7);
+                        DROPBITS(here.bits);
+                        len = 0;
+                        copy = 11 + BITS(7);
+                        DROPBITS(7);
+                    }
+                    if (state->have + copy > state->nlen + state->ndist) {
+                        strm->msg = (char *)"invalid bit length repeat";
+                        state->mode = BAD;
+                        break;
+                    }
+                    while (copy--)
+                        state->lens[state->have++] = (unsigned short)len;
+                }
+            }
+
+            /* handle error breaks in while */
+            if (state->mode == BAD) break;
+
+            /* check for end-of-block code (better have one) */
+            if (state->lens[256] == 0) {
+                strm->msg = (char *)"invalid code -- missing end-of-block";
+                state->mode = BAD;
+                break;
+            }
+
+            /* build code tables -- note: do not change the lenbits or distbits
+               values here (9 and 6) without reading the comments in inftrees.h
+               concerning the ENOUGH constants, which depend on those values */
+            state->next = state->codes;
+            state->lencode = (code const FAR *)(state->next);
+            state->lenbits = 9;
+            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
+                                &(state->lenbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid literal/lengths set";
+                state->mode = BAD;
+                break;
+            }
+            state->distcode = (code const FAR *)(state->next);
+            state->distbits = 6;
+            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
+                            &(state->next), &(state->distbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid distances set";
+                state->mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       codes ok\n"));
+            state->mode = LEN;
+
+        case LEN:
+            /* use inflate_fast() if we have enough input and output */
+            if (have >= 6 && left >= 258) {
+                RESTORE();
+                if (state->whave < state->wsize)
+                    state->whave = state->wsize - left;
+                inflate_fast(strm, state->wsize);
+                LOAD();
+                break;
+            }
+
+            /* get a literal, length, or end-of-block code */
+            for (;;) {
+                here = state->lencode[BITS(state->lenbits)];
+                if ((unsigned)(here.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if (here.op && (here.op & 0xf0) == 0) {
+                last = here;
+                for (;;) {
+                    here = state->lencode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+            }
+            DROPBITS(here.bits);
+            state->length = (unsigned)here.val;
+
+            /* process literal */
+            if (here.op == 0) {
+                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+                        "inflate:         literal '%c'\n" :
+                        "inflate:         literal 0x%02x\n", here.val));
+                ROOM();
+                *put++ = (unsigned char)(state->length);
+                left--;
+                state->mode = LEN;
+                break;
+            }
+
+            /* process end of block */
+            if (here.op & 32) {
+                Tracevv((stderr, "inflate:         end of block\n"));
+                state->mode = TYPE;
+                break;
+            }
+
+            /* invalid code */
+            if (here.op & 64) {
+                strm->msg = (char *)"invalid literal/length code";
+                state->mode = BAD;
+                break;
+            }
+
+            /* length code -- get extra bits, if any */
+            state->extra = (unsigned)(here.op) & 15;
+            if (state->extra != 0) {
+                NEEDBITS(state->extra);
+                state->length += BITS(state->extra);
+                DROPBITS(state->extra);
+            }
+            Tracevv((stderr, "inflate:         length %u\n", state->length));
+
+            /* get distance code */
+            for (;;) {
+                here = state->distcode[BITS(state->distbits)];
+                if ((unsigned)(here.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if ((here.op & 0xf0) == 0) {
+                last = here;
+                for (;;) {
+                    here = state->distcode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+            }
+            DROPBITS(here.bits);
+            if (here.op & 64) {
+                strm->msg = (char *)"invalid distance code";
+                state->mode = BAD;
+                break;
+            }
+            state->offset = (unsigned)here.val;
+
+            /* get distance extra bits, if any */
+            state->extra = (unsigned)(here.op) & 15;
+            if (state->extra != 0) {
+                NEEDBITS(state->extra);
+                state->offset += BITS(state->extra);
+                DROPBITS(state->extra);
+            }
+            if (state->offset > state->wsize - (state->whave < state->wsize ?
+                                                left : 0)) {
+                strm->msg = (char *)"invalid distance too far back";
+                state->mode = BAD;
+                break;
+            }
+            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
+
+            /* copy match from window to output */
+            do {
+                ROOM();
+                copy = state->wsize - state->offset;
+                if (copy < left) {
+                    from = put + copy;
+                    copy = left - copy;
+                }
+                else {
+                    from = put - state->offset;
+                    copy = left;
+                }
+                if (copy > state->length) copy = state->length;
+                state->length -= copy;
+                left -= copy;
+                do {
+                    *put++ = *from++;
+                } while (--copy);
+            } while (state->length != 0);
+            break;
+
+        case DONE:
+            /* inflate stream terminated properly -- write leftover output */
+            ret = Z_STREAM_END;
+            if (left < state->wsize) {
+                if (out(out_desc, state->window, state->wsize - left))
+                    ret = Z_BUF_ERROR;
+            }
+            goto inf_leave;
+
+        case BAD:
+            ret = Z_DATA_ERROR;
+            goto inf_leave;
+
+        default:                /* can't happen, but makes compilers happy */
+            ret = Z_STREAM_ERROR;
+            goto inf_leave;
+        }
+
+    /* Return unused input */
+  inf_leave:
+    strm->next_in = next;
+    strm->avail_in = have;
+    return ret;
+}
+
+int ZEXPORT inflateBackEnd(strm)
+z_streamp strm;
+{
+    if (strm == Z_NULL || strm->state == Z_NULL || strm->zfree == (free_func)0)
+        return Z_STREAM_ERROR;
+    ZFREE(strm, strm->state);
+    strm->state = Z_NULL;
+    Tracev((stderr, "inflate: end\n"));
+    return Z_OK;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/inffast.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,347 @@
+/*
+ * 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.
+ */
+
+/* inffast.c -- fast decoding
+ * Copyright (C) 1995-2017 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+#include "inflate.h"
+#include "inffast.h"
+
+#ifdef ASMINF
+#  pragma message("Assembler code may have bugs -- use at your own risk")
+#else
+
+/*
+   Decode literal, length, and distance codes and write out the resulting
+   literal and match bytes until either not enough input or output is
+   available, an end-of-block is encountered, or a data error is encountered.
+   When large enough input and output buffers are supplied to inflate(), for
+   example, a 16K input buffer and a 64K output buffer, more than 95% of the
+   inflate execution time is spent in this routine.
+
+   Entry assumptions:
+
+        state->mode == LEN
+        strm->avail_in >= 6
+        strm->avail_out >= 258
+        start >= strm->avail_out
+        state->bits < 8
+
+   On return, state->mode is one of:
+
+        LEN -- ran out of enough output space or enough available input
+        TYPE -- reached end of block code, inflate() to interpret next block
+        BAD -- error in block data
+
+   Notes:
+
+    - The maximum input bits used by a length/distance pair is 15 bits for the
+      length code, 5 bits for the length extra, 15 bits for the distance code,
+      and 13 bits for the distance extra.  This totals 48 bits, or six bytes.
+      Therefore if strm->avail_in >= 6, then there is enough input to avoid
+      checking for available input while decoding.
+
+    - The maximum bytes that a single length/distance pair can output is 258
+      bytes, which is the maximum length that can be coded.  inflate_fast()
+      requires strm->avail_out >= 258 for each loop to avoid checking for
+      output space.
+ */
+void ZLIB_INTERNAL inflate_fast(strm, start)
+z_streamp strm;
+unsigned start;         /* inflate()'s starting value for strm->avail_out */
+{
+    struct inflate_state FAR *state;
+    z_const unsigned char FAR *in;      /* local strm->next_in */
+    z_const unsigned char FAR *last;    /* have enough input while in < last */
+    unsigned char FAR *out;     /* local strm->next_out */
+    unsigned char FAR *beg;     /* inflate()'s initial strm->next_out */
+    unsigned char FAR *end;     /* while out < end, enough space available */
+#ifdef INFLATE_STRICT
+    unsigned dmax;              /* maximum distance from zlib header */
+#endif
+    unsigned wsize;             /* window size or zero if not using window */
+    unsigned whave;             /* valid bytes in the window */
+    unsigned wnext;             /* window write index */
+    unsigned char FAR *window;  /* allocated sliding window, if wsize != 0 */
+    unsigned long hold;         /* local strm->hold */
+    unsigned bits;              /* local strm->bits */
+    code const FAR *lcode;      /* local strm->lencode */
+    code const FAR *dcode;      /* local strm->distcode */
+    unsigned lmask;             /* mask for first level of length codes */
+    unsigned dmask;             /* mask for first level of distance codes */
+    code here;                  /* retrieved table entry */
+    unsigned op;                /* code bits, operation, extra bits, or */
+                                /*  window position, window bytes to copy */
+    unsigned len;               /* match length, unused bytes */
+    unsigned dist;              /* match distance */
+    unsigned char FAR *from;    /* where to copy match from */
+
+    /* copy state to local variables */
+    state = (struct inflate_state FAR *)strm->state;
+    in = strm->next_in;
+    last = in + (strm->avail_in - 5);
+    out = strm->next_out;
+    beg = out - (start - strm->avail_out);
+    end = out + (strm->avail_out - 257);
+#ifdef INFLATE_STRICT
+    dmax = state->dmax;
+#endif
+    wsize = state->wsize;
+    whave = state->whave;
+    wnext = state->wnext;
+    window = state->window;
+    hold = state->hold;
+    bits = state->bits;
+    lcode = state->lencode;
+    dcode = state->distcode;
+    lmask = (1U << state->lenbits) - 1;
+    dmask = (1U << state->distbits) - 1;
+
+    /* decode literals and length/distances until end-of-block or not enough
+       input data or output space */
+    do {
+        if (bits < 15) {
+            hold += (unsigned long)(*in++) << bits;
+            bits += 8;
+            hold += (unsigned long)(*in++) << bits;
+            bits += 8;
+        }
+        here = lcode[hold & lmask];
+      dolen:
+        op = (unsigned)(here.bits);
+        hold >>= op;
+        bits -= op;
+        op = (unsigned)(here.op);
+        if (op == 0) {                          /* literal */
+            Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+                    "inflate:         literal '%c'\n" :
+                    "inflate:         literal 0x%02x\n", here.val));
+            *out++ = (unsigned char)(here.val);
+        }
+        else if (op & 16) {                     /* length base */
+            len = (unsigned)(here.val);
+            op &= 15;                           /* number of extra bits */
+            if (op) {
+                if (bits < op) {
+                    hold += (unsigned long)(*in++) << bits;
+                    bits += 8;
+                }
+                len += (unsigned)hold & ((1U << op) - 1);
+                hold >>= op;
+                bits -= op;
+            }
+            Tracevv((stderr, "inflate:         length %u\n", len));
+            if (bits < 15) {
+                hold += (unsigned long)(*in++) << bits;
+                bits += 8;
+                hold += (unsigned long)(*in++) << bits;
+                bits += 8;
+            }
+            here = dcode[hold & dmask];
+          dodist:
+            op = (unsigned)(here.bits);
+            hold >>= op;
+            bits -= op;
+            op = (unsigned)(here.op);
+            if (op & 16) {                      /* distance base */
+                dist = (unsigned)(here.val);
+                op &= 15;                       /* number of extra bits */
+                if (bits < op) {
+                    hold += (unsigned long)(*in++) << bits;
+                    bits += 8;
+                    if (bits < op) {
+                        hold += (unsigned long)(*in++) << bits;
+                        bits += 8;
+                    }
+                }
+                dist += (unsigned)hold & ((1U << op) - 1);
+#ifdef INFLATE_STRICT
+                if (dist > dmax) {
+                    strm->msg = (char *)"invalid distance too far back";
+                    state->mode = BAD;
+                    break;
+                }
+#endif
+                hold >>= op;
+                bits -= op;
+                Tracevv((stderr, "inflate:         distance %u\n", dist));
+                op = (unsigned)(out - beg);     /* max distance in output */
+                if (dist > op) {                /* see if copy from window */
+                    op = dist - op;             /* distance back in window */
+                    if (op > whave) {
+                        if (state->sane) {
+                            strm->msg =
+                                (char *)"invalid distance too far back";
+                            state->mode = BAD;
+                            break;
+                        }
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+                        if (len <= op - whave) {
+                            do {
+                                *out++ = 0;
+                            } while (--len);
+                            continue;
+                        }
+                        len -= op - whave;
+                        do {
+                            *out++ = 0;
+                        } while (--op > whave);
+                        if (op == 0) {
+                            from = out - dist;
+                            do {
+                                *out++ = *from++;
+                            } while (--len);
+                            continue;
+                        }
+#endif
+                    }
+                    from = window;
+                    if (wnext == 0) {           /* very common case */
+                        from += wsize - op;
+                        if (op < len) {         /* some from window */
+                            len -= op;
+                            do {
+                                *out++ = *from++;
+                            } while (--op);
+                            from = out - dist;  /* rest from output */
+                        }
+                    }
+                    else if (wnext < op) {      /* wrap around window */
+                        from += wsize + wnext - op;
+                        op -= wnext;
+                        if (op < len) {         /* some from end of window */
+                            len -= op;
+                            do {
+                                *out++ = *from++;
+                            } while (--op);
+                            from = window;
+                            if (wnext < len) {  /* some from start of window */
+                                op = wnext;
+                                len -= op;
+                                do {
+                                    *out++ = *from++;
+                                } while (--op);
+                                from = out - dist;      /* rest from output */
+                            }
+                        }
+                    }
+                    else {                      /* contiguous in window */
+                        from += wnext - op;
+                        if (op < len) {         /* some from window */
+                            len -= op;
+                            do {
+                                *out++ = *from++;
+                            } while (--op);
+                            from = out - dist;  /* rest from output */
+                        }
+                    }
+                    while (len > 2) {
+                        *out++ = *from++;
+                        *out++ = *from++;
+                        *out++ = *from++;
+                        len -= 3;
+                    }
+                    if (len) {
+                        *out++ = *from++;
+                        if (len > 1)
+                            *out++ = *from++;
+                    }
+                }
+                else {
+                    from = out - dist;          /* copy direct from output */
+                    do {                        /* minimum length is three */
+                        *out++ = *from++;
+                        *out++ = *from++;
+                        *out++ = *from++;
+                        len -= 3;
+                    } while (len > 2);
+                    if (len) {
+                        *out++ = *from++;
+                        if (len > 1)
+                            *out++ = *from++;
+                    }
+                }
+            }
+            else if ((op & 64) == 0) {          /* 2nd level distance code */
+                here = dcode[here.val + (hold & ((1U << op) - 1))];
+                goto dodist;
+            }
+            else {
+                strm->msg = (char *)"invalid distance code";
+                state->mode = BAD;
+                break;
+            }
+        }
+        else if ((op & 64) == 0) {              /* 2nd level length code */
+            here = lcode[here.val + (hold & ((1U << op) - 1))];
+            goto dolen;
+        }
+        else if (op & 32) {                     /* end-of-block */
+            Tracevv((stderr, "inflate:         end of block\n"));
+            state->mode = TYPE;
+            break;
+        }
+        else {
+            strm->msg = (char *)"invalid literal/length code";
+            state->mode = BAD;
+            break;
+        }
+    } while (in < last && out < end);
+
+    /* return unused bytes (on entry, bits < 8, so in won't go too far back) */
+    len = bits >> 3;
+    in -= len;
+    bits -= len << 3;
+    hold &= (1U << bits) - 1;
+
+    /* update state and return */
+    strm->next_in = in;
+    strm->next_out = out;
+    strm->avail_in = (unsigned)(in < last ? 5 + (last - in) : 5 - (in - last));
+    strm->avail_out = (unsigned)(out < end ?
+                                 257 + (end - out) : 257 - (out - end));
+    state->hold = hold;
+    state->bits = bits;
+    return;
+}
+
+/*
+   inflate_fast() speedups that turned out slower (on a PowerPC G3 750CXe):
+   - Using bit fields for code structure
+   - Different op definition to avoid & for extra bits (do & for table bits)
+   - Three separate decoding do-loops for direct, window, and wnext == 0
+   - Special case for distance > 1 copies to do overlapped load and store copy
+   - Explicit branch predictions (based on measured branch probabilities)
+   - Deferring match copy and interspersed it with decoding subsequent codes
+   - Swapping literal/length else
+   - Swapping window/direct else
+   - Larger unrolled copy loops (three is about right)
+   - Moving len -= 3 statement into middle of loop
+ */
+
+#endif /* !ASMINF */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/inffast.h	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,35 @@
+/*
+ * 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.
+ */
+
+/* inffast.h -- header to use inffast.c
+ * Copyright (C) 1995-2003, 2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+void ZLIB_INTERNAL inflate_fast OF((z_streamp strm, unsigned start));
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/inffixed.h	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,118 @@
+/*
+ * 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.
+ */
+
+    /* inffixed.h -- table for decoding fixed codes
+     * Generated automatically by makefixed().
+     */
+
+    /* WARNING: this file should *not* be used by applications.
+       It is part of the implementation of this library and is
+       subject to change. Applications should only use zlib.h.
+     */
+
+    static const code lenfix[512] = {
+        {96,7,0},{0,8,80},{0,8,16},{20,8,115},{18,7,31},{0,8,112},{0,8,48},
+        {0,9,192},{16,7,10},{0,8,96},{0,8,32},{0,9,160},{0,8,0},{0,8,128},
+        {0,8,64},{0,9,224},{16,7,6},{0,8,88},{0,8,24},{0,9,144},{19,7,59},
+        {0,8,120},{0,8,56},{0,9,208},{17,7,17},{0,8,104},{0,8,40},{0,9,176},
+        {0,8,8},{0,8,136},{0,8,72},{0,9,240},{16,7,4},{0,8,84},{0,8,20},
+        {21,8,227},{19,7,43},{0,8,116},{0,8,52},{0,9,200},{17,7,13},{0,8,100},
+        {0,8,36},{0,9,168},{0,8,4},{0,8,132},{0,8,68},{0,9,232},{16,7,8},
+        {0,8,92},{0,8,28},{0,9,152},{20,7,83},{0,8,124},{0,8,60},{0,9,216},
+        {18,7,23},{0,8,108},{0,8,44},{0,9,184},{0,8,12},{0,8,140},{0,8,76},
+        {0,9,248},{16,7,3},{0,8,82},{0,8,18},{21,8,163},{19,7,35},{0,8,114},
+        {0,8,50},{0,9,196},{17,7,11},{0,8,98},{0,8,34},{0,9,164},{0,8,2},
+        {0,8,130},{0,8,66},{0,9,228},{16,7,7},{0,8,90},{0,8,26},{0,9,148},
+        {20,7,67},{0,8,122},{0,8,58},{0,9,212},{18,7,19},{0,8,106},{0,8,42},
+        {0,9,180},{0,8,10},{0,8,138},{0,8,74},{0,9,244},{16,7,5},{0,8,86},
+        {0,8,22},{64,8,0},{19,7,51},{0,8,118},{0,8,54},{0,9,204},{17,7,15},
+        {0,8,102},{0,8,38},{0,9,172},{0,8,6},{0,8,134},{0,8,70},{0,9,236},
+        {16,7,9},{0,8,94},{0,8,30},{0,9,156},{20,7,99},{0,8,126},{0,8,62},
+        {0,9,220},{18,7,27},{0,8,110},{0,8,46},{0,9,188},{0,8,14},{0,8,142},
+        {0,8,78},{0,9,252},{96,7,0},{0,8,81},{0,8,17},{21,8,131},{18,7,31},
+        {0,8,113},{0,8,49},{0,9,194},{16,7,10},{0,8,97},{0,8,33},{0,9,162},
+        {0,8,1},{0,8,129},{0,8,65},{0,9,226},{16,7,6},{0,8,89},{0,8,25},
+        {0,9,146},{19,7,59},{0,8,121},{0,8,57},{0,9,210},{17,7,17},{0,8,105},
+        {0,8,41},{0,9,178},{0,8,9},{0,8,137},{0,8,73},{0,9,242},{16,7,4},
+        {0,8,85},{0,8,21},{16,8,258},{19,7,43},{0,8,117},{0,8,53},{0,9,202},
+        {17,7,13},{0,8,101},{0,8,37},{0,9,170},{0,8,5},{0,8,133},{0,8,69},
+        {0,9,234},{16,7,8},{0,8,93},{0,8,29},{0,9,154},{20,7,83},{0,8,125},
+        {0,8,61},{0,9,218},{18,7,23},{0,8,109},{0,8,45},{0,9,186},{0,8,13},
+        {0,8,141},{0,8,77},{0,9,250},{16,7,3},{0,8,83},{0,8,19},{21,8,195},
+        {19,7,35},{0,8,115},{0,8,51},{0,9,198},{17,7,11},{0,8,99},{0,8,35},
+        {0,9,166},{0,8,3},{0,8,131},{0,8,67},{0,9,230},{16,7,7},{0,8,91},
+        {0,8,27},{0,9,150},{20,7,67},{0,8,123},{0,8,59},{0,9,214},{18,7,19},
+        {0,8,107},{0,8,43},{0,9,182},{0,8,11},{0,8,139},{0,8,75},{0,9,246},
+        {16,7,5},{0,8,87},{0,8,23},{64,8,0},{19,7,51},{0,8,119},{0,8,55},
+        {0,9,206},{17,7,15},{0,8,103},{0,8,39},{0,9,174},{0,8,7},{0,8,135},
+        {0,8,71},{0,9,238},{16,7,9},{0,8,95},{0,8,31},{0,9,158},{20,7,99},
+        {0,8,127},{0,8,63},{0,9,222},{18,7,27},{0,8,111},{0,8,47},{0,9,190},
+        {0,8,15},{0,8,143},{0,8,79},{0,9,254},{96,7,0},{0,8,80},{0,8,16},
+        {20,8,115},{18,7,31},{0,8,112},{0,8,48},{0,9,193},{16,7,10},{0,8,96},
+        {0,8,32},{0,9,161},{0,8,0},{0,8,128},{0,8,64},{0,9,225},{16,7,6},
+        {0,8,88},{0,8,24},{0,9,145},{19,7,59},{0,8,120},{0,8,56},{0,9,209},
+        {17,7,17},{0,8,104},{0,8,40},{0,9,177},{0,8,8},{0,8,136},{0,8,72},
+        {0,9,241},{16,7,4},{0,8,84},{0,8,20},{21,8,227},{19,7,43},{0,8,116},
+        {0,8,52},{0,9,201},{17,7,13},{0,8,100},{0,8,36},{0,9,169},{0,8,4},
+        {0,8,132},{0,8,68},{0,9,233},{16,7,8},{0,8,92},{0,8,28},{0,9,153},
+        {20,7,83},{0,8,124},{0,8,60},{0,9,217},{18,7,23},{0,8,108},{0,8,44},
+        {0,9,185},{0,8,12},{0,8,140},{0,8,76},{0,9,249},{16,7,3},{0,8,82},
+        {0,8,18},{21,8,163},{19,7,35},{0,8,114},{0,8,50},{0,9,197},{17,7,11},
+        {0,8,98},{0,8,34},{0,9,165},{0,8,2},{0,8,130},{0,8,66},{0,9,229},
+        {16,7,7},{0,8,90},{0,8,26},{0,9,149},{20,7,67},{0,8,122},{0,8,58},
+        {0,9,213},{18,7,19},{0,8,106},{0,8,42},{0,9,181},{0,8,10},{0,8,138},
+        {0,8,74},{0,9,245},{16,7,5},{0,8,86},{0,8,22},{64,8,0},{19,7,51},
+        {0,8,118},{0,8,54},{0,9,205},{17,7,15},{0,8,102},{0,8,38},{0,9,173},
+        {0,8,6},{0,8,134},{0,8,70},{0,9,237},{16,7,9},{0,8,94},{0,8,30},
+        {0,9,157},{20,7,99},{0,8,126},{0,8,62},{0,9,221},{18,7,27},{0,8,110},
+        {0,8,46},{0,9,189},{0,8,14},{0,8,142},{0,8,78},{0,9,253},{96,7,0},
+        {0,8,81},{0,8,17},{21,8,131},{18,7,31},{0,8,113},{0,8,49},{0,9,195},
+        {16,7,10},{0,8,97},{0,8,33},{0,9,163},{0,8,1},{0,8,129},{0,8,65},
+        {0,9,227},{16,7,6},{0,8,89},{0,8,25},{0,9,147},{19,7,59},{0,8,121},
+        {0,8,57},{0,9,211},{17,7,17},{0,8,105},{0,8,41},{0,9,179},{0,8,9},
+        {0,8,137},{0,8,73},{0,9,243},{16,7,4},{0,8,85},{0,8,21},{16,8,258},
+        {19,7,43},{0,8,117},{0,8,53},{0,9,203},{17,7,13},{0,8,101},{0,8,37},
+        {0,9,171},{0,8,5},{0,8,133},{0,8,69},{0,9,235},{16,7,8},{0,8,93},
+        {0,8,29},{0,9,155},{20,7,83},{0,8,125},{0,8,61},{0,9,219},{18,7,23},
+        {0,8,109},{0,8,45},{0,9,187},{0,8,13},{0,8,141},{0,8,77},{0,9,251},
+        {16,7,3},{0,8,83},{0,8,19},{21,8,195},{19,7,35},{0,8,115},{0,8,51},
+        {0,9,199},{17,7,11},{0,8,99},{0,8,35},{0,9,167},{0,8,3},{0,8,131},
+        {0,8,67},{0,9,231},{16,7,7},{0,8,91},{0,8,27},{0,9,151},{20,7,67},
+        {0,8,123},{0,8,59},{0,9,215},{18,7,19},{0,8,107},{0,8,43},{0,9,183},
+        {0,8,11},{0,8,139},{0,8,75},{0,9,247},{16,7,5},{0,8,87},{0,8,23},
+        {64,8,0},{19,7,51},{0,8,119},{0,8,55},{0,9,207},{17,7,15},{0,8,103},
+        {0,8,39},{0,9,175},{0,8,7},{0,8,135},{0,8,71},{0,9,239},{16,7,9},
+        {0,8,95},{0,8,31},{0,9,159},{20,7,99},{0,8,127},{0,8,63},{0,9,223},
+        {18,7,27},{0,8,111},{0,8,47},{0,9,191},{0,8,15},{0,8,143},{0,8,79},
+        {0,9,255}
+    };
+
+    static const code distfix[32] = {
+        {16,5,1},{23,5,257},{19,5,17},{27,5,4097},{17,5,5},{25,5,1025},
+        {21,5,65},{29,5,16385},{16,5,3},{24,5,513},{20,5,33},{28,5,8193},
+        {18,5,9},{26,5,2049},{22,5,129},{64,5,0},{16,5,2},{23,5,385},
+        {19,5,25},{27,5,6145},{17,5,7},{25,5,1537},{21,5,97},{29,5,24577},
+        {16,5,4},{24,5,769},{20,5,49},{28,5,12289},{18,5,13},{26,5,3073},
+        {22,5,193},{64,5,0}
+    };
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/inflate.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,1585 @@
+/*
+ * 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.
+ */
+
+/* inflate.c -- zlib decompression
+ * Copyright (C) 1995-2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+ * Change history:
+ *
+ * 1.2.beta0    24 Nov 2002
+ * - First version -- complete rewrite of inflate to simplify code, avoid
+ *   creation of window when not needed, minimize use of window when it is
+ *   needed, make inffast.c even faster, implement gzip decoding, and to
+ *   improve code readability and style over the previous zlib inflate code
+ *
+ * 1.2.beta1    25 Nov 2002
+ * - Use pointers for available input and output checking in inffast.c
+ * - Remove input and output counters in inffast.c
+ * - Change inffast.c entry and loop from avail_in >= 7 to >= 6
+ * - Remove unnecessary second byte pull from length extra in inffast.c
+ * - Unroll direct copy to three copies per loop in inffast.c
+ *
+ * 1.2.beta2    4 Dec 2002
+ * - Change external routine names to reduce potential conflicts
+ * - Correct filename to inffixed.h for fixed tables in inflate.c
+ * - Make hbuf[] unsigned char to match parameter type in inflate.c
+ * - Change strm->next_out[-state->offset] to *(strm->next_out - state->offset)
+ *   to avoid negation problem on Alphas (64 bit) in inflate.c
+ *
+ * 1.2.beta3    22 Dec 2002
+ * - Add comments on state->bits assertion in inffast.c
+ * - Add comments on op field in inftrees.h
+ * - Fix bug in reuse of allocated window after inflateReset()
+ * - Remove bit fields--back to byte structure for speed
+ * - Remove distance extra == 0 check in inflate_fast()--only helps for lengths
+ * - Change post-increments to pre-increments in inflate_fast(), PPC biased?
+ * - Add compile time option, POSTINC, to use post-increments instead (Intel?)
+ * - Make MATCH copy in inflate() much faster for when inflate_fast() not used
+ * - Use local copies of stream next and avail values, as well as local bit
+ *   buffer and bit count in inflate()--for speed when inflate_fast() not used
+ *
+ * 1.2.beta4    1 Jan 2003
+ * - Split ptr - 257 statements in inflate_table() to avoid compiler warnings
+ * - Move a comment on output buffer sizes from inffast.c to inflate.c
+ * - Add comments in inffast.c to introduce the inflate_fast() routine
+ * - Rearrange window copies in inflate_fast() for speed and simplification
+ * - Unroll last copy for window match in inflate_fast()
+ * - Use local copies of window variables in inflate_fast() for speed
+ * - Pull out common wnext == 0 case for speed in inflate_fast()
+ * - Make op and len in inflate_fast() unsigned for consistency
+ * - Add FAR to lcode and dcode declarations in inflate_fast()
+ * - Simplified bad distance check in inflate_fast()
+ * - Added inflateBackInit(), inflateBack(), and inflateBackEnd() in new
+ *   source file infback.c to provide a call-back interface to inflate for
+ *   programs like gzip and unzip -- uses window as output buffer to avoid
+ *   window copying
+ *
+ * 1.2.beta5    1 Jan 2003
+ * - Improved inflateBack() interface to allow the caller to provide initial
+ *   input in strm.
+ * - Fixed stored blocks bug in inflateBack()
+ *
+ * 1.2.beta6    4 Jan 2003
+ * - Added comments in inffast.c on effectiveness of POSTINC
+ * - Typecasting all around to reduce compiler warnings
+ * - Changed loops from while (1) or do {} while (1) to for (;;), again to
+ *   make compilers happy
+ * - Changed type of window in inflateBackInit() to unsigned char *
+ *
+ * 1.2.beta7    27 Jan 2003
+ * - Changed many types to unsigned or unsigned short to avoid warnings
+ * - Added inflateCopy() function
+ *
+ * 1.2.0        9 Mar 2003
+ * - Changed inflateBack() interface to provide separate opaque descriptors
+ *   for the in() and out() functions
+ * - Changed inflateBack() argument and in_func typedef to swap the length
+ *   and buffer address return values for the input function
+ * - Check next_in and next_out for Z_NULL on entry to inflate()
+ *
+ * The history for versions after 1.2.0 are in ChangeLog in zlib distribution.
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+#include "inflate.h"
+#include "inffast.h"
+
+#ifdef MAKEFIXED
+#  ifndef BUILDFIXED
+#    define BUILDFIXED
+#  endif
+#endif
+
+/* function prototypes */
+local int inflateStateCheck OF((z_streamp strm));
+local void fixedtables OF((struct inflate_state FAR *state));
+local int updatewindow OF((z_streamp strm, const unsigned char FAR *end,
+                           unsigned copy));
+#ifdef BUILDFIXED
+   void makefixed OF((void));
+#endif
+local unsigned syncsearch OF((unsigned FAR *have, const unsigned char FAR *buf,
+                              unsigned len));
+
+local int inflateStateCheck(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+    if (strm == Z_NULL ||
+        strm->zalloc == (alloc_func)0 || strm->zfree == (free_func)0)
+        return 1;
+    state = (struct inflate_state FAR *)strm->state;
+    if (state == Z_NULL || state->strm != strm ||
+        state->mode < HEAD || state->mode > SYNC)
+        return 1;
+    return 0;
+}
+
+int ZEXPORT inflateResetKeep(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    strm->total_in = strm->total_out = state->total = 0;
+    strm->msg = Z_NULL;
+    if (state->wrap)        /* to support ill-conceived Java test suite */
+        strm->adler = state->wrap & 1;
+    state->mode = HEAD;
+    state->last = 0;
+    state->havedict = 0;
+    state->dmax = 32768U;
+    state->head = Z_NULL;
+    state->hold = 0;
+    state->bits = 0;
+    state->lencode = state->distcode = state->next = state->codes;
+    state->sane = 1;
+    state->back = -1;
+    Tracev((stderr, "inflate: reset\n"));
+    return Z_OK;
+}
+
+int ZEXPORT inflateReset(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    state->wsize = 0;
+    state->whave = 0;
+    state->wnext = 0;
+    return inflateResetKeep(strm);
+}
+
+int ZEXPORT inflateReset2(strm, windowBits)
+z_streamp strm;
+int windowBits;
+{
+    int wrap;
+    struct inflate_state FAR *state;
+
+    /* get the state */
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+
+    /* extract wrap request from windowBits parameter */
+    if (windowBits < 0) {
+        wrap = 0;
+        windowBits = -windowBits;
+    }
+    else {
+        wrap = (windowBits >> 4) + 5;
+#ifdef GUNZIP
+        if (windowBits < 48)
+            windowBits &= 15;
+#endif
+    }
+
+    /* set number of window bits, free window if different */
+    if (windowBits && (windowBits < 8 || windowBits > 15))
+        return Z_STREAM_ERROR;
+    if (state->window != Z_NULL && state->wbits != (unsigned)windowBits) {
+        ZFREE(strm, state->window);
+        state->window = Z_NULL;
+    }
+
+    /* update state and reset the rest of it */
+    state->wrap = wrap;
+    state->wbits = (unsigned)windowBits;
+    return inflateReset(strm);
+}
+
+int ZEXPORT inflateInit2_(strm, windowBits, version, stream_size)
+z_streamp strm;
+int windowBits;
+const char *version;
+int stream_size;
+{
+    int ret;
+    struct inflate_state FAR *state;
+
+    if (version == Z_NULL || version[0] != ZLIB_VERSION[0] ||
+        stream_size != (int)(sizeof(z_stream)))
+        return Z_VERSION_ERROR;
+    if (strm == Z_NULL) return Z_STREAM_ERROR;
+    strm->msg = Z_NULL;                 /* in case we return an error */
+    if (strm->zalloc == (alloc_func)0) {
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+        strm->zalloc = zcalloc;
+        strm->opaque = (voidpf)0;
+#endif
+    }
+    if (strm->zfree == (free_func)0)
+#ifdef Z_SOLO
+        return Z_STREAM_ERROR;
+#else
+        strm->zfree = zcfree;
+#endif
+    state = (struct inflate_state FAR *)
+            ZALLOC(strm, 1, sizeof(struct inflate_state));
+    if (state == Z_NULL) return Z_MEM_ERROR;
+    Tracev((stderr, "inflate: allocated\n"));
+    strm->state = (struct internal_state FAR *)state;
+    state->strm = strm;
+    state->window = Z_NULL;
+    state->mode = HEAD;     /* to pass state test in inflateReset2() */
+    ret = inflateReset2(strm, windowBits);
+    if (ret != Z_OK) {
+        ZFREE(strm, state);
+        strm->state = Z_NULL;
+    }
+    return ret;
+}
+
+int ZEXPORT inflateInit_(strm, version, stream_size)
+z_streamp strm;
+const char *version;
+int stream_size;
+{
+    return inflateInit2_(strm, DEF_WBITS, version, stream_size);
+}
+
+int ZEXPORT inflatePrime(strm, bits, value)
+z_streamp strm;
+int bits;
+int value;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (bits < 0) {
+        state->hold = 0;
+        state->bits = 0;
+        return Z_OK;
+    }
+    if (bits > 16 || state->bits + (uInt)bits > 32) return Z_STREAM_ERROR;
+    value &= (1L << bits) - 1;
+    state->hold += (unsigned)value << state->bits;
+    state->bits += (uInt)bits;
+    return Z_OK;
+}
+
+/*
+   Return state with length and distance decoding tables and index sizes set to
+   fixed code decoding.  Normally this returns fixed tables from inffixed.h.
+   If BUILDFIXED is defined, then instead this routine builds the tables the
+   first time it's called, and returns those tables the first time and
+   thereafter.  This reduces the size of the code by about 2K bytes, in
+   exchange for a little execution time.  However, BUILDFIXED should not be
+   used for threaded applications, since the rewriting of the tables and virgin
+   may not be thread-safe.
+ */
+local void fixedtables(state)
+struct inflate_state FAR *state;
+{
+#ifdef BUILDFIXED
+    static int virgin = 1;
+    static code *lenfix, *distfix;
+    static code fixed[544];
+
+    /* build fixed huffman tables if first call (may not be thread safe) */
+    if (virgin) {
+        unsigned sym, bits;
+        static code *next;
+
+        /* literal/length table */
+        sym = 0;
+        while (sym < 144) state->lens[sym++] = 8;
+        while (sym < 256) state->lens[sym++] = 9;
+        while (sym < 280) state->lens[sym++] = 7;
+        while (sym < 288) state->lens[sym++] = 8;
+        next = fixed;
+        lenfix = next;
+        bits = 9;
+        inflate_table(LENS, state->lens, 288, &(next), &(bits), state->work);
+
+        /* distance table */
+        sym = 0;
+        while (sym < 32) state->lens[sym++] = 5;
+        distfix = next;
+        bits = 5;
+        inflate_table(DISTS, state->lens, 32, &(next), &(bits), state->work);
+
+        /* do this just once */
+        virgin = 0;
+    }
+#else /* !BUILDFIXED */
+#   include "inffixed.h"
+#endif /* BUILDFIXED */
+    state->lencode = lenfix;
+    state->lenbits = 9;
+    state->distcode = distfix;
+    state->distbits = 5;
+}
+
+#ifdef MAKEFIXED
+#include <stdio.h>
+
+/*
+   Write out the inffixed.h that is #include'd above.  Defining MAKEFIXED also
+   defines BUILDFIXED, so the tables are built on the fly.  makefixed() writes
+   those tables to stdout, which would be piped to inffixed.h.  A small program
+   can simply call makefixed to do this:
+
+    void makefixed(void);
+
+    int main(void)
+    {
+        makefixed();
+        return 0;
+    }
+
+   Then that can be linked with zlib built with MAKEFIXED defined and run:
+
+    a.out > inffixed.h
+ */
+void makefixed()
+{
+    unsigned low, size;
+    struct inflate_state state;
+
+    fixedtables(&state);
+    puts("    /* inffixed.h -- table for decoding fixed codes");
+    puts("     * Generated automatically by makefixed().");
+    puts("     */");
+    puts("");
+    puts("    /* WARNING: this file should *not* be used by applications.");
+    puts("       It is part of the implementation of this library and is");
+    puts("       subject to change. Applications should only use zlib.h.");
+    puts("     */");
+    puts("");
+    size = 1U << 9;
+    printf("    static const code lenfix[%u] = {", size);
+    low = 0;
+    for (;;) {
+        if ((low % 7) == 0) printf("\n        ");
+        printf("{%u,%u,%d}", (low & 127) == 99 ? 64 : state.lencode[low].op,
+               state.lencode[low].bits, state.lencode[low].val);
+        if (++low == size) break;
+        putchar(',');
+    }
+    puts("\n    };");
+    size = 1U << 5;
+    printf("\n    static const code distfix[%u] = {", size);
+    low = 0;
+    for (;;) {
+        if ((low % 6) == 0) printf("\n        ");
+        printf("{%u,%u,%d}", state.distcode[low].op, state.distcode[low].bits,
+               state.distcode[low].val);
+        if (++low == size) break;
+        putchar(',');
+    }
+    puts("\n    };");
+}
+#endif /* MAKEFIXED */
+
+/*
+   Update the window with the last wsize (normally 32K) bytes written before
+   returning.  If window does not exist yet, create it.  This is only called
+   when a window is already in use, or when output has been written during this
+   inflate call, but the end of the deflate stream has not been reached yet.
+   It is also called to create a window for dictionary data when a dictionary
+   is loaded.
+
+   Providing output buffers larger than 32K to inflate() should provide a speed
+   advantage, since only the last 32K of output is copied to the sliding window
+   upon return from inflate(), and since all distances after the first 32K of
+   output will fall in the output data, making match copies simpler and faster.
+   The advantage may be dependent on the size of the processor's data caches.
+ */
+local int updatewindow(strm, end, copy)
+z_streamp strm;
+const Bytef *end;
+unsigned copy;
+{
+    struct inflate_state FAR *state;
+    unsigned dist;
+
+    state = (struct inflate_state FAR *)strm->state;
+
+    /* if it hasn't been done already, allocate space for the window */
+    if (state->window == Z_NULL) {
+        state->window = (unsigned char FAR *)
+                        ZALLOC(strm, 1U << state->wbits,
+                               sizeof(unsigned char));
+        if (state->window == Z_NULL) return 1;
+    }
+
+    /* if window not in use yet, initialize */
+    if (state->wsize == 0) {
+        state->wsize = 1U << state->wbits;
+        state->wnext = 0;
+        state->whave = 0;
+    }
+
+    /* copy state->wsize or less output bytes into the circular window */
+    if (copy >= state->wsize) {
+        zmemcpy(state->window, end - state->wsize, state->wsize);
+        state->wnext = 0;
+        state->whave = state->wsize;
+    }
+    else {
+        dist = state->wsize - state->wnext;
+        if (dist > copy) dist = copy;
+        zmemcpy(state->window + state->wnext, end - copy, dist);
+        copy -= dist;
+        if (copy) {
+            zmemcpy(state->window, end - copy, copy);
+            state->wnext = copy;
+            state->whave = state->wsize;
+        }
+        else {
+            state->wnext += dist;
+            if (state->wnext == state->wsize) state->wnext = 0;
+            if (state->whave < state->wsize) state->whave += dist;
+        }
+    }
+    return 0;
+}
+
+/* Macros for inflate(): */
+
+/* check function to use adler32() for zlib or crc32() for gzip */
+#ifdef GUNZIP
+#  define UPDATE(check, buf, len) \
+    (state->flags ? crc32(check, buf, len) : adler32(check, buf, len))
+#else
+#  define UPDATE(check, buf, len) adler32(check, buf, len)
+#endif
+
+/* check macros for header crc */
+#ifdef GUNZIP
+#  define CRC2(check, word) \
+    do { \
+        hbuf[0] = (unsigned char)(word); \
+        hbuf[1] = (unsigned char)((word) >> 8); \
+        check = crc32(check, hbuf, 2); \
+    } while (0)
+
+#  define CRC4(check, word) \
+    do { \
+        hbuf[0] = (unsigned char)(word); \
+        hbuf[1] = (unsigned char)((word) >> 8); \
+        hbuf[2] = (unsigned char)((word) >> 16); \
+        hbuf[3] = (unsigned char)((word) >> 24); \
+        check = crc32(check, hbuf, 4); \
+    } while (0)
+#endif
+
+/* Load registers with state in inflate() for speed */
+#define LOAD() \
+    do { \
+        put = strm->next_out; \
+        left = strm->avail_out; \
+        next = strm->next_in; \
+        have = strm->avail_in; \
+        hold = state->hold; \
+        bits = state->bits; \
+    } while (0)
+
+/* Restore state from registers in inflate() */
+#define RESTORE() \
+    do { \
+        strm->next_out = put; \
+        strm->avail_out = left; \
+        strm->next_in = next; \
+        strm->avail_in = have; \
+        state->hold = hold; \
+        state->bits = bits; \
+    } while (0)
+
+/* Clear the input bit accumulator */
+#define INITBITS() \
+    do { \
+        hold = 0; \
+        bits = 0; \
+    } while (0)
+
+/* Get a byte of input into the bit accumulator, or return from inflate()
+   if there is no input available. */
+#define PULLBYTE() \
+    do { \
+        if (have == 0) goto inf_leave; \
+        have--; \
+        hold += (unsigned long)(*next++) << bits; \
+        bits += 8; \
+    } while (0)
+
+/* Assure that there are at least n bits in the bit accumulator.  If there is
+   not enough available input to do that, then return from inflate(). */
+#define NEEDBITS(n) \
+    do { \
+        while (bits < (unsigned)(n)) \
+            PULLBYTE(); \
+    } while (0)
+
+/* Return the low n bits of the bit accumulator (n < 16) */
+#define BITS(n) \
+    ((unsigned)hold & ((1U << (n)) - 1))
+
+/* Remove n bits from the bit accumulator */
+#define DROPBITS(n) \
+    do { \
+        hold >>= (n); \
+        bits -= (unsigned)(n); \
+    } while (0)
+
+/* Remove zero to seven bits as needed to go to a byte boundary */
+#define BYTEBITS() \
+    do { \
+        hold >>= bits & 7; \
+        bits -= bits & 7; \
+    } while (0)
+
+/*
+   inflate() uses a state machine to process as much input data and generate as
+   much output data as possible before returning.  The state machine is
+   structured roughly as follows:
+
+    for (;;) switch (state) {
+    ...
+    case STATEn:
+        if (not enough input data or output space to make progress)
+            return;
+        ... make progress ...
+        state = STATEm;
+        break;
+    ...
+    }
+
+   so when inflate() is called again, the same case is attempted again, and
+   if the appropriate resources are provided, the machine proceeds to the
+   next state.  The NEEDBITS() macro is usually the way the state evaluates
+   whether it can proceed or should return.  NEEDBITS() does the return if
+   the requested bits are not available.  The typical use of the BITS macros
+   is:
+
+        NEEDBITS(n);
+        ... do something with BITS(n) ...
+        DROPBITS(n);
+
+   where NEEDBITS(n) either returns from inflate() if there isn't enough
+   input left to load n bits into the accumulator, or it continues.  BITS(n)
+   gives the low n bits in the accumulator.  When done, DROPBITS(n) drops
+   the low n bits off the accumulator.  INITBITS() clears the accumulator
+   and sets the number of available bits to zero.  BYTEBITS() discards just
+   enough bits to put the accumulator on a byte boundary.  After BYTEBITS()
+   and a NEEDBITS(8), then BITS(8) would return the next byte in the stream.
+
+   NEEDBITS(n) uses PULLBYTE() to get an available byte of input, or to return
+   if there is no input available.  The decoding of variable length codes uses
+   PULLBYTE() directly in order to pull just enough bytes to decode the next
+   code, and no more.
+
+   Some states loop until they get enough input, making sure that enough
+   state information is maintained to continue the loop where it left off
+   if NEEDBITS() returns in the loop.  For example, want, need, and keep
+   would all have to actually be part of the saved state in case NEEDBITS()
+   returns:
+
+    case STATEw:
+        while (want < need) {
+            NEEDBITS(n);
+            keep[want++] = BITS(n);
+            DROPBITS(n);
+        }
+        state = STATEx;
+    case STATEx:
+
+   As shown above, if the next state is also the next case, then the break
+   is omitted.
+
+   A state may also return if there is not enough output space available to
+   complete that state.  Those states are copying stored data, writing a
+   literal byte, and copying a matching string.
+
+   When returning, a "goto inf_leave" is used to update the total counters,
+   update the check value, and determine whether any progress has been made
+   during that inflate() call in order to return the proper return code.
+   Progress is defined as a change in either strm->avail_in or strm->avail_out.
+   When there is a window, goto inf_leave will update the window with the last
+   output written.  If a goto inf_leave occurs in the middle of decompression
+   and there is no window currently, goto inf_leave will create one and copy
+   output to the window for the next call of inflate().
+
+   In this implementation, the flush parameter of inflate() only affects the
+   return code (per zlib.h).  inflate() always writes as much as possible to
+   strm->next_out, given the space available and the provided input--the effect
+   documented in zlib.h of Z_SYNC_FLUSH.  Furthermore, inflate() always defers
+   the allocation of and copying into a sliding window until necessary, which
+   provides the effect documented in zlib.h for Z_FINISH when the entire input
+   stream available.  So the only thing the flush parameter actually does is:
+   when flush is set to Z_FINISH, inflate() cannot return Z_OK.  Instead it
+   will return Z_BUF_ERROR if it has not reached the end of the stream.
+ */
+
+int ZEXPORT inflate(strm, flush)
+z_streamp strm;
+int flush;
+{
+    struct inflate_state FAR *state;
+    z_const unsigned char FAR *next;    /* next input */
+    unsigned char FAR *put;     /* next output */
+    unsigned have, left;        /* available input and output */
+    unsigned long hold;         /* bit buffer */
+    unsigned bits;              /* bits in bit buffer */
+    unsigned in, out;           /* save starting available input and output */
+    unsigned copy;              /* number of stored or match bytes to copy */
+    unsigned char FAR *from;    /* where to copy match bytes from */
+    code here;                  /* current decoding table entry */
+    code last;                  /* parent table entry */
+    unsigned len;               /* length to copy for repeats, bits to drop */
+    int ret;                    /* return code */
+#ifdef GUNZIP
+    unsigned char hbuf[4];      /* buffer for gzip header crc calculation */
+#endif
+    static const unsigned short order[19] = /* permutation of code lengths */
+        {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15};
+
+    if (inflateStateCheck(strm) || strm->next_out == Z_NULL ||
+        (strm->next_in == Z_NULL && strm->avail_in != 0))
+        return Z_STREAM_ERROR;
+
+    state = (struct inflate_state FAR *)strm->state;
+    if (state->mode == TYPE) state->mode = TYPEDO;      /* skip check */
+    LOAD();
+    in = have;
+    out = left;
+    ret = Z_OK;
+    for (;;)
+        switch (state->mode) {
+        case HEAD:
+            if (state->wrap == 0) {
+                state->mode = TYPEDO;
+                break;
+            }
+            NEEDBITS(16);
+#ifdef GUNZIP
+            if ((state->wrap & 2) && hold == 0x8b1f) {  /* gzip header */
+                if (state->wbits == 0)
+                    state->wbits = 15;
+                state->check = crc32(0L, Z_NULL, 0);
+                CRC2(state->check, hold);
+                INITBITS();
+                state->mode = FLAGS;
+                break;
+            }
+            state->flags = 0;           /* expect zlib header */
+            if (state->head != Z_NULL)
+                state->head->done = -1;
+            if (!(state->wrap & 1) ||   /* check if zlib header allowed */
+#else
+            if (
+#endif
+                ((BITS(8) << 8) + (hold >> 8)) % 31) {
+                strm->msg = (char *)"incorrect header check";
+                state->mode = BAD;
+                break;
+            }
+            if (BITS(4) != Z_DEFLATED) {
+                strm->msg = (char *)"unknown compression method";
+                state->mode = BAD;
+                break;
+            }
+            DROPBITS(4);
+            len = BITS(4) + 8;
+            if (state->wbits == 0)
+                state->wbits = len;
+            if (len > 15 || len > state->wbits) {
+                strm->msg = (char *)"invalid window size";
+                state->mode = BAD;
+                break;
+            }
+            state->dmax = 1U << len;
+            Tracev((stderr, "inflate:   zlib header ok\n"));
+            strm->adler = state->check = adler32(0L, Z_NULL, 0);
+            state->mode = hold & 0x200 ? DICTID : TYPE;
+            INITBITS();
+            break;
+#ifdef GUNZIP
+        case FLAGS:
+            NEEDBITS(16);
+            state->flags = (int)(hold);
+            if ((state->flags & 0xff) != Z_DEFLATED) {
+                strm->msg = (char *)"unknown compression method";
+                state->mode = BAD;
+                break;
+            }
+            if (state->flags & 0xe000) {
+                strm->msg = (char *)"unknown header flags set";
+                state->mode = BAD;
+                break;
+            }
+            if (state->head != Z_NULL)
+                state->head->text = (int)((hold >> 8) & 1);
+            if ((state->flags & 0x0200) && (state->wrap & 4))
+                CRC2(state->check, hold);
+            INITBITS();
+            state->mode = TIME;
+        case TIME:
+            NEEDBITS(32);
+            if (state->head != Z_NULL)
+                state->head->time = hold;
+            if ((state->flags & 0x0200) && (state->wrap & 4))
+                CRC4(state->check, hold);
+            INITBITS();
+            state->mode = OS;
+        case OS:
+            NEEDBITS(16);
+            if (state->head != Z_NULL) {
+                state->head->xflags = (int)(hold & 0xff);
+                state->head->os = (int)(hold >> 8);
+            }
+            if ((state->flags & 0x0200) && (state->wrap & 4))
+                CRC2(state->check, hold);
+            INITBITS();
+            state->mode = EXLEN;
+        case EXLEN:
+            if (state->flags & 0x0400) {
+                NEEDBITS(16);
+                state->length = (unsigned)(hold);
+                if (state->head != Z_NULL)
+                    state->head->extra_len = (unsigned)hold;
+                if ((state->flags & 0x0200) && (state->wrap & 4))
+                    CRC2(state->check, hold);
+                INITBITS();
+            }
+            else if (state->head != Z_NULL)
+                state->head->extra = Z_NULL;
+            state->mode = EXTRA;
+        case EXTRA:
+            if (state->flags & 0x0400) {
+                copy = state->length;
+                if (copy > have) copy = have;
+                if (copy) {
+                    if (state->head != Z_NULL &&
+                        state->head->extra != Z_NULL) {
+                        len = state->head->extra_len - state->length;
+                        zmemcpy(state->head->extra + len, next,
+                                len + copy > state->head->extra_max ?
+                                state->head->extra_max - len : copy);
+                    }
+                    if ((state->flags & 0x0200) && (state->wrap & 4))
+                        state->check = crc32(state->check, next, copy);
+                    have -= copy;
+                    next += copy;
+                    state->length -= copy;
+                }
+                if (state->length) goto inf_leave;
+            }
+            state->length = 0;
+            state->mode = NAME;
+        case NAME:
+            if (state->flags & 0x0800) {
+                if (have == 0) goto inf_leave;
+                copy = 0;
+                do {
+                    len = (unsigned)(next[copy++]);
+                    if (state->head != Z_NULL &&
+                            state->head->name != Z_NULL &&
+                            state->length < state->head->name_max)
+                        state->head->name[state->length++] = (Bytef)len;
+                } while (len && copy < have);
+                if ((state->flags & 0x0200) && (state->wrap & 4))
+                    state->check = crc32(state->check, next, copy);
+                have -= copy;
+                next += copy;
+                if (len) goto inf_leave;
+            }
+            else if (state->head != Z_NULL)
+                state->head->name = Z_NULL;
+            state->length = 0;
+            state->mode = COMMENT;
+        case COMMENT:
+            if (state->flags & 0x1000) {
+                if (have == 0) goto inf_leave;
+                copy = 0;
+                do {
+                    len = (unsigned)(next[copy++]);
+                    if (state->head != Z_NULL &&
+                            state->head->comment != Z_NULL &&
+                            state->length < state->head->comm_max)
+                        state->head->comment[state->length++] = (Bytef)len;
+                } while (len && copy < have);
+                if ((state->flags & 0x0200) && (state->wrap & 4))
+                    state->check = crc32(state->check, next, copy);
+                have -= copy;
+                next += copy;
+                if (len) goto inf_leave;
+            }
+            else if (state->head != Z_NULL)
+                state->head->comment = Z_NULL;
+            state->mode = HCRC;
+        case HCRC:
+            if (state->flags & 0x0200) {
+                NEEDBITS(16);
+                if ((state->wrap & 4) && hold != (state->check & 0xffff)) {
+                    strm->msg = (char *)"header crc mismatch";
+                    state->mode = BAD;
+                    break;
+                }
+                INITBITS();
+            }
+            if (state->head != Z_NULL) {
+                state->head->hcrc = (int)((state->flags >> 9) & 1);
+                state->head->done = 1;
+            }
+            strm->adler = state->check = crc32(0L, Z_NULL, 0);
+            state->mode = TYPE;
+            break;
+#endif
+        case DICTID:
+            NEEDBITS(32);
+            strm->adler = state->check = ZSWAP32(hold);
+            INITBITS();
+            state->mode = DICT;
+        case DICT:
+            if (state->havedict == 0) {
+                RESTORE();
+                return Z_NEED_DICT;
+            }
+            strm->adler = state->check = adler32(0L, Z_NULL, 0);
+            state->mode = TYPE;
+        case TYPE:
+            if (flush == Z_BLOCK || flush == Z_TREES) goto inf_leave;
+        case TYPEDO:
+            if (state->last) {
+                BYTEBITS();
+                state->mode = CHECK;
+                break;
+            }
+            NEEDBITS(3);
+            state->last = BITS(1);
+            DROPBITS(1);
+            switch (BITS(2)) {
+            case 0:                             /* stored block */
+                Tracev((stderr, "inflate:     stored block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = STORED;
+                break;
+            case 1:                             /* fixed block */
+                fixedtables(state);
+                Tracev((stderr, "inflate:     fixed codes block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = LEN_;             /* decode codes */
+                if (flush == Z_TREES) {
+                    DROPBITS(2);
+                    goto inf_leave;
+                }
+                break;
+            case 2:                             /* dynamic block */
+                Tracev((stderr, "inflate:     dynamic codes block%s\n",
+                        state->last ? " (last)" : ""));
+                state->mode = TABLE;
+                break;
+            case 3:
+                strm->msg = (char *)"invalid block type";
+                state->mode = BAD;
+            }
+            DROPBITS(2);
+            break;
+        case STORED:
+            BYTEBITS();                         /* go to byte boundary */
+            NEEDBITS(32);
+            if ((hold & 0xffff) != ((hold >> 16) ^ 0xffff)) {
+                strm->msg = (char *)"invalid stored block lengths";
+                state->mode = BAD;
+                break;
+            }
+            state->length = (unsigned)hold & 0xffff;
+            Tracev((stderr, "inflate:       stored length %u\n",
+                    state->length));
+            INITBITS();
+            state->mode = COPY_;
+            if (flush == Z_TREES) goto inf_leave;
+        case COPY_:
+            state->mode = COPY;
+        case COPY:
+            copy = state->length;
+            if (copy) {
+                if (copy > have) copy = have;
+                if (copy > left) copy = left;
+                if (copy == 0) goto inf_leave;
+                zmemcpy(put, next, copy);
+                have -= copy;
+                next += copy;
+                left -= copy;
+                put += copy;
+                state->length -= copy;
+                break;
+            }
+            Tracev((stderr, "inflate:       stored end\n"));
+            state->mode = TYPE;
+            break;
+        case TABLE:
+            NEEDBITS(14);
+            state->nlen = BITS(5) + 257;
+            DROPBITS(5);
+            state->ndist = BITS(5) + 1;
+            DROPBITS(5);
+            state->ncode = BITS(4) + 4;
+            DROPBITS(4);
+#ifndef PKZIP_BUG_WORKAROUND
+            if (state->nlen > 286 || state->ndist > 30) {
+                strm->msg = (char *)"too many length or distance symbols";
+                state->mode = BAD;
+                break;
+            }
+#endif
+            Tracev((stderr, "inflate:       table sizes ok\n"));
+            state->have = 0;
+            state->mode = LENLENS;
+        case LENLENS:
+            while (state->have < state->ncode) {
+                NEEDBITS(3);
+                state->lens[order[state->have++]] = (unsigned short)BITS(3);
+                DROPBITS(3);
+            }
+            while (state->have < 19)
+                state->lens[order[state->have++]] = 0;
+            state->next = state->codes;
+            state->lencode = (const code FAR *)(state->next);
+            state->lenbits = 7;
+            ret = inflate_table(CODES, state->lens, 19, &(state->next),
+                                &(state->lenbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid code lengths set";
+                state->mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       code lengths ok\n"));
+            state->have = 0;
+            state->mode = CODELENS;
+        case CODELENS:
+            while (state->have < state->nlen + state->ndist) {
+                for (;;) {
+                    here = state->lencode[BITS(state->lenbits)];
+                    if ((unsigned)(here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                if (here.val < 16) {
+                    DROPBITS(here.bits);
+                    state->lens[state->have++] = here.val;
+                }
+                else {
+                    if (here.val == 16) {
+                        NEEDBITS(here.bits + 2);
+                        DROPBITS(here.bits);
+                        if (state->have == 0) {
+                            strm->msg = (char *)"invalid bit length repeat";
+                            state->mode = BAD;
+                            break;
+                        }
+                        len = state->lens[state->have - 1];
+                        copy = 3 + BITS(2);
+                        DROPBITS(2);
+                    }
+                    else if (here.val == 17) {
+                        NEEDBITS(here.bits + 3);
+                        DROPBITS(here.bits);
+                        len = 0;
+                        copy = 3 + BITS(3);
+                        DROPBITS(3);
+                    }
+                    else {
+                        NEEDBITS(here.bits + 7);
+                        DROPBITS(here.bits);
+                        len = 0;
+                        copy = 11 + BITS(7);
+                        DROPBITS(7);
+                    }
+                    if (state->have + copy > state->nlen + state->ndist) {
+                        strm->msg = (char *)"invalid bit length repeat";
+                        state->mode = BAD;
+                        break;
+                    }
+                    while (copy--)
+                        state->lens[state->have++] = (unsigned short)len;
+                }
+            }
+
+            /* handle error breaks in while */
+            if (state->mode == BAD) break;
+
+            /* check for end-of-block code (better have one) */
+            if (state->lens[256] == 0) {
+                strm->msg = (char *)"invalid code -- missing end-of-block";
+                state->mode = BAD;
+                break;
+            }
+
+            /* build code tables -- note: do not change the lenbits or distbits
+               values here (9 and 6) without reading the comments in inftrees.h
+               concerning the ENOUGH constants, which depend on those values */
+            state->next = state->codes;
+            state->lencode = (const code FAR *)(state->next);
+            state->lenbits = 9;
+            ret = inflate_table(LENS, state->lens, state->nlen, &(state->next),
+                                &(state->lenbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid literal/lengths set";
+                state->mode = BAD;
+                break;
+            }
+            state->distcode = (const code FAR *)(state->next);
+            state->distbits = 6;
+            ret = inflate_table(DISTS, state->lens + state->nlen, state->ndist,
+                            &(state->next), &(state->distbits), state->work);
+            if (ret) {
+                strm->msg = (char *)"invalid distances set";
+                state->mode = BAD;
+                break;
+            }
+            Tracev((stderr, "inflate:       codes ok\n"));
+            state->mode = LEN_;
+            if (flush == Z_TREES) goto inf_leave;
+        case LEN_:
+            state->mode = LEN;
+        case LEN:
+            if (have >= 6 && left >= 258) {
+                RESTORE();
+                inflate_fast(strm, out);
+                LOAD();
+                if (state->mode == TYPE)
+                    state->back = -1;
+                break;
+            }
+            state->back = 0;
+            for (;;) {
+                here = state->lencode[BITS(state->lenbits)];
+                if ((unsigned)(here.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if (here.op && (here.op & 0xf0) == 0) {
+                last = here;
+                for (;;) {
+                    here = state->lencode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+                state->back += last.bits;
+            }
+            DROPBITS(here.bits);
+            state->back += here.bits;
+            state->length = (unsigned)here.val;
+            if ((int)(here.op) == 0) {
+                Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
+                        "inflate:         literal '%c'\n" :
+                        "inflate:         literal 0x%02x\n", here.val));
+                state->mode = LIT;
+                break;
+            }
+            if (here.op & 32) {
+                Tracevv((stderr, "inflate:         end of block\n"));
+                state->back = -1;
+                state->mode = TYPE;
+                break;
+            }
+            if (here.op & 64) {
+                strm->msg = (char *)"invalid literal/length code";
+                state->mode = BAD;
+                break;
+            }
+            state->extra = (unsigned)(here.op) & 15;
+            state->mode = LENEXT;
+        case LENEXT:
+            if (state->extra) {
+                NEEDBITS(state->extra);
+                state->length += BITS(state->extra);
+                DROPBITS(state->extra);
+                state->back += state->extra;
+            }
+            Tracevv((stderr, "inflate:         length %u\n", state->length));
+            state->was = state->length;
+            state->mode = DIST;
+        case DIST:
+            for (;;) {
+                here = state->distcode[BITS(state->distbits)];
+                if ((unsigned)(here.bits) <= bits) break;
+                PULLBYTE();
+            }
+            if ((here.op & 0xf0) == 0) {
+                last = here;
+                for (;;) {
+                    here = state->distcode[last.val +
+                            (BITS(last.bits + last.op) >> last.bits)];
+                    if ((unsigned)(last.bits + here.bits) <= bits) break;
+                    PULLBYTE();
+                }
+                DROPBITS(last.bits);
+                state->back += last.bits;
+            }
+            DROPBITS(here.bits);
+            state->back += here.bits;
+            if (here.op & 64) {
+                strm->msg = (char *)"invalid distance code";
+                state->mode = BAD;
+                break;
+            }
+            state->offset = (unsigned)here.val;
+            state->extra = (unsigned)(here.op) & 15;
+            state->mode = DISTEXT;
+        case DISTEXT:
+            if (state->extra) {
+                NEEDBITS(state->extra);
+                state->offset += BITS(state->extra);
+                DROPBITS(state->extra);
+                state->back += state->extra;
+            }
+#ifdef INFLATE_STRICT
+            if (state->offset > state->dmax) {
+                strm->msg = (char *)"invalid distance too far back";
+                state->mode = BAD;
+                break;
+            }
+#endif
+            Tracevv((stderr, "inflate:         distance %u\n", state->offset));
+            state->mode = MATCH;
+        case MATCH:
+            if (left == 0) goto inf_leave;
+            copy = out - left;
+            if (state->offset > copy) {         /* copy from window */
+                copy = state->offset - copy;
+                if (copy > state->whave) {
+                    if (state->sane) {
+                        strm->msg = (char *)"invalid distance too far back";
+                        state->mode = BAD;
+                        break;
+                    }
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+                    Trace((stderr, "inflate.c too far\n"));
+                    copy -= state->whave;
+                    if (copy > state->length) copy = state->length;
+                    if (copy > left) copy = left;
+                    left -= copy;
+                    state->length -= copy;
+                    do {
+                        *put++ = 0;
+                    } while (--copy);
+                    if (state->length == 0) state->mode = LEN;
+                    break;
+#endif
+                }
+                if (copy > state->wnext) {
+                    copy -= state->wnext;
+                    from = state->window + (state->wsize - copy);
+                }
+                else
+                    from = state->window + (state->wnext - copy);
+                if (copy > state->length) copy = state->length;
+            }
+            else {                              /* copy from output */
+                from = put - state->offset;
+                copy = state->length;
+            }
+            if (copy > left) copy = left;
+            left -= copy;
+            state->length -= copy;
+            do {
+                *put++ = *from++;
+            } while (--copy);
+            if (state->length == 0) state->mode = LEN;
+            break;
+        case LIT:
+            if (left == 0) goto inf_leave;
+            *put++ = (unsigned char)(state->length);
+            left--;
+            state->mode = LEN;
+            break;
+        case CHECK:
+            if (state->wrap) {
+                NEEDBITS(32);
+                out -= left;
+                strm->total_out += out;
+                state->total += out;
+                if ((state->wrap & 4) && out)
+                    strm->adler = state->check =
+                        UPDATE(state->check, put - out, out);
+                out = left;
+                if ((state->wrap & 4) && (
+#ifdef GUNZIP
+                     state->flags ? hold :
+#endif
+                     ZSWAP32(hold)) != state->check) {
+                    strm->msg = (char *)"incorrect data check";
+                    state->mode = BAD;
+                    break;
+                }
+                INITBITS();
+                Tracev((stderr, "inflate:   check matches trailer\n"));
+            }
+#ifdef GUNZIP
+            state->mode = LENGTH;
+        case LENGTH:
+            if (state->wrap && state->flags) {
+                NEEDBITS(32);
+                if (hold != (state->total & 0xffffffffUL)) {
+                    strm->msg = (char *)"incorrect length check";
+                    state->mode = BAD;
+                    break;
+                }
+                INITBITS();
+                Tracev((stderr, "inflate:   length matches trailer\n"));
+            }
+#endif
+            state->mode = DONE;
+        case DONE:
+            ret = Z_STREAM_END;
+            goto inf_leave;
+        case BAD:
+            ret = Z_DATA_ERROR;
+            goto inf_leave;
+        case MEM:
+            return Z_MEM_ERROR;
+        case SYNC:
+        default:
+            return Z_STREAM_ERROR;
+        }
+
+    /*
+       Return from inflate(), updating the total counts and the check value.
+       If there was no progress during the inflate() call, return a buffer
+       error.  Call updatewindow() to create and/or update the window state.
+       Note: a memory error from inflate() is non-recoverable.
+     */
+  inf_leave:
+    RESTORE();
+    if (state->wsize || (out != strm->avail_out && state->mode < BAD &&
+            (state->mode < CHECK || flush != Z_FINISH)))
+        if (updatewindow(strm, strm->next_out, out - strm->avail_out)) {
+            state->mode = MEM;
+            return Z_MEM_ERROR;
+        }
+    in -= strm->avail_in;
+    out -= strm->avail_out;
+    strm->total_in += in;
+    strm->total_out += out;
+    state->total += out;
+    if ((state->wrap & 4) && out)
+        strm->adler = state->check =
+            UPDATE(state->check, strm->next_out - out, out);
+    strm->data_type = (int)state->bits + (state->last ? 64 : 0) +
+                      (state->mode == TYPE ? 128 : 0) +
+                      (state->mode == LEN_ || state->mode == COPY_ ? 256 : 0);
+    if (((in == 0 && out == 0) || flush == Z_FINISH) && ret == Z_OK)
+        ret = Z_BUF_ERROR;
+    return ret;
+}
+
+int ZEXPORT inflateEnd(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+    if (inflateStateCheck(strm))
+        return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (state->window != Z_NULL) ZFREE(strm, state->window);
+    ZFREE(strm, strm->state);
+    strm->state = Z_NULL;
+    Tracev((stderr, "inflate: end\n"));
+    return Z_OK;
+}
+
+int ZEXPORT inflateGetDictionary(strm, dictionary, dictLength)
+z_streamp strm;
+Bytef *dictionary;
+uInt *dictLength;
+{
+    struct inflate_state FAR *state;
+
+    /* check state */
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+
+    /* copy dictionary */
+    if (state->whave && dictionary != Z_NULL) {
+        zmemcpy(dictionary, state->window + state->wnext,
+                state->whave - state->wnext);
+        zmemcpy(dictionary + state->whave - state->wnext,
+                state->window, state->wnext);
+    }
+    if (dictLength != Z_NULL)
+        *dictLength = state->whave;
+    return Z_OK;
+}
+
+int ZEXPORT inflateSetDictionary(strm, dictionary, dictLength)
+z_streamp strm;
+const Bytef *dictionary;
+uInt dictLength;
+{
+    struct inflate_state FAR *state;
+    unsigned long dictid;
+    int ret;
+
+    /* check state */
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (state->wrap != 0 && state->mode != DICT)
+        return Z_STREAM_ERROR;
+
+    /* check for correct dictionary identifier */
+    if (state->mode == DICT) {
+        dictid = adler32(0L, Z_NULL, 0);
+        dictid = adler32(dictid, dictionary, dictLength);
+        if (dictid != state->check)
+            return Z_DATA_ERROR;
+    }
+
+    /* copy dictionary to window using updatewindow(), which will amend the
+       existing dictionary if appropriate */
+    ret = updatewindow(strm, dictionary + dictLength, dictLength);
+    if (ret) {
+        state->mode = MEM;
+        return Z_MEM_ERROR;
+    }
+    state->havedict = 1;
+    Tracev((stderr, "inflate:   dictionary set\n"));
+    return Z_OK;
+}
+
+int ZEXPORT inflateGetHeader(strm, head)
+z_streamp strm;
+gz_headerp head;
+{
+    struct inflate_state FAR *state;
+
+    /* check state */
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if ((state->wrap & 2) == 0) return Z_STREAM_ERROR;
+
+    /* save header structure */
+    state->head = head;
+    head->done = 0;
+    return Z_OK;
+}
+
+/*
+   Search buf[0..len-1] for the pattern: 0, 0, 0xff, 0xff.  Return when found
+   or when out of input.  When called, *have is the number of pattern bytes
+   found in order so far, in 0..3.  On return *have is updated to the new
+   state.  If on return *have equals four, then the pattern was found and the
+   return value is how many bytes were read including the last byte of the
+   pattern.  If *have is less than four, then the pattern has not been found
+   yet and the return value is len.  In the latter case, syncsearch() can be
+   called again with more data and the *have state.  *have is initialized to
+   zero for the first call.
+ */
+local unsigned syncsearch(have, buf, len)
+unsigned FAR *have;
+const unsigned char FAR *buf;
+unsigned len;
+{
+    unsigned got;
+    unsigned next;
+
+    got = *have;
+    next = 0;
+    while (next < len && got < 4) {
+        if ((int)(buf[next]) == (got < 2 ? 0 : 0xff))
+            got++;
+        else if (buf[next])
+            got = 0;
+        else
+            got = 4 - got;
+        next++;
+    }
+    *have = got;
+    return next;
+}
+
+int ZEXPORT inflateSync(strm)
+z_streamp strm;
+{
+    unsigned len;               /* number of bytes to look at or looked at */
+    unsigned long in, out;      /* temporary to save total_in and total_out */
+    unsigned char buf[4];       /* to restore bit buffer to byte string */
+    struct inflate_state FAR *state;
+
+    /* check parameters */
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (strm->avail_in == 0 && state->bits < 8) return Z_BUF_ERROR;
+
+    /* if first time, start search in bit buffer */
+    if (state->mode != SYNC) {
+        state->mode = SYNC;
+        state->hold <<= state->bits & 7;
+        state->bits -= state->bits & 7;
+        len = 0;
+        while (state->bits >= 8) {
+            buf[len++] = (unsigned char)(state->hold);
+            state->hold >>= 8;
+            state->bits -= 8;
+        }
+        state->have = 0;
+        syncsearch(&(state->have), buf, len);
+    }
+
+    /* search available input */
+    len = syncsearch(&(state->have), strm->next_in, strm->avail_in);
+    strm->avail_in -= len;
+    strm->next_in += len;
+    strm->total_in += len;
+
+    /* return no joy or set up to restart inflate() on a new block */
+    if (state->have != 4) return Z_DATA_ERROR;
+    in = strm->total_in;  out = strm->total_out;
+    inflateReset(strm);
+    strm->total_in = in;  strm->total_out = out;
+    state->mode = TYPE;
+    return Z_OK;
+}
+
+/*
+   Returns true if inflate is currently at the end of a block generated by
+   Z_SYNC_FLUSH or Z_FULL_FLUSH. This function is used by one PPP
+   implementation to provide an additional safety check. PPP uses
+   Z_SYNC_FLUSH but removes the length bytes of the resulting empty stored
+   block. When decompressing, PPP checks that at the end of input packet,
+   inflate is waiting for these length bytes.
+ */
+int ZEXPORT inflateSyncPoint(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    return state->mode == STORED && state->bits == 0;
+}
+
+int ZEXPORT inflateCopy(dest, source)
+z_streamp dest;
+z_streamp source;
+{
+    struct inflate_state FAR *state;
+    struct inflate_state FAR *copy;
+    unsigned char FAR *window;
+    unsigned wsize;
+
+    /* check input */
+    if (inflateStateCheck(source) || dest == Z_NULL)
+        return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)source->state;
+
+    /* allocate space */
+    copy = (struct inflate_state FAR *)
+           ZALLOC(source, 1, sizeof(struct inflate_state));
+    if (copy == Z_NULL) return Z_MEM_ERROR;
+    window = Z_NULL;
+    if (state->window != Z_NULL) {
+        window = (unsigned char FAR *)
+                 ZALLOC(source, 1U << state->wbits, sizeof(unsigned char));
+        if (window == Z_NULL) {
+            ZFREE(source, copy);
+            return Z_MEM_ERROR;
+        }
+    }
+
+    /* copy state */
+    zmemcpy((voidpf)dest, (voidpf)source, sizeof(z_stream));
+    zmemcpy((voidpf)copy, (voidpf)state, sizeof(struct inflate_state));
+    copy->strm = dest;
+    if (state->lencode >= state->codes &&
+        state->lencode <= state->codes + ENOUGH - 1) {
+        copy->lencode = copy->codes + (state->lencode - state->codes);
+        copy->distcode = copy->codes + (state->distcode - state->codes);
+    }
+    copy->next = copy->codes + (state->next - state->codes);
+    if (window != Z_NULL) {
+        wsize = 1U << state->wbits;
+        zmemcpy(window, state->window, wsize);
+    }
+    copy->window = window;
+    dest->state = (struct internal_state FAR *)copy;
+    return Z_OK;
+}
+
+int ZEXPORT inflateUndermine(strm, subvert)
+z_streamp strm;
+int subvert;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
+    state->sane = !subvert;
+    return Z_OK;
+#else
+    (void)subvert;
+    state->sane = 1;
+    return Z_DATA_ERROR;
+#endif
+}
+
+int ZEXPORT inflateValidate(strm, check)
+z_streamp strm;
+int check;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm)) return Z_STREAM_ERROR;
+    state = (struct inflate_state FAR *)strm->state;
+    if (check)
+        state->wrap |= 4;
+    else
+        state->wrap &= ~4;
+    return Z_OK;
+}
+
+long ZEXPORT inflateMark(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+
+    if (inflateStateCheck(strm))
+        return -(1L << 16);
+    state = (struct inflate_state FAR *)strm->state;
+    return (long)(((unsigned long)((long)state->back)) << 16) +
+        (state->mode == COPY ? state->length :
+            (state->mode == MATCH ? state->was - state->length : 0));
+}
+
+unsigned long ZEXPORT inflateCodesUsed(strm)
+z_streamp strm;
+{
+    struct inflate_state FAR *state;
+    if (inflateStateCheck(strm)) return (unsigned long)-1;
+    state = (struct inflate_state FAR *)strm->state;
+    return (unsigned long)(state->next - state->codes);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/inflate.h	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,149 @@
+/*
+ * 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.
+ */
+
+/* inflate.h -- internal inflate state definition
+ * Copyright (C) 1995-2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* define NO_GZIP when compiling if you want to disable gzip header and
+   trailer decoding by inflate().  NO_GZIP would be used to avoid linking in
+   the crc code when it is not needed.  For shared libraries, gzip decoding
+   should be left enabled. */
+#ifndef NO_GZIP
+#  define GUNZIP
+#endif
+
+/* Possible inflate modes between inflate() calls */
+typedef enum {
+    HEAD = 16180,   /* i: waiting for magic header */
+    FLAGS,      /* i: waiting for method and flags (gzip) */
+    TIME,       /* i: waiting for modification time (gzip) */
+    OS,         /* i: waiting for extra flags and operating system (gzip) */
+    EXLEN,      /* i: waiting for extra length (gzip) */
+    EXTRA,      /* i: waiting for extra bytes (gzip) */
+    NAME,       /* i: waiting for end of file name (gzip) */
+    COMMENT,    /* i: waiting for end of comment (gzip) */
+    HCRC,       /* i: waiting for header crc (gzip) */
+    DICTID,     /* i: waiting for dictionary check value */
+    DICT,       /* waiting for inflateSetDictionary() call */
+        TYPE,       /* i: waiting for type bits, including last-flag bit */
+        TYPEDO,     /* i: same, but skip check to exit inflate on new block */
+        STORED,     /* i: waiting for stored size (length and complement) */
+        COPY_,      /* i/o: same as COPY below, but only first time in */
+        COPY,       /* i/o: waiting for input or output to copy stored block */
+        TABLE,      /* i: waiting for dynamic block table lengths */
+        LENLENS,    /* i: waiting for code length code lengths */
+        CODELENS,   /* i: waiting for length/lit and distance code lengths */
+            LEN_,       /* i: same as LEN below, but only first time in */
+            LEN,        /* i: waiting for length/lit/eob code */
+            LENEXT,     /* i: waiting for length extra bits */
+            DIST,       /* i: waiting for distance code */
+            DISTEXT,    /* i: waiting for distance extra bits */
+            MATCH,      /* o: waiting for output space to copy string */
+            LIT,        /* o: waiting for output space to write literal */
+    CHECK,      /* i: waiting for 32-bit check value */
+    LENGTH,     /* i: waiting for 32-bit length (gzip) */
+    DONE,       /* finished check, done -- remain here until reset */
+    BAD,        /* got a data error -- remain here until reset */
+    MEM,        /* got an inflate() memory error -- remain here until reset */
+    SYNC        /* looking for synchronization bytes to restart inflate() */
+} inflate_mode;
+
+/*
+    State transitions between above modes -
+
+    (most modes can go to BAD or MEM on error -- not shown for clarity)
+
+    Process header:
+        HEAD -> (gzip) or (zlib) or (raw)
+        (gzip) -> FLAGS -> TIME -> OS -> EXLEN -> EXTRA -> NAME -> COMMENT ->
+                  HCRC -> TYPE
+        (zlib) -> DICTID or TYPE
+        DICTID -> DICT -> TYPE
+        (raw) -> TYPEDO
+    Read deflate blocks:
+            TYPE -> TYPEDO -> STORED or TABLE or LEN_ or CHECK
+            STORED -> COPY_ -> COPY -> TYPE
+            TABLE -> LENLENS -> CODELENS -> LEN_
+            LEN_ -> LEN
+    Read deflate codes in fixed or dynamic block:
+                LEN -> LENEXT or LIT or TYPE
+                LENEXT -> DIST -> DISTEXT -> MATCH -> LEN
+                LIT -> LEN
+    Process trailer:
+        CHECK -> LENGTH -> DONE
+ */
+
+/* State maintained between inflate() calls -- approximately 7K bytes, not
+   including the allocated sliding window, which is up to 32K bytes. */
+struct inflate_state {
+    z_streamp strm;             /* pointer back to this zlib stream */
+    inflate_mode mode;          /* current inflate mode */
+    int last;                   /* true if processing last block */
+    int wrap;                   /* bit 0 true for zlib, bit 1 true for gzip,
+                                   bit 2 true to validate check value */
+    int havedict;               /* true if dictionary provided */
+    int flags;                  /* gzip header method and flags (0 if zlib) */
+    unsigned dmax;              /* zlib header max distance (INFLATE_STRICT) */
+    unsigned long check;        /* protected copy of check value */
+    unsigned long total;        /* protected copy of output count */
+    gz_headerp head;            /* where to save gzip header information */
+        /* sliding window */
+    unsigned wbits;             /* log base 2 of requested window size */
+    unsigned wsize;             /* window size or zero if not using window */
+    unsigned whave;             /* valid bytes in the window */
+    unsigned wnext;             /* window write index */
+    unsigned char FAR *window;  /* allocated sliding window, if needed */
+        /* bit accumulator */
+    unsigned long hold;         /* input bit accumulator */
+    unsigned bits;              /* number of bits in "in" */
+        /* for string and stored block copying */
+    unsigned length;            /* literal or length of data to copy */
+    unsigned offset;            /* distance back to copy string from */
+        /* for table and code decoding */
+    unsigned extra;             /* extra bits needed */
+        /* fixed and dynamic code tables */
+    code const FAR *lencode;    /* starting table for length/literal codes */
+    code const FAR *distcode;   /* starting table for distance codes */
+    unsigned lenbits;           /* index bits for lencode */
+    unsigned distbits;          /* index bits for distcode */
+        /* dynamic table building */
+    unsigned ncode;             /* number of code length code lengths */
+    unsigned nlen;              /* number of length code lengths */
+    unsigned ndist;             /* number of distance code lengths */
+    unsigned have;              /* number of code lengths in lens[] */
+    code FAR *next;             /* next available space in codes[] */
+    unsigned short lens[320];   /* temporary storage for code lengths */
+    unsigned short work[288];   /* work area for code table building */
+    code codes[ENOUGH];         /* space for code tables */
+    int sane;                   /* if false, allow invalid distance too far */
+    int back;                   /* bits back of last unprocessed length/lit */
+    unsigned was;               /* initial length of match */
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/inftrees.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,328 @@
+/*
+ * 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.
+ */
+
+/* inftrees.c -- generate Huffman trees for efficient decoding
+ * Copyright (C) 1995-2017 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+#include "zutil.h"
+#include "inftrees.h"
+
+#define MAXBITS 15
+
+const char inflate_copyright[] =
+   " inflate 1.2.11 Copyright 1995-2017 Mark Adler ";
+/*
+  If you use the zlib library in a product, an acknowledgment is welcome
+  in the documentation of your product. If for some reason you cannot
+  include such an acknowledgment, I would appreciate that you keep this
+  copyright string in the executable of your product.
+ */
+
+/*
+   Build a set of tables to decode the provided canonical Huffman code.
+   The code lengths are lens[0..codes-1].  The result starts at *table,
+   whose indices are 0..2^bits-1.  work is a writable array of at least
+   lens shorts, which is used as a work area.  type is the type of code
+   to be generated, CODES, LENS, or DISTS.  On return, zero is success,
+   -1 is an invalid code, and +1 means that ENOUGH isn't enough.  table
+   on return points to the next available entry's address.  bits is the
+   requested root table index bits, and on return it is the actual root
+   table index bits.  It will differ if the request is greater than the
+   longest code or if it is less than the shortest code.
+ */
+int ZLIB_INTERNAL inflate_table(type, lens, codes, table, bits, work)
+codetype type;
+unsigned short FAR *lens;
+unsigned codes;
+code FAR * FAR *table;
+unsigned FAR *bits;
+unsigned short FAR *work;
+{
+    unsigned len;               /* a code's length in bits */
+    unsigned sym;               /* index of code symbols */
+    unsigned min, max;          /* minimum and maximum code lengths */
+    unsigned root;              /* number of index bits for root table */
+    unsigned curr;              /* number of index bits for current table */
+    unsigned drop;              /* code bits to drop for sub-table */
+    int left;                   /* number of prefix codes available */
+    unsigned used;              /* code entries in table used */
+    unsigned huff;              /* Huffman code */
+    unsigned incr;              /* for incrementing code, index */
+    unsigned fill;              /* index for replicating entries */
+    unsigned low;               /* low bits for current root entry */
+    unsigned mask;              /* mask for low root bits */
+    code here;                  /* table entry for duplication */
+    code FAR *next;             /* next available space in table */
+    const unsigned short FAR *base;     /* base value table to use */
+    const unsigned short FAR *extra;    /* extra bits table to use */
+    unsigned match;             /* use base and extra for symbol >= match */
+    unsigned short count[MAXBITS+1];    /* number of codes of each length */
+    unsigned short offs[MAXBITS+1];     /* offsets in table for each length */
+    static const unsigned short lbase[31] = { /* Length codes 257..285 base */
+        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31,
+        35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0};
+    static const unsigned short lext[31] = { /* Length codes 257..285 extra */
+        16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18,
+        19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 77, 202};
+    static const unsigned short dbase[32] = { /* Distance codes 0..29 base */
+        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193,
+        257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145,
+        8193, 12289, 16385, 24577, 0, 0};
+    static const unsigned short dext[32] = { /* Distance codes 0..29 extra */
+        16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22,
+        23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
+        28, 28, 29, 29, 64, 64};
+
+    /*
+       Process a set of code lengths to create a canonical Huffman code.  The
+       code lengths are lens[0..codes-1].  Each length corresponds to the
+       symbols 0..codes-1.  The Huffman code is generated by first sorting the
+       symbols by length from short to long, and retaining the symbol order
+       for codes with equal lengths.  Then the code starts with all zero bits
+       for the first code of the shortest length, and the codes are integer
+       increments for the same length, and zeros are appended as the length
+       increases.  For the deflate format, these bits are stored backwards
+       from their more natural integer increment ordering, and so when the
+       decoding tables are built in the large loop below, the integer codes
+       are incremented backwards.
+
+       This routine assumes, but does not check, that all of the entries in
+       lens[] are in the range 0..MAXBITS.  The caller must assure this.
+       1..MAXBITS is interpreted as that code length.  zero means that that
+       symbol does not occur in this code.
+
+       The codes are sorted by computing a count of codes for each length,
+       creating from that a table of starting indices for each length in the
+       sorted table, and then entering the symbols in order in the sorted
+       table.  The sorted table is work[], with that space being provided by
+       the caller.
+
+       The length counts are used for other purposes as well, i.e. finding
+       the minimum and maximum length codes, determining if there are any
+       codes at all, checking for a valid set of lengths, and looking ahead
+       at length counts to determine sub-table sizes when building the
+       decoding tables.
+     */
+
+    /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
+    for (len = 0; len <= MAXBITS; len++)
+        count[len] = 0;
+    for (sym = 0; sym < codes; sym++)
+        count[lens[sym]]++;
+
+    /* bound code lengths, force root to be within code lengths */
+    root = *bits;
+    for (max = MAXBITS; max >= 1; max--)
+        if (count[max] != 0) break;
+    if (root > max) root = max;
+    if (max == 0) {                     /* no symbols to code at all */
+        here.op = (unsigned char)64;    /* invalid code marker */
+        here.bits = (unsigned char)1;
+        here.val = (unsigned short)0;
+        *(*table)++ = here;             /* make a table to force an error */
+        *(*table)++ = here;
+        *bits = 1;
+        return 0;     /* no symbols, but wait for decoding to report error */
+    }
+    for (min = 1; min < max; min++)
+        if (count[min] != 0) break;
+    if (root < min) root = min;
+
+    /* check for an over-subscribed or incomplete set of lengths */
+    left = 1;
+    for (len = 1; len <= MAXBITS; len++) {
+        left <<= 1;
+        left -= count[len];
+        if (left < 0) return -1;        /* over-subscribed */
+    }
+    if (left > 0 && (type == CODES || max != 1))
+        return -1;                      /* incomplete set */
+
+    /* generate offsets into symbol table for each length for sorting */
+    offs[1] = 0;
+    for (len = 1; len < MAXBITS; len++)
+        offs[len + 1] = offs[len] + count[len];
+
+    /* sort symbols by length, by symbol order within each length */
+    for (sym = 0; sym < codes; sym++)
+        if (lens[sym] != 0) work[offs[lens[sym]]++] = (unsigned short)sym;
+
+    /*
+       Create and fill in decoding tables.  In this loop, the table being
+       filled is at next and has curr index bits.  The code being used is huff
+       with length len.  That code is converted to an index by dropping drop
+       bits off of the bottom.  For codes where len is less than drop + curr,
+       those top drop + curr - len bits are incremented through all values to
+       fill the table with replicated entries.
+
+       root is the number of index bits for the root table.  When len exceeds
+       root, sub-tables are created pointed to by the root entry with an index
+       of the low root bits of huff.  This is saved in low to check for when a
+       new sub-table should be started.  drop is zero when the root table is
+       being filled, and drop is root when sub-tables are being filled.
+
+       When a new sub-table is needed, it is necessary to look ahead in the
+       code lengths to determine what size sub-table is needed.  The length
+       counts are used for this, and so count[] is decremented as codes are
+       entered in the tables.
+
+       used keeps track of how many table entries have been allocated from the
+       provided *table space.  It is checked for LENS and DIST tables against
+       the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
+       the initial root table size constants.  See the comments in inftrees.h
+       for more information.
+
+       sym increments through all symbols, and the loop terminates when
+       all codes of length max, i.e. all codes, have been processed.  This
+       routine permits incomplete codes, so another loop after this one fills
+       in the rest of the decoding tables with invalid code markers.
+     */
+
+    /* set up for code type */
+    switch (type) {
+    case CODES:
+        base = extra = work;    /* dummy value--not used */
+        match = 20;
+        break;
+    case LENS:
+        base = lbase;
+        extra = lext;
+        match = 257;
+        break;
+    default:    /* DISTS */
+        base = dbase;
+        extra = dext;
+        match = 0;
+    }
+
+    /* initialize state for loop */
+    huff = 0;                   /* starting code */
+    sym = 0;                    /* starting code symbol */
+    len = min;                  /* starting code length */
+    next = *table;              /* current table to fill in */
+    curr = root;                /* current table index bits */
+    drop = 0;                   /* current bits to drop from code for index */
+    low = (unsigned)(-1);       /* trigger new sub-table when len > root */
+    used = 1U << root;          /* use root table entries */
+    mask = used - 1;            /* mask for comparing low */
+
+    /* check available table space */
+    if ((type == LENS && used > ENOUGH_LENS) ||
+        (type == DISTS && used > ENOUGH_DISTS))
+        return 1;
+
+    /* process all codes and make table entries */
+    for (;;) {
+        /* create table entry */
+        here.bits = (unsigned char)(len - drop);
+        if (work[sym] + 1U < match) {
+            here.op = (unsigned char)0;
+            here.val = work[sym];
+        }
+        else if (work[sym] >= match) {
+            here.op = (unsigned char)(extra[work[sym] - match]);
+            here.val = base[work[sym] - match];
+        }
+        else {
+            here.op = (unsigned char)(32 + 64);         /* end of block */
+            here.val = 0;
+        }
+
+        /* replicate for those indices with low len bits equal to huff */
+        incr = 1U << (len - drop);
+        fill = 1U << curr;
+        min = fill;                 /* save offset to next table */
+        do {
+            fill -= incr;
+            next[(huff >> drop) + fill] = here;
+        } while (fill != 0);
+
+        /* backwards increment the len-bit code huff */
+        incr = 1U << (len - 1);
+        while (huff & incr)
+            incr >>= 1;
+        if (incr != 0) {
+            huff &= incr - 1;
+            huff += incr;
+        }
+        else
+            huff = 0;
+
+        /* go to next symbol, update count, len */
+        sym++;
+        if (--(count[len]) == 0) {
+            if (len == max) break;
+            len = lens[work[sym]];
+        }
+
+        /* create new sub-table if needed */
+        if (len > root && (huff & mask) != low) {
+            /* if first time, transition to sub-tables */
+            if (drop == 0)
+                drop = root;
+
+            /* increment past last table */
+            next += min;            /* here min is 1 << curr */
+
+            /* determine length of next table */
+            curr = len - drop;
+            left = (int)(1 << curr);
+            while (curr + drop < max) {
+                left -= count[curr + drop];
+                if (left <= 0) break;
+                curr++;
+                left <<= 1;
+            }
+
+            /* check for enough space */
+            used += 1U << curr;
+            if ((type == LENS && used > ENOUGH_LENS) ||
+                (type == DISTS && used > ENOUGH_DISTS))
+                return 1;
+
+            /* point entry in root table to sub-table */
+            low = huff & mask;
+            (*table)[low].op = (unsigned char)curr;
+            (*table)[low].bits = (unsigned char)root;
+            (*table)[low].val = (unsigned short)(next - *table);
+        }
+    }
+
+    /* fill in remaining table entry if code is incomplete (guaranteed to have
+       at most one remaining entry, since if the code is incomplete, the
+       maximum code length that was allowed to get this far is one bit) */
+    if (huff != 0) {
+        here.op = (unsigned char)64;            /* invalid code marker */
+        here.bits = (unsigned char)(len - drop);
+        here.val = (unsigned short)0;
+        next[huff] = here;
+    }
+
+    /* set return parameters */
+    *table += used;
+    *bits = root;
+    return 0;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/inftrees.h	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,86 @@
+/*
+ * 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.
+ */
+
+/* inftrees.h -- header to use inftrees.c
+ * Copyright (C) 1995-2005, 2010 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* Structure for decoding tables.  Each entry provides either the
+   information needed to do the operation requested by the code that
+   indexed that table entry, or it provides a pointer to another
+   table that indexes more bits of the code.  op indicates whether
+   the entry is a pointer to another table, a literal, a length or
+   distance, an end-of-block, or an invalid code.  For a table
+   pointer, the low four bits of op is the number of index bits of
+   that table.  For a length or distance, the low four bits of op
+   is the number of extra bits to get after the code.  bits is
+   the number of bits in this code or part of the code to drop off
+   of the bit buffer.  val is the actual byte to output in the case
+   of a literal, the base length or distance, or the offset from
+   the current table to the next table.  Each entry is four bytes. */
+typedef struct {
+    unsigned char op;           /* operation, extra bits, table bits */
+    unsigned char bits;         /* bits in this part of the code */
+    unsigned short val;         /* offset in table or code value */
+} code;
+
+/* op values as set by inflate_table():
+    00000000 - literal
+    0000tttt - table link, tttt != 0 is the number of table index bits
+    0001eeee - length or distance, eeee is the number of extra bits
+    01100000 - end of block
+    01000000 - invalid code
+ */
+
+/* Maximum size of the dynamic table.  The maximum number of code structures is
+   1444, which is the sum of 852 for literal/length codes and 592 for distance
+   codes.  These values were found by exhaustive searches using the program
+   examples/enough.c found in the zlib distribtution.  The arguments to that
+   program are the number of symbols, the initial root table size, and the
+   maximum bit length of a code.  "enough 286 9 15" for literal/length codes
+   returns returns 852, and "enough 30 6 15" for distance codes returns 592.
+   The initial root table size (9 or 6) is found in the fifth argument of the
+   inflate_table() calls in inflate.c and infback.c.  If the root table size is
+   changed, then these maximum sizes would be need to be recalculated and
+   updated. */
+#define ENOUGH_LENS 852
+#define ENOUGH_DISTS 592
+#define ENOUGH (ENOUGH_LENS+ENOUGH_DISTS)
+
+/* Type of code to build for inflate_table() */
+typedef enum {
+    CODES,
+    LENS,
+    DISTS
+} codetype;
+
+int ZLIB_INTERNAL inflate_table OF((codetype type, unsigned short FAR *lens,
+                             unsigned codes, code FAR * FAR *table,
+                             unsigned FAR *bits, unsigned short FAR *work));
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/patches/ChangeLog_java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,81 @@
+(1) renamed adler32.c -> zadler32.c, zcrc32c -> zcrc32.c
+
+(2) zconf.h:
+    - added _LP64 to make uLong a 32-bit int on 64-bit platform
+    uLong -> 32-bit int
+
+--------------------------
+35,37d10
+< /* for _LP64 */
+< #include <sys/types.h>
+<
+421,424d393
+<
+< #ifdef _LP64
+< typedef unsigned int  uLong;  /* 32 bits or more */
+< #else
+426d394
+< #endif
+--------------------------
+
+(3) updated crc32.c/crc32(), crc32_z()
+   unsigned long      -> uLong
+
+--------------------------
+
+226,227c202,203
+< uLong ZEXPORT crc32_z(crc, buf, len)
+<     uLong crc;
+---
+> unsigned long ZEXPORT crc32_z(crc, buf, len)
+>     unsigned long crc;
+244c220
+<             return (uLong)crc32_little(crc, buf, len);
+---
+>             return crc32_little(crc, buf, len);
+246c222
+<             return (uLong)crc32_big(crc, buf, len);
+---
+>             return crc32_big(crc, buf, len);
+261,262c237,238
+< uLong ZEXPORT crc32(crc, buf, len)
+<     uLong crc;
+---
+> unsigned long ZEXPORT crc32(crc, buf, len)
+>     unsigned long crc;
+
+--------------------------
+
+(4) gzread.c
+
+--------------------------
+343c319
+<             n = (unsigned)len;
+---
+>             n = len;
+424c400
+<     len = (unsigned)gz_read(state, buf, len);
+---
+>     len = gz_read(state, buf, len);
+496c472
+<     ret = (int)gz_read(state, buf, 1);
+---
+>     ret = gz_read(state, buf, 1);
+--------------------------
+
+(5) gzwrite.c
+
+--------------------------
+236c212
+<                 copy = (unsigned)len;
+---
+>                 copy = len;
+256c232
+<                 n = (unsigned)len;
+---
+>                 n = len;
+--------------------------
+
+
+
+  
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/trees.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,1227 @@
+/*
+ * 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.
+ */
+
+/* trees.c -- output deflated data using Huffman coding
+ * Copyright (C) 1995-2017 Jean-loup Gailly
+ * detect_data_type() function provided freely by Cosmin Truta, 2006
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/*
+ *  ALGORITHM
+ *
+ *      The "deflation" process uses several Huffman trees. The more
+ *      common source values are represented by shorter bit sequences.
+ *
+ *      Each code tree is stored in a compressed form which is itself
+ * a Huffman encoding of the lengths of all the code strings (in
+ * ascending order by source values).  The actual code strings are
+ * reconstructed from the lengths in the inflate process, as described
+ * in the deflate specification.
+ *
+ *  REFERENCES
+ *
+ *      Deutsch, L.P.,"'Deflate' Compressed Data Format Specification".
+ *      Available in ftp.uu.net:/pub/archiving/zip/doc/deflate-1.1.doc
+ *
+ *      Storer, James A.
+ *          Data Compression:  Methods and Theory, pp. 49-50.
+ *          Computer Science Press, 1988.  ISBN 0-7167-8156-5.
+ *
+ *      Sedgewick, R.
+ *          Algorithms, p290.
+ *          Addison-Wesley, 1983. ISBN 0-201-06672-6.
+ */
+
+/* @(#) $Id$ */
+
+/* #define GEN_TREES_H */
+
+#include "deflate.h"
+
+#ifdef ZLIB_DEBUG
+#  include <ctype.h>
+#endif
+
+/* ===========================================================================
+ * Constants
+ */
+
+#define MAX_BL_BITS 7
+/* Bit length codes must not exceed MAX_BL_BITS bits */
+
+#define END_BLOCK 256
+/* end of block literal code */
+
+#define REP_3_6      16
+/* repeat previous bit length 3-6 times (2 bits of repeat count) */
+
+#define REPZ_3_10    17
+/* repeat a zero length 3-10 times  (3 bits of repeat count) */
+
+#define REPZ_11_138  18
+/* repeat a zero length 11-138 times  (7 bits of repeat count) */
+
+local const int extra_lbits[LENGTH_CODES] /* extra bits for each length code */
+   = {0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0};
+
+local const int extra_dbits[D_CODES] /* extra bits for each distance code */
+   = {0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13};
+
+local const int extra_blbits[BL_CODES]/* extra bits for each bit length code */
+   = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7};
+
+local const uch bl_order[BL_CODES]
+   = {16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15};
+/* The lengths of the bit length codes are sent in order of decreasing
+ * probability, to avoid transmitting the lengths for unused bit length codes.
+ */
+
+/* ===========================================================================
+ * Local data. These are initialized only once.
+ */
+
+#define DIST_CODE_LEN  512 /* see definition of array dist_code below */
+
+#if defined(GEN_TREES_H) || !defined(STDC)
+/* non ANSI compilers may not accept trees.h */
+
+local ct_data static_ltree[L_CODES+2];
+/* The static literal tree. Since the bit lengths are imposed, there is no
+ * need for the L_CODES extra codes used during heap construction. However
+ * The codes 286 and 287 are needed to build a canonical tree (see _tr_init
+ * below).
+ */
+
+local ct_data static_dtree[D_CODES];
+/* The static distance tree. (Actually a trivial tree since all codes use
+ * 5 bits.)
+ */
+
+uch _dist_code[DIST_CODE_LEN];
+/* Distance codes. The first 256 values correspond to the distances
+ * 3 .. 258, the last 256 values correspond to the top 8 bits of
+ * the 15 bit distances.
+ */
+
+uch _length_code[MAX_MATCH-MIN_MATCH+1];
+/* length code for each normalized match length (0 == MIN_MATCH) */
+
+local int base_length[LENGTH_CODES];
+/* First normalized length for each code (0 = MIN_MATCH) */
+
+local int base_dist[D_CODES];
+/* First normalized distance for each code (0 = distance of 1) */
+
+#else
+#  include "trees.h"
+#endif /* GEN_TREES_H */
+
+struct static_tree_desc_s {
+    const ct_data *static_tree;  /* static tree or NULL */
+    const intf *extra_bits;      /* extra bits for each code or NULL */
+    int     extra_base;          /* base index for extra_bits */
+    int     elems;               /* max number of elements in the tree */
+    int     max_length;          /* max bit length for the codes */
+};
+
+local const static_tree_desc  static_l_desc =
+{static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS};
+
+local const static_tree_desc  static_d_desc =
+{static_dtree, extra_dbits, 0,          D_CODES, MAX_BITS};
+
+local const static_tree_desc  static_bl_desc =
+{(const ct_data *)0, extra_blbits, 0,   BL_CODES, MAX_BL_BITS};
+
+/* ===========================================================================
+ * Local (static) routines in this file.
+ */
+
+local void tr_static_init OF((void));
+local void init_block     OF((deflate_state *s));
+local void pqdownheap     OF((deflate_state *s, ct_data *tree, int k));
+local void gen_bitlen     OF((deflate_state *s, tree_desc *desc));
+local void gen_codes      OF((ct_data *tree, int max_code, ushf *bl_count));
+local void build_tree     OF((deflate_state *s, tree_desc *desc));
+local void scan_tree      OF((deflate_state *s, ct_data *tree, int max_code));
+local void send_tree      OF((deflate_state *s, ct_data *tree, int max_code));
+local int  build_bl_tree  OF((deflate_state *s));
+local void send_all_trees OF((deflate_state *s, int lcodes, int dcodes,
+                              int blcodes));
+local void compress_block OF((deflate_state *s, const ct_data *ltree,
+                              const ct_data *dtree));
+local int  detect_data_type OF((deflate_state *s));
+local unsigned bi_reverse OF((unsigned value, int length));
+local void bi_windup      OF((deflate_state *s));
+local void bi_flush       OF((deflate_state *s));
+
+#ifdef GEN_TREES_H
+local void gen_trees_header OF((void));
+#endif
+
+#ifndef ZLIB_DEBUG
+#  define send_code(s, c, tree) send_bits(s, tree[c].Code, tree[c].Len)
+   /* Send a code of the given tree. c and tree must not have side effects */
+
+#else /* !ZLIB_DEBUG */
+#  define send_code(s, c, tree) \
+     { if (z_verbose>2) fprintf(stderr,"\ncd %3d ",(c)); \
+       send_bits(s, tree[c].Code, tree[c].Len); }
+#endif
+
+/* ===========================================================================
+ * Output a short LSB first on the stream.
+ * IN assertion: there is enough room in pendingBuf.
+ */
+#define put_short(s, w) { \
+    put_byte(s, (uch)((w) & 0xff)); \
+    put_byte(s, (uch)((ush)(w) >> 8)); \
+}
+
+/* ===========================================================================
+ * Send a value on a given number of bits.
+ * IN assertion: length <= 16 and value fits in length bits.
+ */
+#ifdef ZLIB_DEBUG
+local void send_bits      OF((deflate_state *s, int value, int length));
+
+local void send_bits(s, value, length)
+    deflate_state *s;
+    int value;  /* value to send */
+    int length; /* number of bits */
+{
+    Tracevv((stderr," l %2d v %4x ", length, value));
+    Assert(length > 0 && length <= 15, "invalid length");
+    s->bits_sent += (ulg)length;
+
+    /* If not enough room in bi_buf, use (valid) bits from bi_buf and
+     * (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
+     * unused bits in value.
+     */
+    if (s->bi_valid > (int)Buf_size - length) {
+        s->bi_buf |= (ush)value << s->bi_valid;
+        put_short(s, s->bi_buf);
+        s->bi_buf = (ush)value >> (Buf_size - s->bi_valid);
+        s->bi_valid += length - Buf_size;
+    } else {
+        s->bi_buf |= (ush)value << s->bi_valid;
+        s->bi_valid += length;
+    }
+}
+#else /* !ZLIB_DEBUG */
+
+#define send_bits(s, value, length) \
+{ int len = length;\
+  if (s->bi_valid > (int)Buf_size - len) {\
+    int val = (int)value;\
+    s->bi_buf |= (ush)val << s->bi_valid;\
+    put_short(s, s->bi_buf);\
+    s->bi_buf = (ush)val >> (Buf_size - s->bi_valid);\
+    s->bi_valid += len - Buf_size;\
+  } else {\
+    s->bi_buf |= (ush)(value) << s->bi_valid;\
+    s->bi_valid += len;\
+  }\
+}
+#endif /* ZLIB_DEBUG */
+
+
+/* the arguments must not have side effects */
+
+/* ===========================================================================
+ * Initialize the various 'constant' tables.
+ */
+local void tr_static_init()
+{
+#if defined(GEN_TREES_H) || !defined(STDC)
+    static int static_init_done = 0;
+    int n;        /* iterates over tree elements */
+    int bits;     /* bit counter */
+    int length;   /* length value */
+    int code;     /* code value */
+    int dist;     /* distance index */
+    ush bl_count[MAX_BITS+1];
+    /* number of codes at each bit length for an optimal tree */
+
+    if (static_init_done) return;
+
+    /* For some embedded targets, global variables are not initialized: */
+#ifdef NO_INIT_GLOBAL_POINTERS
+    static_l_desc.static_tree = static_ltree;
+    static_l_desc.extra_bits = extra_lbits;
+    static_d_desc.static_tree = static_dtree;
+    static_d_desc.extra_bits = extra_dbits;
+    static_bl_desc.extra_bits = extra_blbits;
+#endif
+
+    /* Initialize the mapping length (0..255) -> length code (0..28) */
+    length = 0;
+    for (code = 0; code < LENGTH_CODES-1; code++) {
+        base_length[code] = length;
+        for (n = 0; n < (1<<extra_lbits[code]); n++) {
+            _length_code[length++] = (uch)code;
+        }
+    }
+    Assert (length == 256, "tr_static_init: length != 256");
+    /* Note that the length 255 (match length 258) can be represented
+     * in two different ways: code 284 + 5 bits or code 285, so we
+     * overwrite length_code[255] to use the best encoding:
+     */
+    _length_code[length-1] = (uch)code;
+
+    /* Initialize the mapping dist (0..32K) -> dist code (0..29) */
+    dist = 0;
+    for (code = 0 ; code < 16; code++) {
+        base_dist[code] = dist;
+        for (n = 0; n < (1<<extra_dbits[code]); n++) {
+            _dist_code[dist++] = (uch)code;
+        }
+    }
+    Assert (dist == 256, "tr_static_init: dist != 256");
+    dist >>= 7; /* from now on, all distances are divided by 128 */
+    for ( ; code < D_CODES; code++) {
+        base_dist[code] = dist << 7;
+        for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
+            _dist_code[256 + dist++] = (uch)code;
+        }
+    }
+    Assert (dist == 256, "tr_static_init: 256+dist != 512");
+
+    /* Construct the codes of the static literal tree */
+    for (bits = 0; bits <= MAX_BITS; bits++) bl_count[bits] = 0;
+    n = 0;
+    while (n <= 143) static_ltree[n++].Len = 8, bl_count[8]++;
+    while (n <= 255) static_ltree[n++].Len = 9, bl_count[9]++;
+    while (n <= 279) static_ltree[n++].Len = 7, bl_count[7]++;
+    while (n <= 287) static_ltree[n++].Len = 8, bl_count[8]++;
+    /* Codes 286 and 287 do not exist, but we must include them in the
+     * tree construction to get a canonical Huffman tree (longest code
+     * all ones)
+     */
+    gen_codes((ct_data *)static_ltree, L_CODES+1, bl_count);
+
+    /* The static distance tree is trivial: */
+    for (n = 0; n < D_CODES; n++) {
+        static_dtree[n].Len = 5;
+        static_dtree[n].Code = bi_reverse((unsigned)n, 5);
+    }
+    static_init_done = 1;
+
+#  ifdef GEN_TREES_H
+    gen_trees_header();
+#  endif
+#endif /* defined(GEN_TREES_H) || !defined(STDC) */
+}
+
+/* ===========================================================================
+ * Genererate the file trees.h describing the static trees.
+ */
+#ifdef GEN_TREES_H
+#  ifndef ZLIB_DEBUG
+#    include <stdio.h>
+#  endif
+
+#  define SEPARATOR(i, last, width) \
+      ((i) == (last)? "\n};\n\n" :    \
+       ((i) % (width) == (width)-1 ? ",\n" : ", "))
+
+void gen_trees_header()
+{
+    FILE *header = fopen("trees.h", "w");
+    int i;
+
+    Assert (header != NULL, "Can't open trees.h");
+    fprintf(header,
+            "/* header created automatically with -DGEN_TREES_H */\n\n");
+
+    fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
+    for (i = 0; i < L_CODES+2; i++) {
+        fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
+                static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
+    }
+
+    fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
+    for (i = 0; i < D_CODES; i++) {
+        fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
+                static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
+    }
+
+    fprintf(header, "const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {\n");
+    for (i = 0; i < DIST_CODE_LEN; i++) {
+        fprintf(header, "%2u%s", _dist_code[i],
+                SEPARATOR(i, DIST_CODE_LEN-1, 20));
+    }
+
+    fprintf(header,
+        "const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
+    for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
+        fprintf(header, "%2u%s", _length_code[i],
+                SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
+    }
+
+    fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
+    for (i = 0; i < LENGTH_CODES; i++) {
+        fprintf(header, "%1u%s", base_length[i],
+                SEPARATOR(i, LENGTH_CODES-1, 20));
+    }
+
+    fprintf(header, "local const int base_dist[D_CODES] = {\n");
+    for (i = 0; i < D_CODES; i++) {
+        fprintf(header, "%5u%s", base_dist[i],
+                SEPARATOR(i, D_CODES-1, 10));
+    }
+
+    fclose(header);
+}
+#endif /* GEN_TREES_H */
+
+/* ===========================================================================
+ * Initialize the tree data structures for a new zlib stream.
+ */
+void ZLIB_INTERNAL _tr_init(s)
+    deflate_state *s;
+{
+    tr_static_init();
+
+    s->l_desc.dyn_tree = s->dyn_ltree;
+    s->l_desc.stat_desc = &static_l_desc;
+
+    s->d_desc.dyn_tree = s->dyn_dtree;
+    s->d_desc.stat_desc = &static_d_desc;
+
+    s->bl_desc.dyn_tree = s->bl_tree;
+    s->bl_desc.stat_desc = &static_bl_desc;
+
+    s->bi_buf = 0;
+    s->bi_valid = 0;
+#ifdef ZLIB_DEBUG
+    s->compressed_len = 0L;
+    s->bits_sent = 0L;
+#endif
+
+    /* Initialize the first block of the first file: */
+    init_block(s);
+}
+
+/* ===========================================================================
+ * Initialize a new block.
+ */
+local void init_block(s)
+    deflate_state *s;
+{
+    int n; /* iterates over tree elements */
+
+    /* Initialize the trees. */
+    for (n = 0; n < L_CODES;  n++) s->dyn_ltree[n].Freq = 0;
+    for (n = 0; n < D_CODES;  n++) s->dyn_dtree[n].Freq = 0;
+    for (n = 0; n < BL_CODES; n++) s->bl_tree[n].Freq = 0;
+
+    s->dyn_ltree[END_BLOCK].Freq = 1;
+    s->opt_len = s->static_len = 0L;
+    s->last_lit = s->matches = 0;
+}
+
+#define SMALLEST 1
+/* Index within the heap array of least frequent node in the Huffman tree */
+
+
+/* ===========================================================================
+ * Remove the smallest element from the heap and recreate the heap with
+ * one less element. Updates heap and heap_len.
+ */
+#define pqremove(s, tree, top) \
+{\
+    top = s->heap[SMALLEST]; \
+    s->heap[SMALLEST] = s->heap[s->heap_len--]; \
+    pqdownheap(s, tree, SMALLEST); \
+}
+
+/* ===========================================================================
+ * Compares to subtrees, using the tree depth as tie breaker when
+ * the subtrees have equal frequency. This minimizes the worst case length.
+ */
+#define smaller(tree, n, m, depth) \
+   (tree[n].Freq < tree[m].Freq || \
+   (tree[n].Freq == tree[m].Freq && depth[n] <= depth[m]))
+
+/* ===========================================================================
+ * Restore the heap property by moving down the tree starting at node k,
+ * exchanging a node with the smallest of its two sons if necessary, stopping
+ * when the heap property is re-established (each father smaller than its
+ * two sons).
+ */
+local void pqdownheap(s, tree, k)
+    deflate_state *s;
+    ct_data *tree;  /* the tree to restore */
+    int k;               /* node to move down */
+{
+    int v = s->heap[k];
+    int j = k << 1;  /* left son of k */
+    while (j <= s->heap_len) {
+        /* Set j to the smallest of the two sons: */
+        if (j < s->heap_len &&
+            smaller(tree, s->heap[j+1], s->heap[j], s->depth)) {
+            j++;
+        }
+        /* Exit if v is smaller than both sons */
+        if (smaller(tree, v, s->heap[j], s->depth)) break;
+
+        /* Exchange v with the smallest son */
+        s->heap[k] = s->heap[j];  k = j;
+
+        /* And continue down the tree, setting j to the left son of k */
+        j <<= 1;
+    }
+    s->heap[k] = v;
+}
+
+/* ===========================================================================
+ * Compute the optimal bit lengths for a tree and update the total bit length
+ * for the current block.
+ * IN assertion: the fields freq and dad are set, heap[heap_max] and
+ *    above are the tree nodes sorted by increasing frequency.
+ * OUT assertions: the field len is set to the optimal bit length, the
+ *     array bl_count contains the frequencies for each bit length.
+ *     The length opt_len is updated; static_len is also updated if stree is
+ *     not null.
+ */
+local void gen_bitlen(s, desc)
+    deflate_state *s;
+    tree_desc *desc;    /* the tree descriptor */
+{
+    ct_data *tree        = desc->dyn_tree;
+    int max_code         = desc->max_code;
+    const ct_data *stree = desc->stat_desc->static_tree;
+    const intf *extra    = desc->stat_desc->extra_bits;
+    int base             = desc->stat_desc->extra_base;
+    int max_length       = desc->stat_desc->max_length;
+    int h;              /* heap index */
+    int n, m;           /* iterate over the tree elements */
+    int bits;           /* bit length */
+    int xbits;          /* extra bits */
+    ush f;              /* frequency */
+    int overflow = 0;   /* number of elements with bit length too large */
+
+    for (bits = 0; bits <= MAX_BITS; bits++) s->bl_count[bits] = 0;
+
+    /* In a first pass, compute the optimal bit lengths (which may
+     * overflow in the case of the bit length tree).
+     */
+    tree[s->heap[s->heap_max]].Len = 0; /* root of the heap */
+
+    for (h = s->heap_max+1; h < HEAP_SIZE; h++) {
+        n = s->heap[h];
+        bits = tree[tree[n].Dad].Len + 1;
+        if (bits > max_length) bits = max_length, overflow++;
+        tree[n].Len = (ush)bits;
+        /* We overwrite tree[n].Dad which is no longer needed */
+
+        if (n > max_code) continue; /* not a leaf node */
+
+        s->bl_count[bits]++;
+        xbits = 0;
+        if (n >= base) xbits = extra[n-base];
+        f = tree[n].Freq;
+        s->opt_len += (ulg)f * (unsigned)(bits + xbits);
+        if (stree) s->static_len += (ulg)f * (unsigned)(stree[n].Len + xbits);
+    }
+    if (overflow == 0) return;
+
+    Tracev((stderr,"\nbit length overflow\n"));
+    /* This happens for example on obj2 and pic of the Calgary corpus */
+
+    /* Find the first bit length which could increase: */
+    do {
+        bits = max_length-1;
+        while (s->bl_count[bits] == 0) bits--;
+        s->bl_count[bits]--;      /* move one leaf down the tree */
+        s->bl_count[bits+1] += 2; /* move one overflow item as its brother */
+        s->bl_count[max_length]--;
+        /* The brother of the overflow item also moves one step up,
+         * but this does not affect bl_count[max_length]
+         */
+        overflow -= 2;
+    } while (overflow > 0);
+
+    /* Now recompute all bit lengths, scanning in increasing frequency.
+     * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
+     * lengths instead of fixing only the wrong ones. This idea is taken
+     * from 'ar' written by Haruhiko Okumura.)
+     */
+    for (bits = max_length; bits != 0; bits--) {
+        n = s->bl_count[bits];
+        while (n != 0) {
+            m = s->heap[--h];
+            if (m > max_code) continue;
+            if ((unsigned) tree[m].Len != (unsigned) bits) {
+                Tracev((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
+                s->opt_len += ((ulg)bits - tree[m].Len) * tree[m].Freq;
+                tree[m].Len = (ush)bits;
+            }
+            n--;
+        }
+    }
+}
+
+/* ===========================================================================
+ * Generate the codes for a given tree and bit counts (which need not be
+ * optimal).
+ * IN assertion: the array bl_count contains the bit length statistics for
+ * the given tree and the field len is set for all tree elements.
+ * OUT assertion: the field code is set for all tree elements of non
+ *     zero code length.
+ */
+local void gen_codes (tree, max_code, bl_count)
+    ct_data *tree;             /* the tree to decorate */
+    int max_code;              /* largest code with non zero frequency */
+    ushf *bl_count;            /* number of codes at each bit length */
+{
+    ush next_code[MAX_BITS+1]; /* next code value for each bit length */
+    unsigned code = 0;         /* running code value */
+    int bits;                  /* bit index */
+    int n;                     /* code index */
+
+    /* The distribution counts are first used to generate the code values
+     * without bit reversal.
+     */
+    for (bits = 1; bits <= MAX_BITS; bits++) {
+        code = (code + bl_count[bits-1]) << 1;
+        next_code[bits] = (ush)code;
+    }
+    /* Check that the bit counts in bl_count are consistent. The last code
+     * must be all ones.
+     */
+    Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
+            "inconsistent bit counts");
+    Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
+
+    for (n = 0;  n <= max_code; n++) {
+        int len = tree[n].Len;
+        if (len == 0) continue;
+        /* Now reverse the bits */
+        tree[n].Code = (ush)bi_reverse(next_code[len]++, len);
+
+        Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
+             n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
+    }
+}
+
+/* ===========================================================================
+ * Construct one Huffman tree and assigns the code bit strings and lengths.
+ * Update the total bit length for the current block.
+ * IN assertion: the field freq is set for all tree elements.
+ * OUT assertions: the fields len and code are set to the optimal bit length
+ *     and corresponding code. The length opt_len is updated; static_len is
+ *     also updated if stree is not null. The field max_code is set.
+ */
+local void build_tree(s, desc)
+    deflate_state *s;
+    tree_desc *desc; /* the tree descriptor */
+{
+    ct_data *tree         = desc->dyn_tree;
+    const ct_data *stree  = desc->stat_desc->static_tree;
+    int elems             = desc->stat_desc->elems;
+    int n, m;          /* iterate over heap elements */
+    int max_code = -1; /* largest code with non zero frequency */
+    int node;          /* new node being created */
+
+    /* Construct the initial heap, with least frequent element in
+     * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
+     * heap[0] is not used.
+     */
+    s->heap_len = 0, s->heap_max = HEAP_SIZE;
+
+    for (n = 0; n < elems; n++) {
+        if (tree[n].Freq != 0) {
+            s->heap[++(s->heap_len)] = max_code = n;
+            s->depth[n] = 0;
+        } else {
+            tree[n].Len = 0;
+        }
+    }
+
+    /* The pkzip format requires that at least one distance code exists,
+     * and that at least one bit should be sent even if there is only one
+     * possible code. So to avoid special checks later on we force at least
+     * two codes of non zero frequency.
+     */
+    while (s->heap_len < 2) {
+        node = s->heap[++(s->heap_len)] = (max_code < 2 ? ++max_code : 0);
+        tree[node].Freq = 1;
+        s->depth[node] = 0;
+        s->opt_len--; if (stree) s->static_len -= stree[node].Len;
+        /* node is 0 or 1 so it does not have extra bits */
+    }
+    desc->max_code = max_code;
+
+    /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
+     * establish sub-heaps of increasing lengths:
+     */
+    for (n = s->heap_len/2; n >= 1; n--) pqdownheap(s, tree, n);
+
+    /* Construct the Huffman tree by repeatedly combining the least two
+     * frequent nodes.
+     */
+    node = elems;              /* next internal node of the tree */
+    do {
+        pqremove(s, tree, n);  /* n = node of least frequency */
+        m = s->heap[SMALLEST]; /* m = node of next least frequency */
+
+        s->heap[--(s->heap_max)] = n; /* keep the nodes sorted by frequency */
+        s->heap[--(s->heap_max)] = m;
+
+        /* Create a new node father of n and m */
+        tree[node].Freq = tree[n].Freq + tree[m].Freq;
+        s->depth[node] = (uch)((s->depth[n] >= s->depth[m] ?
+                                s->depth[n] : s->depth[m]) + 1);
+        tree[n].Dad = tree[m].Dad = (ush)node;
+#ifdef DUMP_BL_TREE
+        if (tree == s->bl_tree) {
+            fprintf(stderr,"\nnode %d(%d), sons %d(%d) %d(%d)",
+                    node, tree[node].Freq, n, tree[n].Freq, m, tree[m].Freq);
+        }
+#endif
+        /* and insert the new node in the heap */
+        s->heap[SMALLEST] = node++;
+        pqdownheap(s, tree, SMALLEST);
+
+    } while (s->heap_len >= 2);
+
+    s->heap[--(s->heap_max)] = s->heap[SMALLEST];
+
+    /* At this point, the fields freq and dad are set. We can now
+     * generate the bit lengths.
+     */
+    gen_bitlen(s, (tree_desc *)desc);
+
+    /* The field len is now set, we can generate the bit codes */
+    gen_codes ((ct_data *)tree, max_code, s->bl_count);
+}
+
+/* ===========================================================================
+ * Scan a literal or distance tree to determine the frequencies of the codes
+ * in the bit length tree.
+ */
+local void scan_tree (s, tree, max_code)
+    deflate_state *s;
+    ct_data *tree;   /* the tree to be scanned */
+    int max_code;    /* and its largest code of non zero frequency */
+{
+    int n;                     /* iterates over all tree elements */
+    int prevlen = -1;          /* last emitted length */
+    int curlen;                /* length of current code */
+    int nextlen = tree[0].Len; /* length of next code */
+    int count = 0;             /* repeat count of the current code */
+    int max_count = 7;         /* max repeat count */
+    int min_count = 4;         /* min repeat count */
+
+    if (nextlen == 0) max_count = 138, min_count = 3;
+    tree[max_code+1].Len = (ush)0xffff; /* guard */
+
+    for (n = 0; n <= max_code; n++) {
+        curlen = nextlen; nextlen = tree[n+1].Len;
+        if (++count < max_count && curlen == nextlen) {
+            continue;
+        } else if (count < min_count) {
+            s->bl_tree[curlen].Freq += count;
+        } else if (curlen != 0) {
+            if (curlen != prevlen) s->bl_tree[curlen].Freq++;
+            s->bl_tree[REP_3_6].Freq++;
+        } else if (count <= 10) {
+            s->bl_tree[REPZ_3_10].Freq++;
+        } else {
+            s->bl_tree[REPZ_11_138].Freq++;
+        }
+        count = 0; prevlen = curlen;
+        if (nextlen == 0) {
+            max_count = 138, min_count = 3;
+        } else if (curlen == nextlen) {
+            max_count = 6, min_count = 3;
+        } else {
+            max_count = 7, min_count = 4;
+        }
+    }
+}
+
+/* ===========================================================================
+ * Send a literal or distance tree in compressed form, using the codes in
+ * bl_tree.
+ */
+local void send_tree (s, tree, max_code)
+    deflate_state *s;
+    ct_data *tree; /* the tree to be scanned */
+    int max_code;       /* and its largest code of non zero frequency */
+{
+    int n;                     /* iterates over all tree elements */
+    int prevlen = -1;          /* last emitted length */
+    int curlen;                /* length of current code */
+    int nextlen = tree[0].Len; /* length of next code */
+    int count = 0;             /* repeat count of the current code */
+    int max_count = 7;         /* max repeat count */
+    int min_count = 4;         /* min repeat count */
+
+    /* tree[max_code+1].Len = -1; */  /* guard already set */
+    if (nextlen == 0) max_count = 138, min_count = 3;
+
+    for (n = 0; n <= max_code; n++) {
+        curlen = nextlen; nextlen = tree[n+1].Len;
+        if (++count < max_count && curlen == nextlen) {
+            continue;
+        } else if (count < min_count) {
+            do { send_code(s, curlen, s->bl_tree); } while (--count != 0);
+
+        } else if (curlen != 0) {
+            if (curlen != prevlen) {
+                send_code(s, curlen, s->bl_tree); count--;
+            }
+            Assert(count >= 3 && count <= 6, " 3_6?");
+            send_code(s, REP_3_6, s->bl_tree); send_bits(s, count-3, 2);
+
+        } else if (count <= 10) {
+            send_code(s, REPZ_3_10, s->bl_tree); send_bits(s, count-3, 3);
+
+        } else {
+            send_code(s, REPZ_11_138, s->bl_tree); send_bits(s, count-11, 7);
+        }
+        count = 0; prevlen = curlen;
+        if (nextlen == 0) {
+            max_count = 138, min_count = 3;
+        } else if (curlen == nextlen) {
+            max_count = 6, min_count = 3;
+        } else {
+            max_count = 7, min_count = 4;
+        }
+    }
+}
+
+/* ===========================================================================
+ * Construct the Huffman tree for the bit lengths and return the index in
+ * bl_order of the last bit length code to send.
+ */
+local int build_bl_tree(s)
+    deflate_state *s;
+{
+    int max_blindex;  /* index of last bit length code of non zero freq */
+
+    /* Determine the bit length frequencies for literal and distance trees */
+    scan_tree(s, (ct_data *)s->dyn_ltree, s->l_desc.max_code);
+    scan_tree(s, (ct_data *)s->dyn_dtree, s->d_desc.max_code);
+
+    /* Build the bit length tree: */
+    build_tree(s, (tree_desc *)(&(s->bl_desc)));
+    /* opt_len now includes the length of the tree representations, except
+     * the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
+     */
+
+    /* Determine the number of bit length codes to send. The pkzip format
+     * requires that at least 4 bit length codes be sent. (appnote.txt says
+     * 3 but the actual value used is 4.)
+     */
+    for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
+        if (s->bl_tree[bl_order[max_blindex]].Len != 0) break;
+    }
+    /* Update opt_len to include the bit length tree and counts */
+    s->opt_len += 3*((ulg)max_blindex+1) + 5+5+4;
+    Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
+            s->opt_len, s->static_len));
+
+    return max_blindex;
+}
+
+/* ===========================================================================
+ * Send the header for a block using dynamic Huffman trees: the counts, the
+ * lengths of the bit length codes, the literal tree and the distance tree.
+ * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
+ */
+local void send_all_trees(s, lcodes, dcodes, blcodes)
+    deflate_state *s;
+    int lcodes, dcodes, blcodes; /* number of codes for each tree */
+{
+    int rank;                    /* index in bl_order */
+
+    Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
+    Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
+            "too many codes");
+    Tracev((stderr, "\nbl counts: "));
+    send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
+    send_bits(s, dcodes-1,   5);
+    send_bits(s, blcodes-4,  4); /* not -3 as stated in appnote.txt */
+    for (rank = 0; rank < blcodes; rank++) {
+        Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
+        send_bits(s, s->bl_tree[bl_order[rank]].Len, 3);
+    }
+    Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
+
+    send_tree(s, (ct_data *)s->dyn_ltree, lcodes-1); /* literal tree */
+    Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
+
+    send_tree(s, (ct_data *)s->dyn_dtree, dcodes-1); /* distance tree */
+    Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
+}
+
+/* ===========================================================================
+ * Send a stored block
+ */
+void ZLIB_INTERNAL _tr_stored_block(s, buf, stored_len, last)
+    deflate_state *s;
+    charf *buf;       /* input block */
+    ulg stored_len;   /* length of input block */
+    int last;         /* one if this is the last block for a file */
+{
+    send_bits(s, (STORED_BLOCK<<1)+last, 3);    /* send block type */
+    bi_windup(s);        /* align on byte boundary */
+    put_short(s, (ush)stored_len);
+    put_short(s, (ush)~stored_len);
+    zmemcpy(s->pending_buf + s->pending, (Bytef *)buf, stored_len);
+    s->pending += stored_len;
+#ifdef ZLIB_DEBUG
+    s->compressed_len = (s->compressed_len + 3 + 7) & (ulg)~7L;
+    s->compressed_len += (stored_len + 4) << 3;
+    s->bits_sent += 2*16;
+    s->bits_sent += stored_len<<3;
+#endif
+}
+
+/* ===========================================================================
+ * Flush the bits in the bit buffer to pending output (leaves at most 7 bits)
+ */
+void ZLIB_INTERNAL _tr_flush_bits(s)
+    deflate_state *s;
+{
+    bi_flush(s);
+}
+
+/* ===========================================================================
+ * Send one empty static block to give enough lookahead for inflate.
+ * This takes 10 bits, of which 7 may remain in the bit buffer.
+ */
+void ZLIB_INTERNAL _tr_align(s)
+    deflate_state *s;
+{
+    send_bits(s, STATIC_TREES<<1, 3);
+    send_code(s, END_BLOCK, static_ltree);
+#ifdef ZLIB_DEBUG
+    s->compressed_len += 10L; /* 3 for block type, 7 for EOB */
+#endif
+    bi_flush(s);
+}
+
+/* ===========================================================================
+ * Determine the best encoding for the current block: dynamic trees, static
+ * trees or store, and write out the encoded block.
+ */
+void ZLIB_INTERNAL _tr_flush_block(s, buf, stored_len, last)
+    deflate_state *s;
+    charf *buf;       /* input block, or NULL if too old */
+    ulg stored_len;   /* length of input block */
+    int last;         /* one if this is the last block for a file */
+{
+    ulg opt_lenb, static_lenb; /* opt_len and static_len in bytes */
+    int max_blindex = 0;  /* index of last bit length code of non zero freq */
+
+    /* Build the Huffman trees unless a stored block is forced */
+    if (s->level > 0) {
+
+        /* Check if the file is binary or text */
+        if (s->strm->data_type == Z_UNKNOWN)
+            s->strm->data_type = detect_data_type(s);
+
+        /* Construct the literal and distance trees */
+        build_tree(s, (tree_desc *)(&(s->l_desc)));
+        Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
+                s->static_len));
+
+        build_tree(s, (tree_desc *)(&(s->d_desc)));
+        Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
+                s->static_len));
+        /* At this point, opt_len and static_len are the total bit lengths of
+         * the compressed block data, excluding the tree representations.
+         */
+
+        /* Build the bit length tree for the above two trees, and get the index
+         * in bl_order of the last bit length code to send.
+         */
+        max_blindex = build_bl_tree(s);
+
+        /* Determine the best encoding. Compute the block lengths in bytes. */
+        opt_lenb = (s->opt_len+3+7)>>3;
+        static_lenb = (s->static_len+3+7)>>3;
+
+        Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
+                opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
+                s->last_lit));
+
+        if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
+
+    } else {
+        Assert(buf != (char*)0, "lost buf");
+        opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
+    }
+
+#ifdef FORCE_STORED
+    if (buf != (char*)0) { /* force stored block */
+#else
+    if (stored_len+4 <= opt_lenb && buf != (char*)0) {
+                       /* 4: two words for the lengths */
+#endif
+        /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
+         * Otherwise we can't have processed more than WSIZE input bytes since
+         * the last block flush, because compression would have been
+         * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
+         * transform a block into a stored block.
+         */
+        _tr_stored_block(s, buf, stored_len, last);
+
+#ifdef FORCE_STATIC
+    } else if (static_lenb >= 0) { /* force static trees */
+#else
+    } else if (s->strategy == Z_FIXED || static_lenb == opt_lenb) {
+#endif
+        send_bits(s, (STATIC_TREES<<1)+last, 3);
+        compress_block(s, (const ct_data *)static_ltree,
+                       (const ct_data *)static_dtree);
+#ifdef ZLIB_DEBUG
+        s->compressed_len += 3 + s->static_len;
+#endif
+    } else {
+        send_bits(s, (DYN_TREES<<1)+last, 3);
+        send_all_trees(s, s->l_desc.max_code+1, s->d_desc.max_code+1,
+                       max_blindex+1);
+        compress_block(s, (const ct_data *)s->dyn_ltree,
+                       (const ct_data *)s->dyn_dtree);
+#ifdef ZLIB_DEBUG
+        s->compressed_len += 3 + s->opt_len;
+#endif
+    }
+    Assert (s->compressed_len == s->bits_sent, "bad compressed size");
+    /* The above check is made mod 2^32, for files larger than 512 MB
+     * and uLong implemented on 32 bits.
+     */
+    init_block(s);
+
+    if (last) {
+        bi_windup(s);
+#ifdef ZLIB_DEBUG
+        s->compressed_len += 7;  /* align on byte boundary */
+#endif
+    }
+    Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
+           s->compressed_len-7*last));
+}
+
+/* ===========================================================================
+ * Save the match info and tally the frequency counts. Return true if
+ * the current block must be flushed.
+ */
+int ZLIB_INTERNAL _tr_tally (s, dist, lc)
+    deflate_state *s;
+    unsigned dist;  /* distance of matched string */
+    unsigned lc;    /* match length-MIN_MATCH or unmatched char (if dist==0) */
+{
+    s->d_buf[s->last_lit] = (ush)dist;
+    s->l_buf[s->last_lit++] = (uch)lc;
+    if (dist == 0) {
+        /* lc is the unmatched char */
+        s->dyn_ltree[lc].Freq++;
+    } else {
+        s->matches++;
+        /* Here, lc is the match length - MIN_MATCH */
+        dist--;             /* dist = match distance - 1 */
+        Assert((ush)dist < (ush)MAX_DIST(s) &&
+               (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
+               (ush)d_code(dist) < (ush)D_CODES,  "_tr_tally: bad match");
+
+        s->dyn_ltree[_length_code[lc]+LITERALS+1].Freq++;
+        s->dyn_dtree[d_code(dist)].Freq++;
+    }
+
+#ifdef TRUNCATE_BLOCK
+    /* Try to guess if it is profitable to stop the current block here */
+    if ((s->last_lit & 0x1fff) == 0 && s->level > 2) {
+        /* Compute an upper bound for the compressed length */
+        ulg out_length = (ulg)s->last_lit*8L;
+        ulg in_length = (ulg)((long)s->strstart - s->block_start);
+        int dcode;
+        for (dcode = 0; dcode < D_CODES; dcode++) {
+            out_length += (ulg)s->dyn_dtree[dcode].Freq *
+                (5L+extra_dbits[dcode]);
+        }
+        out_length >>= 3;
+        Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
+               s->last_lit, in_length, out_length,
+               100L - out_length*100L/in_length));
+        if (s->matches < s->last_lit/2 && out_length < in_length/2) return 1;
+    }
+#endif
+    return (s->last_lit == s->lit_bufsize-1);
+    /* We avoid equality with lit_bufsize because of wraparound at 64K
+     * on 16 bit machines and because stored blocks are restricted to
+     * 64K-1 bytes.
+     */
+}
+
+/* ===========================================================================
+ * Send the block data compressed using the given Huffman trees
+ */
+local void compress_block(s, ltree, dtree)
+    deflate_state *s;
+    const ct_data *ltree; /* literal tree */
+    const ct_data *dtree; /* distance tree */
+{
+    unsigned dist;      /* distance of matched string */
+    int lc;             /* match length or unmatched char (if dist == 0) */
+    unsigned lx = 0;    /* running index in l_buf */
+    unsigned code;      /* the code to send */
+    int extra;          /* number of extra bits to send */
+
+    if (s->last_lit != 0) do {
+        dist = s->d_buf[lx];
+        lc = s->l_buf[lx++];
+        if (dist == 0) {
+            send_code(s, lc, ltree); /* send a literal byte */
+            Tracecv(isgraph(lc), (stderr," '%c' ", lc));
+        } else {
+            /* Here, lc is the match length - MIN_MATCH */
+            code = _length_code[lc];
+            send_code(s, code+LITERALS+1, ltree); /* send the length code */
+            extra = extra_lbits[code];
+            if (extra != 0) {
+                lc -= base_length[code];
+                send_bits(s, lc, extra);       /* send the extra length bits */
+            }
+            dist--; /* dist is now the match distance - 1 */
+            code = d_code(dist);
+            Assert (code < D_CODES, "bad d_code");
+
+            send_code(s, code, dtree);       /* send the distance code */
+            extra = extra_dbits[code];
+            if (extra != 0) {
+                dist -= (unsigned)base_dist[code];
+                send_bits(s, dist, extra);   /* send the extra distance bits */
+            }
+        } /* literal or match pair ? */
+
+        /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
+        Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
+               "pendingBuf overflow");
+
+    } while (lx < s->last_lit);
+
+    send_code(s, END_BLOCK, ltree);
+}
+
+/* ===========================================================================
+ * Check if the data type is TEXT or BINARY, using the following algorithm:
+ * - TEXT if the two conditions below are satisfied:
+ *    a) There are no non-portable control characters belonging to the
+ *       "black list" (0..6, 14..25, 28..31).
+ *    b) There is at least one printable character belonging to the
+ *       "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
+ * - BINARY otherwise.
+ * - The following partially-portable control characters form a
+ *   "gray list" that is ignored in this detection algorithm:
+ *   (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
+ * IN assertion: the fields Freq of dyn_ltree are set.
+ */
+local int detect_data_type(s)
+    deflate_state *s;
+{
+    /* black_mask is the bit mask of black-listed bytes
+     * set bits 0..6, 14..25, and 28..31
+     * 0xf3ffc07f = binary 11110011111111111100000001111111
+     */
+    unsigned long black_mask = 0xf3ffc07fUL;
+    int n;
+
+    /* Check for non-textual ("black-listed") bytes. */
+    for (n = 0; n <= 31; n++, black_mask >>= 1)
+        if ((black_mask & 1) && (s->dyn_ltree[n].Freq != 0))
+            return Z_BINARY;
+
+    /* Check for textual ("white-listed") bytes. */
+    if (s->dyn_ltree[9].Freq != 0 || s->dyn_ltree[10].Freq != 0
+            || s->dyn_ltree[13].Freq != 0)
+        return Z_TEXT;
+    for (n = 32; n < LITERALS; n++)
+        if (s->dyn_ltree[n].Freq != 0)
+            return Z_TEXT;
+
+    /* There are no "black-listed" or "white-listed" bytes:
+     * this stream either is empty or has tolerated ("gray-listed") bytes only.
+     */
+    return Z_BINARY;
+}
+
+/* ===========================================================================
+ * Reverse the first len bits of a code, using straightforward code (a faster
+ * method would use a table)
+ * IN assertion: 1 <= len <= 15
+ */
+local unsigned bi_reverse(code, len)
+    unsigned code; /* the value to invert */
+    int len;       /* its bit length */
+{
+    register unsigned res = 0;
+    do {
+        res |= code & 1;
+        code >>= 1, res <<= 1;
+    } while (--len > 0);
+    return res >> 1;
+}
+
+/* ===========================================================================
+ * Flush the bit buffer, keeping at most 7 bits in it.
+ */
+local void bi_flush(s)
+    deflate_state *s;
+{
+    if (s->bi_valid == 16) {
+        put_short(s, s->bi_buf);
+        s->bi_buf = 0;
+        s->bi_valid = 0;
+    } else if (s->bi_valid >= 8) {
+        put_byte(s, (Byte)s->bi_buf);
+        s->bi_buf >>= 8;
+        s->bi_valid -= 8;
+    }
+}
+
+/* ===========================================================================
+ * Flush the bit buffer and align the output on a byte boundary
+ */
+local void bi_windup(s)
+    deflate_state *s;
+{
+    if (s->bi_valid > 8) {
+        put_short(s, s->bi_buf);
+    } else if (s->bi_valid > 0) {
+        put_byte(s, (Byte)s->bi_buf);
+    }
+    s->bi_buf = 0;
+    s->bi_valid = 0;
+#ifdef ZLIB_DEBUG
+    s->bits_sent = (s->bits_sent+7) & ~7;
+#endif
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/trees.h	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,152 @@
+/*
+ * 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.
+ */
+
+/* header created automatically with -DGEN_TREES_H */
+
+local const ct_data static_ltree[L_CODES+2] = {
+{{ 12},{  8}}, {{140},{  8}}, {{ 76},{  8}}, {{204},{  8}}, {{ 44},{  8}},
+{{172},{  8}}, {{108},{  8}}, {{236},{  8}}, {{ 28},{  8}}, {{156},{  8}},
+{{ 92},{  8}}, {{220},{  8}}, {{ 60},{  8}}, {{188},{  8}}, {{124},{  8}},
+{{252},{  8}}, {{  2},{  8}}, {{130},{  8}}, {{ 66},{  8}}, {{194},{  8}},
+{{ 34},{  8}}, {{162},{  8}}, {{ 98},{  8}}, {{226},{  8}}, {{ 18},{  8}},
+{{146},{  8}}, {{ 82},{  8}}, {{210},{  8}}, {{ 50},{  8}}, {{178},{  8}},
+{{114},{  8}}, {{242},{  8}}, {{ 10},{  8}}, {{138},{  8}}, {{ 74},{  8}},
+{{202},{  8}}, {{ 42},{  8}}, {{170},{  8}}, {{106},{  8}}, {{234},{  8}},
+{{ 26},{  8}}, {{154},{  8}}, {{ 90},{  8}}, {{218},{  8}}, {{ 58},{  8}},
+{{186},{  8}}, {{122},{  8}}, {{250},{  8}}, {{  6},{  8}}, {{134},{  8}},
+{{ 70},{  8}}, {{198},{  8}}, {{ 38},{  8}}, {{166},{  8}}, {{102},{  8}},
+{{230},{  8}}, {{ 22},{  8}}, {{150},{  8}}, {{ 86},{  8}}, {{214},{  8}},
+{{ 54},{  8}}, {{182},{  8}}, {{118},{  8}}, {{246},{  8}}, {{ 14},{  8}},
+{{142},{  8}}, {{ 78},{  8}}, {{206},{  8}}, {{ 46},{  8}}, {{174},{  8}},
+{{110},{  8}}, {{238},{  8}}, {{ 30},{  8}}, {{158},{  8}}, {{ 94},{  8}},
+{{222},{  8}}, {{ 62},{  8}}, {{190},{  8}}, {{126},{  8}}, {{254},{  8}},
+{{  1},{  8}}, {{129},{  8}}, {{ 65},{  8}}, {{193},{  8}}, {{ 33},{  8}},
+{{161},{  8}}, {{ 97},{  8}}, {{225},{  8}}, {{ 17},{  8}}, {{145},{  8}},
+{{ 81},{  8}}, {{209},{  8}}, {{ 49},{  8}}, {{177},{  8}}, {{113},{  8}},
+{{241},{  8}}, {{  9},{  8}}, {{137},{  8}}, {{ 73},{  8}}, {{201},{  8}},
+{{ 41},{  8}}, {{169},{  8}}, {{105},{  8}}, {{233},{  8}}, {{ 25},{  8}},
+{{153},{  8}}, {{ 89},{  8}}, {{217},{  8}}, {{ 57},{  8}}, {{185},{  8}},
+{{121},{  8}}, {{249},{  8}}, {{  5},{  8}}, {{133},{  8}}, {{ 69},{  8}},
+{{197},{  8}}, {{ 37},{  8}}, {{165},{  8}}, {{101},{  8}}, {{229},{  8}},
+{{ 21},{  8}}, {{149},{  8}}, {{ 85},{  8}}, {{213},{  8}}, {{ 53},{  8}},
+{{181},{  8}}, {{117},{  8}}, {{245},{  8}}, {{ 13},{  8}}, {{141},{  8}},
+{{ 77},{  8}}, {{205},{  8}}, {{ 45},{  8}}, {{173},{  8}}, {{109},{  8}},
+{{237},{  8}}, {{ 29},{  8}}, {{157},{  8}}, {{ 93},{  8}}, {{221},{  8}},
+{{ 61},{  8}}, {{189},{  8}}, {{125},{  8}}, {{253},{  8}}, {{ 19},{  9}},
+{{275},{  9}}, {{147},{  9}}, {{403},{  9}}, {{ 83},{  9}}, {{339},{  9}},
+{{211},{  9}}, {{467},{  9}}, {{ 51},{  9}}, {{307},{  9}}, {{179},{  9}},
+{{435},{  9}}, {{115},{  9}}, {{371},{  9}}, {{243},{  9}}, {{499},{  9}},
+{{ 11},{  9}}, {{267},{  9}}, {{139},{  9}}, {{395},{  9}}, {{ 75},{  9}},
+{{331},{  9}}, {{203},{  9}}, {{459},{  9}}, {{ 43},{  9}}, {{299},{  9}},
+{{171},{  9}}, {{427},{  9}}, {{107},{  9}}, {{363},{  9}}, {{235},{  9}},
+{{491},{  9}}, {{ 27},{  9}}, {{283},{  9}}, {{155},{  9}}, {{411},{  9}},
+{{ 91},{  9}}, {{347},{  9}}, {{219},{  9}}, {{475},{  9}}, {{ 59},{  9}},
+{{315},{  9}}, {{187},{  9}}, {{443},{  9}}, {{123},{  9}}, {{379},{  9}},
+{{251},{  9}}, {{507},{  9}}, {{  7},{  9}}, {{263},{  9}}, {{135},{  9}},
+{{391},{  9}}, {{ 71},{  9}}, {{327},{  9}}, {{199},{  9}}, {{455},{  9}},
+{{ 39},{  9}}, {{295},{  9}}, {{167},{  9}}, {{423},{  9}}, {{103},{  9}},
+{{359},{  9}}, {{231},{  9}}, {{487},{  9}}, {{ 23},{  9}}, {{279},{  9}},
+{{151},{  9}}, {{407},{  9}}, {{ 87},{  9}}, {{343},{  9}}, {{215},{  9}},
+{{471},{  9}}, {{ 55},{  9}}, {{311},{  9}}, {{183},{  9}}, {{439},{  9}},
+{{119},{  9}}, {{375},{  9}}, {{247},{  9}}, {{503},{  9}}, {{ 15},{  9}},
+{{271},{  9}}, {{143},{  9}}, {{399},{  9}}, {{ 79},{  9}}, {{335},{  9}},
+{{207},{  9}}, {{463},{  9}}, {{ 47},{  9}}, {{303},{  9}}, {{175},{  9}},
+{{431},{  9}}, {{111},{  9}}, {{367},{  9}}, {{239},{  9}}, {{495},{  9}},
+{{ 31},{  9}}, {{287},{  9}}, {{159},{  9}}, {{415},{  9}}, {{ 95},{  9}},
+{{351},{  9}}, {{223},{  9}}, {{479},{  9}}, {{ 63},{  9}}, {{319},{  9}},
+{{191},{  9}}, {{447},{  9}}, {{127},{  9}}, {{383},{  9}}, {{255},{  9}},
+{{511},{  9}}, {{  0},{  7}}, {{ 64},{  7}}, {{ 32},{  7}}, {{ 96},{  7}},
+{{ 16},{  7}}, {{ 80},{  7}}, {{ 48},{  7}}, {{112},{  7}}, {{  8},{  7}},
+{{ 72},{  7}}, {{ 40},{  7}}, {{104},{  7}}, {{ 24},{  7}}, {{ 88},{  7}},
+{{ 56},{  7}}, {{120},{  7}}, {{  4},{  7}}, {{ 68},{  7}}, {{ 36},{  7}},
+{{100},{  7}}, {{ 20},{  7}}, {{ 84},{  7}}, {{ 52},{  7}}, {{116},{  7}},
+{{  3},{  8}}, {{131},{  8}}, {{ 67},{  8}}, {{195},{  8}}, {{ 35},{  8}},
+{{163},{  8}}, {{ 99},{  8}}, {{227},{  8}}
+};
+
+local const ct_data static_dtree[D_CODES] = {
+{{ 0},{ 5}}, {{16},{ 5}}, {{ 8},{ 5}}, {{24},{ 5}}, {{ 4},{ 5}},
+{{20},{ 5}}, {{12},{ 5}}, {{28},{ 5}}, {{ 2},{ 5}}, {{18},{ 5}},
+{{10},{ 5}}, {{26},{ 5}}, {{ 6},{ 5}}, {{22},{ 5}}, {{14},{ 5}},
+{{30},{ 5}}, {{ 1},{ 5}}, {{17},{ 5}}, {{ 9},{ 5}}, {{25},{ 5}},
+{{ 5},{ 5}}, {{21},{ 5}}, {{13},{ 5}}, {{29},{ 5}}, {{ 3},{ 5}},
+{{19},{ 5}}, {{11},{ 5}}, {{27},{ 5}}, {{ 7},{ 5}}, {{23},{ 5}}
+};
+
+const uch ZLIB_INTERNAL _dist_code[DIST_CODE_LEN] = {
+ 0,  1,  2,  3,  4,  4,  5,  5,  6,  6,  6,  6,  7,  7,  7,  7,  8,  8,  8,  8,
+ 8,  8,  8,  8,  9,  9,  9,  9,  9,  9,  9,  9, 10, 10, 10, 10, 10, 10, 10, 10,
+10, 10, 10, 10, 10, 10, 10, 10, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11, 11,
+11, 11, 11, 11, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12,
+12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 12, 13, 13, 13, 13,
+13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13, 13,
+13, 13, 13, 13, 13, 13, 13, 13, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14,
+14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 14, 15, 15, 15, 15, 15, 15, 15, 15,
+15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,
+15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15,  0,  0, 16, 17,
+18, 18, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 22, 22, 22, 22, 22, 22, 22, 22,
+23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+24, 24, 24, 24, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
+26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27,
+27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+27, 27, 27, 27, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28,
+28, 28, 28, 28, 28, 28, 28, 28, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29,
+29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29, 29
+};
+
+const uch ZLIB_INTERNAL _length_code[MAX_MATCH-MIN_MATCH+1]= {
+ 0,  1,  2,  3,  4,  5,  6,  7,  8,  8,  9,  9, 10, 10, 11, 11, 12, 12, 12, 12,
+13, 13, 13, 13, 14, 14, 14, 14, 15, 15, 15, 15, 16, 16, 16, 16, 16, 16, 16, 16,
+17, 17, 17, 17, 17, 17, 17, 17, 18, 18, 18, 18, 18, 18, 18, 18, 19, 19, 19, 19,
+19, 19, 19, 19, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20, 20,
+21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 21, 22, 22, 22, 22,
+22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 22, 23, 23, 23, 23, 23, 23, 23, 23,
+23, 23, 23, 23, 23, 23, 23, 23, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24, 24,
+25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25,
+25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 25, 26, 26, 26, 26, 26, 26, 26, 26,
+26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26, 26,
+26, 26, 26, 26, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27,
+27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 27, 28
+};
+
+local const int base_length[LENGTH_CODES] = {
+0, 1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 20, 24, 28, 32, 40, 48, 56,
+64, 80, 96, 112, 128, 160, 192, 224, 0
+};
+
+local const int base_dist[D_CODES] = {
+    0,     1,     2,     3,     4,     6,     8,    12,    16,    24,
+   32,    48,    64,    96,   128,   192,   256,   384,   512,   768,
+ 1024,  1536,  2048,  3072,  4096,  6144,  8192, 12288, 16384, 24576
+};
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/uncompr.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,117 @@
+/*
+ * 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.
+ */
+
+/* uncompr.c -- decompress a memory buffer
+ * Copyright (C) 1995-2003, 2010, 2014, 2016 Jean-loup Gailly, Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#define ZLIB_INTERNAL
+#include "zlib.h"
+
+/* ===========================================================================
+     Decompresses the source buffer into the destination buffer.  *sourceLen is
+   the byte length of the source buffer. Upon entry, *destLen is the total size
+   of the destination buffer, which must be large enough to hold the entire
+   uncompressed data. (The size of the uncompressed data must have been saved
+   previously by the compressor and transmitted to the decompressor by some
+   mechanism outside the scope of this compression library.) Upon exit,
+   *destLen is the size of the decompressed data and *sourceLen is the number
+   of source bytes consumed. Upon return, source + *sourceLen points to the
+   first unused input byte.
+
+     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_BUF_ERROR if there was not enough room in the output buffer, or
+   Z_DATA_ERROR if the input data was corrupted, including if the input data is
+   an incomplete zlib stream.
+*/
+int ZEXPORT uncompress2 (dest, destLen, source, sourceLen)
+    Bytef *dest;
+    uLongf *destLen;
+    const Bytef *source;
+    uLong *sourceLen;
+{
+    z_stream stream;
+    int err;
+    const uInt max = (uInt)-1;
+    uLong len, left;
+    Byte buf[1];    /* for detection of incomplete stream when *destLen == 0 */
+
+    len = *sourceLen;
+    if (*destLen) {
+        left = *destLen;
+        *destLen = 0;
+    }
+    else {
+        left = 1;
+        dest = buf;
+    }
+
+    stream.next_in = (z_const Bytef *)source;
+    stream.avail_in = 0;
+    stream.zalloc = (alloc_func)0;
+    stream.zfree = (free_func)0;
+    stream.opaque = (voidpf)0;
+
+    err = inflateInit(&stream);
+    if (err != Z_OK) return err;
+
+    stream.next_out = dest;
+    stream.avail_out = 0;
+
+    do {
+        if (stream.avail_out == 0) {
+            stream.avail_out = left > (uLong)max ? max : (uInt)left;
+            left -= stream.avail_out;
+        }
+        if (stream.avail_in == 0) {
+            stream.avail_in = len > (uLong)max ? max : (uInt)len;
+            len -= stream.avail_in;
+        }
+        err = inflate(&stream, Z_NO_FLUSH);
+    } while (err == Z_OK);
+
+    *sourceLen -= len + stream.avail_in;
+    if (dest != buf)
+        *destLen = stream.total_out;
+    else if (stream.total_out && err == Z_BUF_ERROR)
+        left = 1;
+
+    inflateEnd(&stream);
+    return err == Z_STREAM_END ? Z_OK :
+           err == Z_NEED_DICT ? Z_DATA_ERROR  :
+           err == Z_BUF_ERROR && left + stream.avail_out ? Z_DATA_ERROR :
+           err;
+}
+
+int ZEXPORT uncompress (dest, destLen, source, sourceLen)
+    Bytef *dest;
+    uLongf *destLen;
+    const Bytef *source;
+    uLong sourceLen;
+{
+    return uncompress2(dest, destLen, source, &sourceLen);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/zadler32.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,210 @@
+/*
+ * 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.
+ */
+
+/* adler32.c -- compute the Adler-32 checksum of a data stream
+ * Copyright (C) 1995-2011, 2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#include "zutil.h"
+
+local uLong adler32_combine_ OF((uLong adler1, uLong adler2, z_off64_t len2));
+
+#define BASE 65521U     /* largest prime smaller than 65536 */
+#define NMAX 5552
+/* NMAX is the largest n such that 255n(n+1)/2 + (n+1)(BASE-1) <= 2^32-1 */
+
+#define DO1(buf,i)  {adler += (buf)[i]; sum2 += adler;}
+#define DO2(buf,i)  DO1(buf,i); DO1(buf,i+1);
+#define DO4(buf,i)  DO2(buf,i); DO2(buf,i+2);
+#define DO8(buf,i)  DO4(buf,i); DO4(buf,i+4);
+#define DO16(buf)   DO8(buf,0); DO8(buf,8);
+
+/* use NO_DIVIDE if your processor does not do division in hardware --
+   try it both ways to see which is faster */
+#ifdef NO_DIVIDE
+/* note that this assumes BASE is 65521, where 65536 % 65521 == 15
+   (thank you to John Reiser for pointing this out) */
+#  define CHOP(a) \
+    do { \
+        unsigned long tmp = a >> 16; \
+        a &= 0xffffUL; \
+        a += (tmp << 4) - tmp; \
+    } while (0)
+#  define MOD28(a) \
+    do { \
+        CHOP(a); \
+        if (a >= BASE) a -= BASE; \
+    } while (0)
+#  define MOD(a) \
+    do { \
+        CHOP(a); \
+        MOD28(a); \
+    } while (0)
+#  define MOD63(a) \
+    do { /* this assumes a is not negative */ \
+        z_off64_t tmp = a >> 32; \
+        a &= 0xffffffffL; \
+        a += (tmp << 8) - (tmp << 5) + tmp; \
+        tmp = a >> 16; \
+        a &= 0xffffL; \
+        a += (tmp << 4) - tmp; \
+        tmp = a >> 16; \
+        a &= 0xffffL; \
+        a += (tmp << 4) - tmp; \
+        if (a >= BASE) a -= BASE; \
+    } while (0)
+#else
+#  define MOD(a) a %= BASE
+#  define MOD28(a) a %= BASE
+#  define MOD63(a) a %= BASE
+#endif
+
+/* ========================================================================= */
+uLong ZEXPORT adler32_z(adler, buf, len)
+    uLong adler;
+    const Bytef *buf;
+    z_size_t len;
+{
+    unsigned long sum2;
+    unsigned n;
+
+    /* split Adler-32 into component sums */
+    sum2 = (adler >> 16) & 0xffff;
+    adler &= 0xffff;
+
+    /* in case user likes doing a byte at a time, keep it fast */
+    if (len == 1) {
+        adler += buf[0];
+        if (adler >= BASE)
+            adler -= BASE;
+        sum2 += adler;
+        if (sum2 >= BASE)
+            sum2 -= BASE;
+        return adler | (sum2 << 16);
+    }
+
+    /* initial Adler-32 value (deferred check for len == 1 speed) */
+    if (buf == Z_NULL)
+        return 1L;
+
+    /* in case short lengths are provided, keep it somewhat fast */
+    if (len < 16) {
+        while (len--) {
+            adler += *buf++;
+            sum2 += adler;
+        }
+        if (adler >= BASE)
+            adler -= BASE;
+        MOD28(sum2);            /* only added so many BASE's */
+        return adler | (sum2 << 16);
+    }
+
+    /* do length NMAX blocks -- requires just one modulo operation */
+    while (len >= NMAX) {
+        len -= NMAX;
+        n = NMAX / 16;          /* NMAX is divisible by 16 */
+        do {
+            DO16(buf);          /* 16 sums unrolled */
+            buf += 16;
+        } while (--n);
+        MOD(adler);
+        MOD(sum2);
+    }
+
+    /* do remaining bytes (less than NMAX, still just one modulo) */
+    if (len) {                  /* avoid modulos if none remaining */
+        while (len >= 16) {
+            len -= 16;
+            DO16(buf);
+            buf += 16;
+        }
+        while (len--) {
+            adler += *buf++;
+            sum2 += adler;
+        }
+        MOD(adler);
+        MOD(sum2);
+    }
+
+    /* return recombined sums */
+    return adler | (sum2 << 16);
+}
+
+/* ========================================================================= */
+uLong ZEXPORT adler32(adler, buf, len)
+    uLong adler;
+    const Bytef *buf;
+    uInt len;
+{
+    return adler32_z(adler, buf, len);
+}
+
+/* ========================================================================= */
+local uLong adler32_combine_(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off64_t len2;
+{
+    unsigned long sum1;
+    unsigned long sum2;
+    unsigned rem;
+
+    /* for negative len, return invalid adler32 as a clue for debugging */
+    if (len2 < 0)
+        return 0xffffffffUL;
+
+    /* the derivation of this formula is left as an exercise for the reader */
+    MOD63(len2);                /* assumes len2 >= 0 */
+    rem = (unsigned)len2;
+    sum1 = adler1 & 0xffff;
+    sum2 = rem * sum1;
+    MOD(sum2);
+    sum1 += (adler2 & 0xffff) + BASE - 1;
+    sum2 += ((adler1 >> 16) & 0xffff) + ((adler2 >> 16) & 0xffff) + BASE - rem;
+    if (sum1 >= BASE) sum1 -= BASE;
+    if (sum1 >= BASE) sum1 -= BASE;
+    if (sum2 >= ((unsigned long)BASE << 1)) sum2 -= ((unsigned long)BASE << 1);
+    if (sum2 >= BASE) sum2 -= BASE;
+    return sum1 | (sum2 << 16);
+}
+
+/* ========================================================================= */
+uLong ZEXPORT adler32_combine(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off_t len2;
+{
+    return adler32_combine_(adler1, adler2, len2);
+}
+
+uLong ZEXPORT adler32_combine64(adler1, adler2, len2)
+    uLong adler1;
+    uLong adler2;
+    z_off64_t len2;
+{
+    return adler32_combine_(adler1, adler2, len2);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/zconf.h	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,566 @@
+/*
+ * 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.
+ */
+
+/* zconf.h -- configuration of the zlib compression library
+ * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#ifndef ZCONF_H
+#define ZCONF_H
+
+/* for _LP64 */
+#include <sys/types.h>
+
+/*
+ * If you *really* need a unique prefix for all types and library functions,
+ * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
+ * Even better than compiling with -DZ_PREFIX would be to use configure to set
+ * this permanently in zconf.h using "./configure --zprefix".
+ */
+#ifdef Z_PREFIX     /* may be set to #if 1 by ./configure */
+#  define Z_PREFIX_SET
+
+/* all linked symbols and init macros */
+#  define _dist_code            z__dist_code
+#  define _length_code          z__length_code
+#  define _tr_align             z__tr_align
+#  define _tr_flush_bits        z__tr_flush_bits
+#  define _tr_flush_block       z__tr_flush_block
+#  define _tr_init              z__tr_init
+#  define _tr_stored_block      z__tr_stored_block
+#  define _tr_tally             z__tr_tally
+#  define adler32               z_adler32
+#  define adler32_combine       z_adler32_combine
+#  define adler32_combine64     z_adler32_combine64
+#  define adler32_z             z_adler32_z
+#  ifndef Z_SOLO
+#    define compress              z_compress
+#    define compress2             z_compress2
+#    define compressBound         z_compressBound
+#  endif
+#  define crc32                 z_crc32
+#  define crc32_combine         z_crc32_combine
+#  define crc32_combine64       z_crc32_combine64
+#  define crc32_z               z_crc32_z
+#  define deflate               z_deflate
+#  define deflateBound          z_deflateBound
+#  define deflateCopy           z_deflateCopy
+#  define deflateEnd            z_deflateEnd
+#  define deflateGetDictionary  z_deflateGetDictionary
+#  define deflateInit           z_deflateInit
+#  define deflateInit2          z_deflateInit2
+#  define deflateInit2_         z_deflateInit2_
+#  define deflateInit_          z_deflateInit_
+#  define deflateParams         z_deflateParams
+#  define deflatePending        z_deflatePending
+#  define deflatePrime          z_deflatePrime
+#  define deflateReset          z_deflateReset
+#  define deflateResetKeep      z_deflateResetKeep
+#  define deflateSetDictionary  z_deflateSetDictionary
+#  define deflateSetHeader      z_deflateSetHeader
+#  define deflateTune           z_deflateTune
+#  define deflate_copyright     z_deflate_copyright
+#  define get_crc_table         z_get_crc_table
+#  ifndef Z_SOLO
+#    define gz_error              z_gz_error
+#    define gz_intmax             z_gz_intmax
+#    define gz_strwinerror        z_gz_strwinerror
+#    define gzbuffer              z_gzbuffer
+#    define gzclearerr            z_gzclearerr
+#    define gzclose               z_gzclose
+#    define gzclose_r             z_gzclose_r
+#    define gzclose_w             z_gzclose_w
+#    define gzdirect              z_gzdirect
+#    define gzdopen               z_gzdopen
+#    define gzeof                 z_gzeof
+#    define gzerror               z_gzerror
+#    define gzflush               z_gzflush
+#    define gzfread               z_gzfread
+#    define gzfwrite              z_gzfwrite
+#    define gzgetc                z_gzgetc
+#    define gzgetc_               z_gzgetc_
+#    define gzgets                z_gzgets
+#    define gzoffset              z_gzoffset
+#    define gzoffset64            z_gzoffset64
+#    define gzopen                z_gzopen
+#    define gzopen64              z_gzopen64
+#    ifdef _WIN32
+#      define gzopen_w              z_gzopen_w
+#    endif
+#    define gzprintf              z_gzprintf
+#    define gzputc                z_gzputc
+#    define gzputs                z_gzputs
+#    define gzread                z_gzread
+#    define gzrewind              z_gzrewind
+#    define gzseek                z_gzseek
+#    define gzseek64              z_gzseek64
+#    define gzsetparams           z_gzsetparams
+#    define gztell                z_gztell
+#    define gztell64              z_gztell64
+#    define gzungetc              z_gzungetc
+#    define gzvprintf             z_gzvprintf
+#    define gzwrite               z_gzwrite
+#  endif
+#  define inflate               z_inflate
+#  define inflateBack           z_inflateBack
+#  define inflateBackEnd        z_inflateBackEnd
+#  define inflateBackInit       z_inflateBackInit
+#  define inflateBackInit_      z_inflateBackInit_
+#  define inflateCodesUsed      z_inflateCodesUsed
+#  define inflateCopy           z_inflateCopy
+#  define inflateEnd            z_inflateEnd
+#  define inflateGetDictionary  z_inflateGetDictionary
+#  define inflateGetHeader      z_inflateGetHeader
+#  define inflateInit           z_inflateInit
+#  define inflateInit2          z_inflateInit2
+#  define inflateInit2_         z_inflateInit2_
+#  define inflateInit_          z_inflateInit_
+#  define inflateMark           z_inflateMark
+#  define inflatePrime          z_inflatePrime
+#  define inflateReset          z_inflateReset
+#  define inflateReset2         z_inflateReset2
+#  define inflateResetKeep      z_inflateResetKeep
+#  define inflateSetDictionary  z_inflateSetDictionary
+#  define inflateSync           z_inflateSync
+#  define inflateSyncPoint      z_inflateSyncPoint
+#  define inflateUndermine      z_inflateUndermine
+#  define inflateValidate       z_inflateValidate
+#  define inflate_copyright     z_inflate_copyright
+#  define inflate_fast          z_inflate_fast
+#  define inflate_table         z_inflate_table
+#  ifndef Z_SOLO
+#    define uncompress            z_uncompress
+#    define uncompress2           z_uncompress2
+#  endif
+#  define zError                z_zError
+#  ifndef Z_SOLO
+#    define zcalloc               z_zcalloc
+#    define zcfree                z_zcfree
+#  endif
+#  define zlibCompileFlags      z_zlibCompileFlags
+#  define zlibVersion           z_zlibVersion
+
+/* all zlib typedefs in zlib.h and zconf.h */
+#  define Byte                  z_Byte
+#  define Bytef                 z_Bytef
+#  define alloc_func            z_alloc_func
+#  define charf                 z_charf
+#  define free_func             z_free_func
+#  ifndef Z_SOLO
+#    define gzFile                z_gzFile
+#  endif
+#  define gz_header             z_gz_header
+#  define gz_headerp            z_gz_headerp
+#  define in_func               z_in_func
+#  define intf                  z_intf
+#  define out_func              z_out_func
+#  define uInt                  z_uInt
+#  define uIntf                 z_uIntf
+#  define uLong                 z_uLong
+#  define uLongf                z_uLongf
+#  define voidp                 z_voidp
+#  define voidpc                z_voidpc
+#  define voidpf                z_voidpf
+
+/* all zlib structs in zlib.h and zconf.h */
+#  define gz_header_s           z_gz_header_s
+#  define internal_state        z_internal_state
+
+#endif
+
+#if defined(__MSDOS__) && !defined(MSDOS)
+#  define MSDOS
+#endif
+#if (defined(OS_2) || defined(__OS2__)) && !defined(OS2)
+#  define OS2
+#endif
+#if defined(_WINDOWS) && !defined(WINDOWS)
+#  define WINDOWS
+#endif
+#if defined(_WIN32) || defined(_WIN32_WCE) || defined(__WIN32__)
+#  ifndef WIN32
+#    define WIN32
+#  endif
+#endif
+#if (defined(MSDOS) || defined(OS2) || defined(WINDOWS)) && !defined(WIN32)
+#  if !defined(__GNUC__) && !defined(__FLAT__) && !defined(__386__)
+#    ifndef SYS16BIT
+#      define SYS16BIT
+#    endif
+#  endif
+#endif
+
+/*
+ * Compile with -DMAXSEG_64K if the alloc function cannot allocate more
+ * than 64k bytes at a time (needed on systems with 16-bit int).
+ */
+#ifdef SYS16BIT
+#  define MAXSEG_64K
+#endif
+#ifdef MSDOS
+#  define UNALIGNED_OK
+#endif
+
+#ifdef __STDC_VERSION__
+#  ifndef STDC
+#    define STDC
+#  endif
+#  if __STDC_VERSION__ >= 199901L
+#    ifndef STDC99
+#      define STDC99
+#    endif
+#  endif
+#endif
+#if !defined(STDC) && (defined(__STDC__) || defined(__cplusplus))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(__GNUC__) || defined(__BORLANDC__))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(MSDOS) || defined(WINDOWS) || defined(WIN32))
+#  define STDC
+#endif
+#if !defined(STDC) && (defined(OS2) || defined(__HOS_AIX__))
+#  define STDC
+#endif
+
+#if defined(__OS400__) && !defined(STDC)    /* iSeries (formerly AS/400). */
+#  define STDC
+#endif
+
+#ifndef STDC
+#  ifndef const /* cannot use !defined(STDC) && !defined(const) on Mac */
+#    define const       /* note: need a more gentle solution here */
+#  endif
+#endif
+
+#if defined(ZLIB_CONST) && !defined(z_const)
+#  define z_const const
+#else
+#  define z_const
+#endif
+
+#ifdef Z_SOLO
+   typedef unsigned long z_size_t;
+#else
+#  define z_longlong long long
+#  if defined(NO_SIZE_T)
+     typedef unsigned NO_SIZE_T z_size_t;
+#  elif defined(STDC)
+#    include <stddef.h>
+     typedef size_t z_size_t;
+#  else
+     typedef unsigned long z_size_t;
+#  endif
+#  undef z_longlong
+#endif
+
+/* Maximum value for memLevel in deflateInit2 */
+#ifndef MAX_MEM_LEVEL
+#  ifdef MAXSEG_64K
+#    define MAX_MEM_LEVEL 8
+#  else
+#    define MAX_MEM_LEVEL 9
+#  endif
+#endif
+
+/* Maximum value for windowBits in deflateInit2 and inflateInit2.
+ * WARNING: reducing MAX_WBITS makes minigzip unable to extract .gz files
+ * created by gzip. (Files created by minigzip can still be extracted by
+ * gzip.)
+ */
+#ifndef MAX_WBITS
+#  define MAX_WBITS   15 /* 32K LZ77 window */
+#endif
+
+/* The memory requirements for deflate are (in bytes):
+            (1 << (windowBits+2)) +  (1 << (memLevel+9))
+ that is: 128K for windowBits=15  +  128K for memLevel = 8  (default values)
+ plus a few kilobytes for small objects. For example, if you want to reduce
+ the default memory requirements from 256K to 128K, compile with
+     make CFLAGS="-O -DMAX_WBITS=14 -DMAX_MEM_LEVEL=7"
+ Of course this will generally degrade compression (there's no free lunch).
+
+   The memory requirements for inflate are (in bytes) 1 << windowBits
+ that is, 32K for windowBits=15 (default value) plus about 7 kilobytes
+ for small objects.
+*/
+
+                        /* Type declarations */
+
+#ifndef OF /* function prototypes */
+#  ifdef STDC
+#    define OF(args)  args
+#  else
+#    define OF(args)  ()
+#  endif
+#endif
+
+#ifndef Z_ARG /* function prototypes for stdarg */
+#  if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#    define Z_ARG(args)  args
+#  else
+#    define Z_ARG(args)  ()
+#  endif
+#endif
+
+/* The following definitions for FAR are needed only for MSDOS mixed
+ * model programming (small or medium model with some far allocations).
+ * This was tested only with MSC; for other MSDOS compilers you may have
+ * to define NO_MEMCPY in zutil.h.  If you don't need the mixed model,
+ * just define FAR to be empty.
+ */
+#ifdef SYS16BIT
+#  if defined(M_I86SM) || defined(M_I86MM)
+     /* MSC small or medium model */
+#    define SMALL_MEDIUM
+#    ifdef _MSC_VER
+#      define FAR _far
+#    else
+#      define FAR far
+#    endif
+#  endif
+#  if (defined(__SMALL__) || defined(__MEDIUM__))
+     /* Turbo C small or medium model */
+#    define SMALL_MEDIUM
+#    ifdef __BORLANDC__
+#      define FAR _far
+#    else
+#      define FAR far
+#    endif
+#  endif
+#endif
+
+#if defined(WINDOWS) || defined(WIN32)
+   /* If building or using zlib as a DLL, define ZLIB_DLL.
+    * This is not mandatory, but it offers a little performance increase.
+    */
+#  ifdef ZLIB_DLL
+#    if defined(WIN32) && (!defined(__BORLANDC__) || (__BORLANDC__ >= 0x500))
+#      ifdef ZLIB_INTERNAL
+#        define ZEXTERN extern __declspec(dllexport)
+#      else
+#        define ZEXTERN extern __declspec(dllimport)
+#      endif
+#    endif
+#  endif  /* ZLIB_DLL */
+   /* If building or using zlib with the WINAPI/WINAPIV calling convention,
+    * define ZLIB_WINAPI.
+    * Caution: the standard ZLIB1.DLL is NOT compiled using ZLIB_WINAPI.
+    */
+#  ifdef ZLIB_WINAPI
+#    ifdef FAR
+#      undef FAR
+#    endif
+#    include <windows.h>
+     /* No need for _export, use ZLIB.DEF instead. */
+     /* For complete Windows compatibility, use WINAPI, not __stdcall. */
+#    define ZEXPORT WINAPI
+#    ifdef WIN32
+#      define ZEXPORTVA WINAPIV
+#    else
+#      define ZEXPORTVA FAR CDECL
+#    endif
+#  endif
+#endif
+
+#if defined (__BEOS__)
+#  ifdef ZLIB_DLL
+#    ifdef ZLIB_INTERNAL
+#      define ZEXPORT   __declspec(dllexport)
+#      define ZEXPORTVA __declspec(dllexport)
+#    else
+#      define ZEXPORT   __declspec(dllimport)
+#      define ZEXPORTVA __declspec(dllimport)
+#    endif
+#  endif
+#endif
+
+#ifndef ZEXTERN
+#  define ZEXTERN extern
+#endif
+#ifndef ZEXPORT
+#  define ZEXPORT
+#endif
+#ifndef ZEXPORTVA
+#  define ZEXPORTVA
+#endif
+
+#ifndef FAR
+#  define FAR
+#endif
+
+#if !defined(__MACTYPES__)
+typedef unsigned char  Byte;  /* 8 bits */
+#endif
+typedef unsigned int   uInt;  /* 16 bits or more */
+
+#ifdef _LP64
+typedef unsigned int  uLong;  /* 32 bits or more */
+#else
+typedef unsigned long  uLong; /* 32 bits or more */
+#endif
+
+#ifdef SMALL_MEDIUM
+   /* Borland C/C++ and some old MSC versions ignore FAR inside typedef */
+#  define Bytef Byte FAR
+#else
+   typedef Byte  FAR Bytef;
+#endif
+typedef char  FAR charf;
+typedef int   FAR intf;
+typedef uInt  FAR uIntf;
+typedef uLong FAR uLongf;
+
+#ifdef STDC
+   typedef void const *voidpc;
+   typedef void FAR   *voidpf;
+   typedef void       *voidp;
+#else
+   typedef Byte const *voidpc;
+   typedef Byte FAR   *voidpf;
+   typedef Byte       *voidp;
+#endif
+
+#if !defined(Z_U4) && !defined(Z_SOLO) && defined(STDC)
+#  include <limits.h>
+#  if (UINT_MAX == 0xffffffffUL)
+#    define Z_U4 unsigned
+#  elif (ULONG_MAX == 0xffffffffUL)
+#    define Z_U4 unsigned long
+#  elif (USHRT_MAX == 0xffffffffUL)
+#    define Z_U4 unsigned short
+#  endif
+#endif
+
+#ifdef Z_U4
+   typedef Z_U4 z_crc_t;
+#else
+   typedef unsigned long z_crc_t;
+#endif
+
+#ifdef HAVE_UNISTD_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_UNISTD_H
+#endif
+
+#ifdef HAVE_STDARG_H    /* may be set to #if 1 by ./configure */
+#  define Z_HAVE_STDARG_H
+#endif
+
+#ifdef STDC
+#  ifndef Z_SOLO
+#    include <sys/types.h>      /* for off_t */
+#  endif
+#endif
+
+#if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#  ifndef Z_SOLO
+#    include <stdarg.h>         /* for va_list */
+#  endif
+#endif
+
+#ifdef _WIN32
+#  ifndef Z_SOLO
+#    include <stddef.h>         /* for wchar_t */
+#  endif
+#endif
+
+/* a little trick to accommodate both "#define _LARGEFILE64_SOURCE" and
+ * "#define _LARGEFILE64_SOURCE 1" as requesting 64-bit operations, (even
+ * though the former does not conform to the LFS document), but considering
+ * both "#undef _LARGEFILE64_SOURCE" and "#define _LARGEFILE64_SOURCE 0" as
+ * equivalently requesting no 64-bit operations
+ */
+#if defined(_LARGEFILE64_SOURCE) && -_LARGEFILE64_SOURCE - -1 == 1
+#  undef _LARGEFILE64_SOURCE
+#endif
+
+#if defined(__WATCOMC__) && !defined(Z_HAVE_UNISTD_H)
+#  define Z_HAVE_UNISTD_H
+#endif
+#ifndef Z_SOLO
+#  if defined(Z_HAVE_UNISTD_H) || defined(_LARGEFILE64_SOURCE)
+#    include <unistd.h>         /* for SEEK_*, off_t, and _LFS64_LARGEFILE */
+#    ifdef VMS
+#      include <unixio.h>       /* for off_t */
+#    endif
+#    ifndef z_off_t
+#      define z_off_t off_t
+#    endif
+#  endif
+#endif
+
+#if defined(_LFS64_LARGEFILE) && _LFS64_LARGEFILE-0
+#  define Z_LFS64
+#endif
+
+#if defined(_LARGEFILE64_SOURCE) && defined(Z_LFS64)
+#  define Z_LARGE64
+#endif
+
+#if defined(_FILE_OFFSET_BITS) && _FILE_OFFSET_BITS-0 == 64 && defined(Z_LFS64)
+#  define Z_WANT64
+#endif
+
+#if !defined(SEEK_SET) && !defined(Z_SOLO)
+#  define SEEK_SET        0       /* Seek from beginning of file.  */
+#  define SEEK_CUR        1       /* Seek from current position.  */
+#  define SEEK_END        2       /* Set file pointer to EOF plus "offset" */
+#endif
+
+#ifndef z_off_t
+#  define z_off_t long
+#endif
+
+#if !defined(_WIN32) && defined(Z_LARGE64)
+#  define z_off64_t off64_t
+#else
+#  if defined(_WIN32) && !defined(__GNUC__) && !defined(Z_SOLO)
+#    define z_off64_t __int64
+#  else
+#    define z_off64_t z_off_t
+#  endif
+#endif
+
+/* MVS linker does not support external names larger than 8 bytes */
+#if defined(__MVS__)
+  #pragma map(deflateInit_,"DEIN")
+  #pragma map(deflateInit2_,"DEIN2")
+  #pragma map(deflateEnd,"DEEND")
+  #pragma map(deflateBound,"DEBND")
+  #pragma map(inflateInit_,"ININ")
+  #pragma map(inflateInit2_,"ININ2")
+  #pragma map(inflateEnd,"INEND")
+  #pragma map(inflateSync,"INSY")
+  #pragma map(inflateSetDictionary,"INSEDI")
+  #pragma map(compressBound,"CMBND")
+  #pragma map(inflate_table,"INTABL")
+  #pragma map(inflate_fast,"INFA")
+  #pragma map(inflate_copyright,"INCOPY")
+#endif
+
+#endif /* ZCONF_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/zcrc32.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,466 @@
+/*
+ * 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.
+ */
+
+/* crc32.c -- compute the CRC-32 of a data stream
+ * Copyright (C) 1995-2006, 2010, 2011, 2012, 2016 Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ *
+ * Thanks to Rodney Brown <rbrown64@csc.com.au> for his contribution of faster
+ * CRC methods: exclusive-oring 32 bits of data at a time, and pre-computing
+ * tables for updating the shift register in one step with three exclusive-ors
+ * instead of four steps with four exclusive-ors.  This results in about a
+ * factor of two increase in speed on a Power PC G4 (PPC7455) using gcc -O3.
+ */
+
+/* @(#) $Id$ */
+
+/*
+  Note on the use of DYNAMIC_CRC_TABLE: there is no mutex or semaphore
+  protection on the static variables used to control the first-use generation
+  of the crc tables.  Therefore, if you #define DYNAMIC_CRC_TABLE, you should
+  first call get_crc_table() to initialize the tables before allowing more than
+  one thread to use crc32().
+
+  DYNAMIC_CRC_TABLE and MAKECRCH can be #defined to write out crc32.h.
+ */
+
+#ifdef MAKECRCH
+#  include <stdio.h>
+#  ifndef DYNAMIC_CRC_TABLE
+#    define DYNAMIC_CRC_TABLE
+#  endif /* !DYNAMIC_CRC_TABLE */
+#endif /* MAKECRCH */
+
+#include "zutil.h"      /* for STDC and FAR definitions */
+
+/* Definitions for doing the crc four data bytes at a time. */
+#if !defined(NOBYFOUR) && defined(Z_U4)
+#  define BYFOUR
+#endif
+#ifdef BYFOUR
+   local unsigned long crc32_little OF((unsigned long,
+                        const unsigned char FAR *, z_size_t));
+   local unsigned long crc32_big OF((unsigned long,
+                        const unsigned char FAR *, z_size_t));
+#  define TBLS 8
+#else
+#  define TBLS 1
+#endif /* BYFOUR */
+
+/* Local functions for crc concatenation */
+local unsigned long gf2_matrix_times OF((unsigned long *mat,
+                                         unsigned long vec));
+local void gf2_matrix_square OF((unsigned long *square, unsigned long *mat));
+local uLong crc32_combine_ OF((uLong crc1, uLong crc2, z_off64_t len2));
+
+
+#ifdef DYNAMIC_CRC_TABLE
+
+local volatile int crc_table_empty = 1;
+local z_crc_t FAR crc_table[TBLS][256];
+local void make_crc_table OF((void));
+#ifdef MAKECRCH
+   local void write_table OF((FILE *, const z_crc_t FAR *));
+#endif /* MAKECRCH */
+/*
+  Generate tables for a byte-wise 32-bit CRC calculation on the polynomial:
+  x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
+
+  Polynomials over GF(2) are represented in binary, one bit per coefficient,
+  with the lowest powers in the most significant bit.  Then adding polynomials
+  is just exclusive-or, and multiplying a polynomial by x is a right shift by
+  one.  If we call the above polynomial p, and represent a byte as the
+  polynomial q, also with the lowest power in the most significant bit (so the
+  byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
+  where a mod b means the remainder after dividing a by b.
+
+  This calculation is done using the shift-register method of multiplying and
+  taking the remainder.  The register is initialized to zero, and for each
+  incoming bit, x^32 is added mod p to the register if the bit is a one (where
+  x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
+  x (which is shifting right by one and adding x^32 mod p if the bit shifted
+  out is a one).  We start with the highest power (least significant bit) of
+  q and repeat for all eight bits of q.
+
+  The first table is simply the CRC of all possible eight bit values.  This is
+  all the information needed to generate CRCs on data a byte at a time for all
+  combinations of CRC register values and incoming bytes.  The remaining tables
+  allow for word-at-a-time CRC calculation for both big-endian and little-
+  endian machines, where a word is four bytes.
+*/
+local void make_crc_table()
+{
+    z_crc_t c;
+    int n, k;
+    z_crc_t poly;                       /* polynomial exclusive-or pattern */
+    /* terms of polynomial defining this crc (except x^32): */
+    static volatile int first = 1;      /* flag to limit concurrent making */
+    static const unsigned char p[] = {0,1,2,4,5,7,8,10,11,12,16,22,23,26};
+
+    /* See if another task is already doing this (not thread-safe, but better
+       than nothing -- significantly reduces duration of vulnerability in
+       case the advice about DYNAMIC_CRC_TABLE is ignored) */
+    if (first) {
+        first = 0;
+
+        /* make exclusive-or pattern from polynomial (0xedb88320UL) */
+        poly = 0;
+        for (n = 0; n < (int)(sizeof(p)/sizeof(unsigned char)); n++)
+            poly |= (z_crc_t)1 << (31 - p[n]);
+
+        /* generate a crc for every 8-bit value */
+        for (n = 0; n < 256; n++) {
+            c = (z_crc_t)n;
+            for (k = 0; k < 8; k++)
+                c = c & 1 ? poly ^ (c >> 1) : c >> 1;
+            crc_table[0][n] = c;
+        }
+
+#ifdef BYFOUR
+        /* generate crc for each value followed by one, two, and three zeros,
+           and then the byte reversal of those as well as the first table */
+        for (n = 0; n < 256; n++) {
+            c = crc_table[0][n];
+            crc_table[4][n] = ZSWAP32(c);
+            for (k = 1; k < 4; k++) {
+                c = crc_table[0][c & 0xff] ^ (c >> 8);
+                crc_table[k][n] = c;
+                crc_table[k + 4][n] = ZSWAP32(c);
+            }
+        }
+#endif /* BYFOUR */
+
+        crc_table_empty = 0;
+    }
+    else {      /* not first */
+        /* wait for the other guy to finish (not efficient, but rare) */
+        while (crc_table_empty)
+            ;
+    }
+
+#ifdef MAKECRCH
+    /* write out CRC tables to crc32.h */
+    {
+        FILE *out;
+
+        out = fopen("crc32.h", "w");
+        if (out == NULL) return;
+        fprintf(out, "/* crc32.h -- tables for rapid CRC calculation\n");
+        fprintf(out, " * Generated automatically by crc32.c\n */\n\n");
+        fprintf(out, "local const z_crc_t FAR ");
+        fprintf(out, "crc_table[TBLS][256] =\n{\n  {\n");
+        write_table(out, crc_table[0]);
+#  ifdef BYFOUR
+        fprintf(out, "#ifdef BYFOUR\n");
+        for (k = 1; k < 8; k++) {
+            fprintf(out, "  },\n  {\n");
+            write_table(out, crc_table[k]);
+        }
+        fprintf(out, "#endif\n");
+#  endif /* BYFOUR */
+        fprintf(out, "  }\n};\n");
+        fclose(out);
+    }
+#endif /* MAKECRCH */
+}
+
+#ifdef MAKECRCH
+local void write_table(out, table)
+    FILE *out;
+    const z_crc_t FAR *table;
+{
+    int n;
+
+    for (n = 0; n < 256; n++)
+        fprintf(out, "%s0x%08lxUL%s", n % 5 ? "" : "    ",
+                (unsigned long)(table[n]),
+                n == 255 ? "\n" : (n % 5 == 4 ? ",\n" : ", "));
+}
+#endif /* MAKECRCH */
+
+#else /* !DYNAMIC_CRC_TABLE */
+/* ========================================================================
+ * Tables of CRC-32s of all single-byte values, made by make_crc_table().
+ */
+#include "crc32.h"
+#endif /* DYNAMIC_CRC_TABLE */
+
+/* =========================================================================
+ * This function can be used by asm versions of crc32()
+ */
+const z_crc_t FAR * ZEXPORT get_crc_table()
+{
+#ifdef DYNAMIC_CRC_TABLE
+    if (crc_table_empty)
+        make_crc_table();
+#endif /* DYNAMIC_CRC_TABLE */
+    return (const z_crc_t FAR *)crc_table;
+}
+
+/* ========================================================================= */
+#define DO1 crc = crc_table[0][((int)crc ^ (*buf++)) & 0xff] ^ (crc >> 8)
+#define DO8 DO1; DO1; DO1; DO1; DO1; DO1; DO1; DO1
+
+/* ========================================================================= */
+uLong ZEXPORT crc32_z(crc, buf, len)
+    uLong crc;
+    const unsigned char FAR *buf;
+    z_size_t len;
+{
+    if (buf == Z_NULL) return 0UL;
+
+#ifdef DYNAMIC_CRC_TABLE
+    if (crc_table_empty)
+        make_crc_table();
+#endif /* DYNAMIC_CRC_TABLE */
+
+#ifdef BYFOUR
+    if (sizeof(void *) == sizeof(ptrdiff_t)) {
+        z_crc_t endian;
+
+        endian = 1;
+        if (*((unsigned char *)(&endian)))
+            return (uLong)crc32_little(crc, buf, len);
+        else
+            return (uLong)crc32_big(crc, buf, len);
+    }
+#endif /* BYFOUR */
+    crc = crc ^ 0xffffffffUL;
+    while (len >= 8) {
+        DO8;
+        len -= 8;
+    }
+    if (len) do {
+        DO1;
+    } while (--len);
+    return crc ^ 0xffffffffUL;
+}
+
+/* ========================================================================= */
+uLong ZEXPORT crc32(crc, buf, len)
+    uLong crc;
+    const unsigned char FAR *buf;
+    uInt len;
+{
+    return crc32_z(crc, buf, len);
+}
+
+#ifdef BYFOUR
+
+/*
+   This BYFOUR code accesses the passed unsigned char * buffer with a 32-bit
+   integer pointer type. This violates the strict aliasing rule, where a
+   compiler can assume, for optimization purposes, that two pointers to
+   fundamentally different types won't ever point to the same memory. This can
+   manifest as a problem only if one of the pointers is written to. This code
+   only reads from those pointers. So long as this code remains isolated in
+   this compilation unit, there won't be a problem. For this reason, this code
+   should not be copied and pasted into a compilation unit in which other code
+   writes to the buffer that is passed to these routines.
+ */
+
+/* ========================================================================= */
+#define DOLIT4 c ^= *buf4++; \
+        c = crc_table[3][c & 0xff] ^ crc_table[2][(c >> 8) & 0xff] ^ \
+            crc_table[1][(c >> 16) & 0xff] ^ crc_table[0][c >> 24]
+#define DOLIT32 DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4; DOLIT4
+
+/* ========================================================================= */
+local unsigned long crc32_little(crc, buf, len)
+    unsigned long crc;
+    const unsigned char FAR *buf;
+    z_size_t len;
+{
+    register z_crc_t c;
+    register const z_crc_t FAR *buf4;
+
+    c = (z_crc_t)crc;
+    c = ~c;
+    while (len && ((ptrdiff_t)buf & 3)) {
+        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
+        len--;
+    }
+
+    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
+    while (len >= 32) {
+        DOLIT32;
+        len -= 32;
+    }
+    while (len >= 4) {
+        DOLIT4;
+        len -= 4;
+    }
+    buf = (const unsigned char FAR *)buf4;
+
+    if (len) do {
+        c = crc_table[0][(c ^ *buf++) & 0xff] ^ (c >> 8);
+    } while (--len);
+    c = ~c;
+    return (unsigned long)c;
+}
+
+/* ========================================================================= */
+#define DOBIG4 c ^= *buf4++; \
+        c = crc_table[4][c & 0xff] ^ crc_table[5][(c >> 8) & 0xff] ^ \
+            crc_table[6][(c >> 16) & 0xff] ^ crc_table[7][c >> 24]
+#define DOBIG32 DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4; DOBIG4
+
+/* ========================================================================= */
+local unsigned long crc32_big(crc, buf, len)
+    unsigned long crc;
+    const unsigned char FAR *buf;
+    z_size_t len;
+{
+    register z_crc_t c;
+    register const z_crc_t FAR *buf4;
+
+    c = ZSWAP32((z_crc_t)crc);
+    c = ~c;
+    while (len && ((ptrdiff_t)buf & 3)) {
+        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
+        len--;
+    }
+
+    buf4 = (const z_crc_t FAR *)(const void FAR *)buf;
+    while (len >= 32) {
+        DOBIG32;
+        len -= 32;
+    }
+    while (len >= 4) {
+        DOBIG4;
+        len -= 4;
+    }
+    buf = (const unsigned char FAR *)buf4;
+
+    if (len) do {
+        c = crc_table[4][(c >> 24) ^ *buf++] ^ (c << 8);
+    } while (--len);
+    c = ~c;
+    return (unsigned long)(ZSWAP32(c));
+}
+
+#endif /* BYFOUR */
+
+#define GF2_DIM 32      /* dimension of GF(2) vectors (length of CRC) */
+
+/* ========================================================================= */
+local unsigned long gf2_matrix_times(mat, vec)
+    unsigned long *mat;
+    unsigned long vec;
+{
+    unsigned long sum;
+
+    sum = 0;
+    while (vec) {
+        if (vec & 1)
+            sum ^= *mat;
+        vec >>= 1;
+        mat++;
+    }
+    return sum;
+}
+
+/* ========================================================================= */
+local void gf2_matrix_square(square, mat)
+    unsigned long *square;
+    unsigned long *mat;
+{
+    int n;
+
+    for (n = 0; n < GF2_DIM; n++)
+        square[n] = gf2_matrix_times(mat, mat[n]);
+}
+
+/* ========================================================================= */
+local uLong crc32_combine_(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off64_t len2;
+{
+    int n;
+    unsigned long row;
+    unsigned long even[GF2_DIM];    /* even-power-of-two zeros operator */
+    unsigned long odd[GF2_DIM];     /* odd-power-of-two zeros operator */
+
+    /* degenerate case (also disallow negative lengths) */
+    if (len2 <= 0)
+        return crc1;
+
+    /* put operator for one zero bit in odd */
+    odd[0] = 0xedb88320UL;          /* CRC-32 polynomial */
+    row = 1;
+    for (n = 1; n < GF2_DIM; n++) {
+        odd[n] = row;
+        row <<= 1;
+    }
+
+    /* put operator for two zero bits in even */
+    gf2_matrix_square(even, odd);
+
+    /* put operator for four zero bits in odd */
+    gf2_matrix_square(odd, even);
+
+    /* apply len2 zeros to crc1 (first square will put the operator for one
+       zero byte, eight zero bits, in even) */
+    do {
+        /* apply zeros operator for this bit of len2 */
+        gf2_matrix_square(even, odd);
+        if (len2 & 1)
+            crc1 = gf2_matrix_times(even, crc1);
+        len2 >>= 1;
+
+        /* if no more bits set, then done */
+        if (len2 == 0)
+            break;
+
+        /* another iteration of the loop with odd and even swapped */
+        gf2_matrix_square(odd, even);
+        if (len2 & 1)
+            crc1 = gf2_matrix_times(odd, crc1);
+        len2 >>= 1;
+
+        /* if no more bits set, then done */
+    } while (len2 != 0);
+
+    /* return combined crc */
+    crc1 ^= crc2;
+    return crc1;
+}
+
+/* ========================================================================= */
+uLong ZEXPORT crc32_combine(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off_t len2;
+{
+    return crc32_combine_(crc1, crc2, len2);
+}
+
+uLong ZEXPORT crc32_combine64(crc1, crc2, len2)
+    uLong crc1;
+    uLong crc2;
+    z_off64_t len2;
+{
+    return crc32_combine_(crc1, crc2, len2);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/zlib.h	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,1936 @@
+/*
+ * 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.
+ */
+
+/* zlib.h -- interface of the 'zlib' general purpose compression library
+  version 1.2.11, January 15th, 2017
+
+  Copyright (C) 1995-2017 Jean-loup Gailly and Mark Adler
+
+  This software is provided 'as-is', without any express or implied
+  warranty.  In no event will the authors be held liable for any damages
+  arising from the use of this software.
+
+  Permission is granted to anyone to use this software for any purpose,
+  including commercial applications, and to alter it and redistribute it
+  freely, subject to the following restrictions:
+
+  1. The origin of this software must not be misrepresented; you must not
+     claim that you wrote the original software. If you use this software
+     in a product, an acknowledgment in the product documentation would be
+     appreciated but is not required.
+  2. Altered source versions must be plainly marked as such, and must not be
+     misrepresented as being the original software.
+  3. This notice may not be removed or altered from any source distribution.
+
+  Jean-loup Gailly        Mark Adler
+  jloup@gzip.org          madler@alumni.caltech.edu
+
+
+  The data format used by the zlib library is described by RFCs (Request for
+  Comments) 1950 to 1952 in the files http://tools.ietf.org/html/rfc1950
+  (zlib format), rfc1951 (deflate format) and rfc1952 (gzip format).
+*/
+
+#ifndef ZLIB_H
+#define ZLIB_H
+
+#include "zconf.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define ZLIB_VERSION "1.2.11"
+#define ZLIB_VERNUM 0x12b0
+#define ZLIB_VER_MAJOR 1
+#define ZLIB_VER_MINOR 2
+#define ZLIB_VER_REVISION 11
+#define ZLIB_VER_SUBREVISION 0
+
+/*
+    The 'zlib' compression library provides in-memory compression and
+  decompression functions, including integrity checks of the uncompressed data.
+  This version of the library supports only one compression method (deflation)
+  but other algorithms will be added later and will have the same stream
+  interface.
+
+    Compression can be done in a single step if the buffers are large enough,
+  or can be done by repeated calls of the compression function.  In the latter
+  case, the application must provide more input and/or consume the output
+  (providing more output space) before each call.
+
+    The compressed data format used by default by the in-memory functions is
+  the zlib format, which is a zlib wrapper documented in RFC 1950, wrapped
+  around a deflate stream, which is itself documented in RFC 1951.
+
+    The library also supports reading and writing files in gzip (.gz) format
+  with an interface similar to that of stdio using the functions that start
+  with "gz".  The gzip format is different from the zlib format.  gzip is a
+  gzip wrapper, documented in RFC 1952, wrapped around a deflate stream.
+
+    This library can optionally read and write gzip and raw deflate streams in
+  memory as well.
+
+    The zlib format was designed to be compact and fast for use in memory
+  and on communications channels.  The gzip format was designed for single-
+  file compression on file systems, has a larger header than zlib to maintain
+  directory information, and uses a different, slower check method than zlib.
+
+    The library does not install any signal handler.  The decoder checks
+  the consistency of the compressed data, so the library should never crash
+  even in the case of corrupted input.
+*/
+
+typedef voidpf (*alloc_func) OF((voidpf opaque, uInt items, uInt size));
+typedef void   (*free_func)  OF((voidpf opaque, voidpf address));
+
+struct internal_state;
+
+typedef struct z_stream_s {
+    z_const Bytef *next_in;     /* next input byte */
+    uInt     avail_in;  /* number of bytes available at next_in */
+    uLong    total_in;  /* total number of input bytes read so far */
+
+    Bytef    *next_out; /* next output byte will go here */
+    uInt     avail_out; /* remaining free space at next_out */
+    uLong    total_out; /* total number of bytes output so far */
+
+    z_const char *msg;  /* last error message, NULL if no error */
+    struct internal_state FAR *state; /* not visible by applications */
+
+    alloc_func zalloc;  /* used to allocate the internal state */
+    free_func  zfree;   /* used to free the internal state */
+    voidpf     opaque;  /* private data object passed to zalloc and zfree */
+
+    int     data_type;  /* best guess about the data type: binary or text
+                           for deflate, or the decoding state for inflate */
+    uLong   adler;      /* Adler-32 or CRC-32 value of the uncompressed data */
+    uLong   reserved;   /* reserved for future use */
+} z_stream;
+
+typedef z_stream FAR *z_streamp;
+
+/*
+     gzip header information passed to and from zlib routines.  See RFC 1952
+  for more details on the meanings of these fields.
+*/
+typedef struct gz_header_s {
+    int     text;       /* true if compressed data believed to be text */
+    uLong   time;       /* modification time */
+    int     xflags;     /* extra flags (not used when writing a gzip file) */
+    int     os;         /* operating system */
+    Bytef   *extra;     /* pointer to extra field or Z_NULL if none */
+    uInt    extra_len;  /* extra field length (valid if extra != Z_NULL) */
+    uInt    extra_max;  /* space at extra (only when reading header) */
+    Bytef   *name;      /* pointer to zero-terminated file name or Z_NULL */
+    uInt    name_max;   /* space at name (only when reading header) */
+    Bytef   *comment;   /* pointer to zero-terminated comment or Z_NULL */
+    uInt    comm_max;   /* space at comment (only when reading header) */
+    int     hcrc;       /* true if there was or will be a header crc */
+    int     done;       /* true when done reading gzip header (not used
+                           when writing a gzip file) */
+} gz_header;
+
+typedef gz_header FAR *gz_headerp;
+
+/*
+     The application must update next_in and avail_in when avail_in has dropped
+   to zero.  It must update next_out and avail_out when avail_out has dropped
+   to zero.  The application must initialize zalloc, zfree and opaque before
+   calling the init function.  All other fields are set by the compression
+   library and must not be updated by the application.
+
+     The opaque value provided by the application will be passed as the first
+   parameter for calls of zalloc and zfree.  This can be useful for custom
+   memory management.  The compression library attaches no meaning to the
+   opaque value.
+
+     zalloc must return Z_NULL if there is not enough memory for the object.
+   If zlib is used in a multi-threaded application, zalloc and zfree must be
+   thread safe.  In that case, zlib is thread-safe.  When zalloc and zfree are
+   Z_NULL on entry to the initialization function, they are set to internal
+   routines that use the standard library functions malloc() and free().
+
+     On 16-bit systems, the functions zalloc and zfree must be able to allocate
+   exactly 65536 bytes, but will not be required to allocate more than this if
+   the symbol MAXSEG_64K is defined (see zconf.h).  WARNING: On MSDOS, pointers
+   returned by zalloc for objects of exactly 65536 bytes *must* have their
+   offset normalized to zero.  The default allocation function provided by this
+   library ensures this (see zutil.c).  To reduce memory requirements and avoid
+   any allocation of 64K objects, at the expense of compression ratio, compile
+   the library with -DMAX_WBITS=14 (see zconf.h).
+
+     The fields total_in and total_out can be used for statistics or progress
+   reports.  After compression, total_in holds the total size of the
+   uncompressed data and may be saved for use by the decompressor (particularly
+   if the decompressor wants to decompress everything in a single step).
+*/
+
+                        /* constants */
+
+#define Z_NO_FLUSH      0
+#define Z_PARTIAL_FLUSH 1
+#define Z_SYNC_FLUSH    2
+#define Z_FULL_FLUSH    3
+#define Z_FINISH        4
+#define Z_BLOCK         5
+#define Z_TREES         6
+/* Allowed flush values; see deflate() and inflate() below for details */
+
+#define Z_OK            0
+#define Z_STREAM_END    1
+#define Z_NEED_DICT     2
+#define Z_ERRNO        (-1)
+#define Z_STREAM_ERROR (-2)
+#define Z_DATA_ERROR   (-3)
+#define Z_MEM_ERROR    (-4)
+#define Z_BUF_ERROR    (-5)
+#define Z_VERSION_ERROR (-6)
+/* Return codes for the compression/decompression functions. Negative values
+ * are errors, positive values are used for special but normal events.
+ */
+
+#define Z_NO_COMPRESSION         0
+#define Z_BEST_SPEED             1
+#define Z_BEST_COMPRESSION       9
+#define Z_DEFAULT_COMPRESSION  (-1)
+/* compression levels */
+
+#define Z_FILTERED            1
+#define Z_HUFFMAN_ONLY        2
+#define Z_RLE                 3
+#define Z_FIXED               4
+#define Z_DEFAULT_STRATEGY    0
+/* compression strategy; see deflateInit2() below for details */
+
+#define Z_BINARY   0
+#define Z_TEXT     1
+#define Z_ASCII    Z_TEXT   /* for compatibility with 1.2.2 and earlier */
+#define Z_UNKNOWN  2
+/* Possible values of the data_type field for deflate() */
+
+#define Z_DEFLATED   8
+/* The deflate compression method (the only one supported in this version) */
+
+#define Z_NULL  0  /* for initializing zalloc, zfree, opaque */
+
+#define zlib_version zlibVersion()
+/* for compatibility with versions < 1.0.2 */
+
+
+                        /* basic functions */
+
+ZEXTERN const char * ZEXPORT zlibVersion OF((void));
+/* The application can compare zlibVersion and ZLIB_VERSION for consistency.
+   If the first character differs, the library code actually used is not
+   compatible with the zlib.h header file used by the application.  This check
+   is automatically made by deflateInit and inflateInit.
+ */
+
+/*
+ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
+
+     Initializes the internal stream state for compression.  The fields
+   zalloc, zfree and opaque must be initialized before by the caller.  If
+   zalloc and zfree are set to Z_NULL, deflateInit updates them to use default
+   allocation functions.
+
+     The compression level must be Z_DEFAULT_COMPRESSION, or between 0 and 9:
+   1 gives best speed, 9 gives best compression, 0 gives no compression at all
+   (the input data is simply copied a block at a time).  Z_DEFAULT_COMPRESSION
+   requests a default compromise between speed and compression (currently
+   equivalent to level 6).
+
+     deflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if level is not a valid compression level, or
+   Z_VERSION_ERROR if the zlib library version (zlib_version) is incompatible
+   with the version assumed by the caller (ZLIB_VERSION).  msg is set to null
+   if there is no error message.  deflateInit does not perform any compression:
+   this will be done by deflate().
+*/
+
+
+ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
+/*
+    deflate compresses as much data as possible, and stops when the input
+  buffer becomes empty or the output buffer becomes full.  It may introduce
+  some output latency (reading input without producing any output) except when
+  forced to flush.
+
+    The detailed semantics are as follows.  deflate performs one or both of the
+  following actions:
+
+  - Compress more input starting at next_in and update next_in and avail_in
+    accordingly.  If not all input can be processed (because there is not
+    enough room in the output buffer), next_in and avail_in are updated and
+    processing will resume at this point for the next call of deflate().
+
+  - Generate more output starting at next_out and update next_out and avail_out
+    accordingly.  This action is forced if the parameter flush is non zero.
+    Forcing flush frequently degrades the compression ratio, so this parameter
+    should be set only when necessary.  Some output may be provided even if
+    flush is zero.
+
+    Before the call of deflate(), the application should ensure that at least
+  one of the actions is possible, by providing more input and/or consuming more
+  output, and updating avail_in or avail_out accordingly; avail_out should
+  never be zero before the call.  The application can consume the compressed
+  output when it wants, for example when the output buffer is full (avail_out
+  == 0), or after each call of deflate().  If deflate returns Z_OK and with
+  zero avail_out, it must be called again after making room in the output
+  buffer because there might be more output pending. See deflatePending(),
+  which can be used if desired to determine whether or not there is more ouput
+  in that case.
+
+    Normally the parameter flush is set to Z_NO_FLUSH, which allows deflate to
+  decide how much data to accumulate before producing output, in order to
+  maximize compression.
+
+    If the parameter flush is set to Z_SYNC_FLUSH, all pending output is
+  flushed to the output buffer and the output is aligned on a byte boundary, so
+  that the decompressor can get all input data available so far.  (In
+  particular avail_in is zero after the call if enough output space has been
+  provided before the call.) Flushing may degrade compression for some
+  compression algorithms and so it should be used only when necessary.  This
+  completes the current deflate block and follows it with an empty stored block
+  that is three bits plus filler bits to the next byte, followed by four bytes
+  (00 00 ff ff).
+
+    If flush is set to Z_PARTIAL_FLUSH, all pending output is flushed to the
+  output buffer, but the output is not aligned to a byte boundary.  All of the
+  input data so far will be available to the decompressor, as for Z_SYNC_FLUSH.
+  This completes the current deflate block and follows it with an empty fixed
+  codes block that is 10 bits long.  This assures that enough bytes are output
+  in order for the decompressor to finish the block before the empty fixed
+  codes block.
+
+    If flush is set to Z_BLOCK, a deflate block is completed and emitted, as
+  for Z_SYNC_FLUSH, but the output is not aligned on a byte boundary, and up to
+  seven bits of the current block are held to be written as the next byte after
+  the next deflate block is completed.  In this case, the decompressor may not
+  be provided enough bits at this point in order to complete decompression of
+  the data provided so far to the compressor.  It may need to wait for the next
+  block to be emitted.  This is for advanced applications that need to control
+  the emission of deflate blocks.
+
+    If flush is set to Z_FULL_FLUSH, all output is flushed as with
+  Z_SYNC_FLUSH, and the compression state is reset so that decompression can
+  restart from this point if previous compressed data has been damaged or if
+  random access is desired.  Using Z_FULL_FLUSH too often can seriously degrade
+  compression.
+
+    If deflate returns with avail_out == 0, this function must be called again
+  with the same value of the flush parameter and more output space (updated
+  avail_out), until the flush is complete (deflate returns with non-zero
+  avail_out).  In the case of a Z_FULL_FLUSH or Z_SYNC_FLUSH, make sure that
+  avail_out is greater than six to avoid repeated flush markers due to
+  avail_out == 0 on return.
+
+    If the parameter flush is set to Z_FINISH, pending input is processed,
+  pending output is flushed and deflate returns with Z_STREAM_END if there was
+  enough output space.  If deflate returns with Z_OK or Z_BUF_ERROR, this
+  function must be called again with Z_FINISH and more output space (updated
+  avail_out) but no more input data, until it returns with Z_STREAM_END or an
+  error.  After deflate has returned Z_STREAM_END, the only possible operations
+  on the stream are deflateReset or deflateEnd.
+
+    Z_FINISH can be used in the first deflate call after deflateInit if all the
+  compression is to be done in a single step.  In order to complete in one
+  call, avail_out must be at least the value returned by deflateBound (see
+  below).  Then deflate is guaranteed to return Z_STREAM_END.  If not enough
+  output space is provided, deflate will not return Z_STREAM_END, and it must
+  be called again as described above.
+
+    deflate() sets strm->adler to the Adler-32 checksum of all input read
+  so far (that is, total_in bytes).  If a gzip stream is being generated, then
+  strm->adler will be the CRC-32 checksum of the input read so far.  (See
+  deflateInit2 below.)
+
+    deflate() may update strm->data_type if it can make a good guess about
+  the input data type (Z_BINARY or Z_TEXT).  If in doubt, the data is
+  considered binary.  This field is only for information purposes and does not
+  affect the compression algorithm in any manner.
+
+    deflate() returns Z_OK if some progress has been made (more input
+  processed or more output produced), Z_STREAM_END if all input has been
+  consumed and all output has been produced (only when flush is set to
+  Z_FINISH), Z_STREAM_ERROR if the stream state was inconsistent (for example
+  if next_in or next_out was Z_NULL or the state was inadvertently written over
+  by the application), or Z_BUF_ERROR if no progress is possible (for example
+  avail_in or avail_out was zero).  Note that Z_BUF_ERROR is not fatal, and
+  deflate() can be called again with more input and more output space to
+  continue compressing.
+*/
+
+
+ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
+/*
+     All dynamically allocated data structures for this stream are freed.
+   This function discards any unprocessed input and does not flush any pending
+   output.
+
+     deflateEnd returns Z_OK if success, Z_STREAM_ERROR if the
+   stream state was inconsistent, Z_DATA_ERROR if the stream was freed
+   prematurely (some input or output was discarded).  In the error case, msg
+   may be set but then points to a static string (which must not be
+   deallocated).
+*/
+
+
+/*
+ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
+
+     Initializes the internal stream state for decompression.  The fields
+   next_in, avail_in, zalloc, zfree and opaque must be initialized before by
+   the caller.  In the current version of inflate, the provided input is not
+   read or consumed.  The allocation of a sliding window will be deferred to
+   the first call of inflate (if the decompression does not complete on the
+   first call).  If zalloc and zfree are set to Z_NULL, inflateInit updates
+   them to use default allocation functions.
+
+     inflateInit returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+   invalid, such as a null pointer to the structure.  msg is set to null if
+   there is no error message.  inflateInit does not perform any decompression.
+   Actual decompression will be done by inflate().  So next_in, and avail_in,
+   next_out, and avail_out are unused and unchanged.  The current
+   implementation of inflateInit() does not process any header information --
+   that is deferred until inflate() is called.
+*/
+
+
+ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
+/*
+    inflate decompresses as much data as possible, and stops when the input
+  buffer becomes empty or the output buffer becomes full.  It may introduce
+  some output latency (reading input without producing any output) except when
+  forced to flush.
+
+  The detailed semantics are as follows.  inflate performs one or both of the
+  following actions:
+
+  - Decompress more input starting at next_in and update next_in and avail_in
+    accordingly.  If not all input can be processed (because there is not
+    enough room in the output buffer), then next_in and avail_in are updated
+    accordingly, and processing will resume at this point for the next call of
+    inflate().
+
+  - Generate more output starting at next_out and update next_out and avail_out
+    accordingly.  inflate() provides as much output as possible, until there is
+    no more input data or no more space in the output buffer (see below about
+    the flush parameter).
+
+    Before the call of inflate(), the application should ensure that at least
+  one of the actions is possible, by providing more input and/or consuming more
+  output, and updating the next_* and avail_* values accordingly.  If the
+  caller of inflate() does not provide both available input and available
+  output space, it is possible that there will be no progress made.  The
+  application can consume the uncompressed output when it wants, for example
+  when the output buffer is full (avail_out == 0), or after each call of
+  inflate().  If inflate returns Z_OK and with zero avail_out, it must be
+  called again after making room in the output buffer because there might be
+  more output pending.
+
+    The flush parameter of inflate() can be Z_NO_FLUSH, Z_SYNC_FLUSH, Z_FINISH,
+  Z_BLOCK, or Z_TREES.  Z_SYNC_FLUSH requests that inflate() flush as much
+  output as possible to the output buffer.  Z_BLOCK requests that inflate()
+  stop if and when it gets to the next deflate block boundary.  When decoding
+  the zlib or gzip format, this will cause inflate() to return immediately
+  after the header and before the first block.  When doing a raw inflate,
+  inflate() will go ahead and process the first block, and will return when it
+  gets to the end of that block, or when it runs out of data.
+
+    The Z_BLOCK option assists in appending to or combining deflate streams.
+  To assist in this, on return inflate() always sets strm->data_type to the
+  number of unused bits in the last byte taken from strm->next_in, plus 64 if
+  inflate() is currently decoding the last block in the deflate stream, plus
+  128 if inflate() returned immediately after decoding an end-of-block code or
+  decoding the complete header up to just before the first byte of the deflate
+  stream.  The end-of-block will not be indicated until all of the uncompressed
+  data from that block has been written to strm->next_out.  The number of
+  unused bits may in general be greater than seven, except when bit 7 of
+  data_type is set, in which case the number of unused bits will be less than
+  eight.  data_type is set as noted here every time inflate() returns for all
+  flush options, and so can be used to determine the amount of currently
+  consumed input in bits.
+
+    The Z_TREES option behaves as Z_BLOCK does, but it also returns when the
+  end of each deflate block header is reached, before any actual data in that
+  block is decoded.  This allows the caller to determine the length of the
+  deflate block header for later use in random access within a deflate block.
+  256 is added to the value of strm->data_type when inflate() returns
+  immediately after reaching the end of the deflate block header.
+
+    inflate() should normally be called until it returns Z_STREAM_END or an
+  error.  However if all decompression is to be performed in a single step (a
+  single call of inflate), the parameter flush should be set to Z_FINISH.  In
+  this case all pending input is processed and all pending output is flushed;
+  avail_out must be large enough to hold all of the uncompressed data for the
+  operation to complete.  (The size of the uncompressed data may have been
+  saved by the compressor for this purpose.)  The use of Z_FINISH is not
+  required to perform an inflation in one step.  However it may be used to
+  inform inflate that a faster approach can be used for the single inflate()
+  call.  Z_FINISH also informs inflate to not maintain a sliding window if the
+  stream completes, which reduces inflate's memory footprint.  If the stream
+  does not complete, either because not all of the stream is provided or not
+  enough output space is provided, then a sliding window will be allocated and
+  inflate() can be called again to continue the operation as if Z_NO_FLUSH had
+  been used.
+
+     In this implementation, inflate() always flushes as much output as
+  possible to the output buffer, and always uses the faster approach on the
+  first call.  So the effects of the flush parameter in this implementation are
+  on the return value of inflate() as noted below, when inflate() returns early
+  when Z_BLOCK or Z_TREES is used, and when inflate() avoids the allocation of
+  memory for a sliding window when Z_FINISH is used.
+
+     If a preset dictionary is needed after this call (see inflateSetDictionary
+  below), inflate sets strm->adler to the Adler-32 checksum of the dictionary
+  chosen by the compressor and returns Z_NEED_DICT; otherwise it sets
+  strm->adler to the Adler-32 checksum of all output produced so far (that is,
+  total_out bytes) and returns Z_OK, Z_STREAM_END or an error code as described
+  below.  At the end of the stream, inflate() checks that its computed Adler-32
+  checksum is equal to that saved by the compressor and returns Z_STREAM_END
+  only if the checksum is correct.
+
+    inflate() can decompress and check either zlib-wrapped or gzip-wrapped
+  deflate data.  The header type is detected automatically, if requested when
+  initializing with inflateInit2().  Any information contained in the gzip
+  header is not retained unless inflateGetHeader() is used.  When processing
+  gzip-wrapped deflate data, strm->adler32 is set to the CRC-32 of the output
+  produced so far.  The CRC-32 is checked against the gzip trailer, as is the
+  uncompressed length, modulo 2^32.
+
+    inflate() returns Z_OK if some progress has been made (more input processed
+  or more output produced), Z_STREAM_END if the end of the compressed data has
+  been reached and all uncompressed output has been produced, Z_NEED_DICT if a
+  preset dictionary is needed at this point, Z_DATA_ERROR if the input data was
+  corrupted (input stream not conforming to the zlib format or incorrect check
+  value, in which case strm->msg points to a string with a more specific
+  error), Z_STREAM_ERROR if the stream structure was inconsistent (for example
+  next_in or next_out was Z_NULL, or the state was inadvertently written over
+  by the application), Z_MEM_ERROR if there was not enough memory, Z_BUF_ERROR
+  if no progress was possible or if there was not enough room in the output
+  buffer when Z_FINISH is used.  Note that Z_BUF_ERROR is not fatal, and
+  inflate() can be called again with more input and more output space to
+  continue decompressing.  If Z_DATA_ERROR is returned, the application may
+  then call inflateSync() to look for a good compression block if a partial
+  recovery of the data is to be attempted.
+*/
+
+
+ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
+/*
+     All dynamically allocated data structures for this stream are freed.
+   This function discards any unprocessed input and does not flush any pending
+   output.
+
+     inflateEnd returns Z_OK if success, or Z_STREAM_ERROR if the stream state
+   was inconsistent.
+*/
+
+
+                        /* Advanced functions */
+
+/*
+    The following functions are needed only in some special applications.
+*/
+
+/*
+ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
+                                     int  level,
+                                     int  method,
+                                     int  windowBits,
+                                     int  memLevel,
+                                     int  strategy));
+
+     This is another version of deflateInit with more compression options.  The
+   fields next_in, zalloc, zfree and opaque must be initialized before by the
+   caller.
+
+     The method parameter is the compression method.  It must be Z_DEFLATED in
+   this version of the library.
+
+     The windowBits parameter is the base two logarithm of the window size
+   (the size of the history buffer).  It should be in the range 8..15 for this
+   version of the library.  Larger values of this parameter result in better
+   compression at the expense of memory usage.  The default value is 15 if
+   deflateInit is used instead.
+
+     For the current implementation of deflate(), a windowBits value of 8 (a
+   window size of 256 bytes) is not supported.  As a result, a request for 8
+   will result in 9 (a 512-byte window).  In that case, providing 8 to
+   inflateInit2() will result in an error when the zlib header with 9 is
+   checked against the initialization of inflate().  The remedy is to not use 8
+   with deflateInit2() with this initialization, or at least in that case use 9
+   with inflateInit2().
+
+     windowBits can also be -8..-15 for raw deflate.  In this case, -windowBits
+   determines the window size.  deflate() will then generate raw deflate data
+   with no zlib header or trailer, and will not compute a check value.
+
+     windowBits can also be greater than 15 for optional gzip encoding.  Add
+   16 to windowBits to write a simple gzip header and trailer around the
+   compressed data instead of a zlib wrapper.  The gzip header will have no
+   file name, no extra data, no comment, no modification time (set to zero), no
+   header crc, and the operating system will be set to the appropriate value,
+   if the operating system was determined at compile time.  If a gzip stream is
+   being written, strm->adler is a CRC-32 instead of an Adler-32.
+
+     For raw deflate or gzip encoding, a request for a 256-byte window is
+   rejected as invalid, since only the zlib header provides a means of
+   transmitting the window size to the decompressor.
+
+     The memLevel parameter specifies how much memory should be allocated
+   for the internal compression state.  memLevel=1 uses minimum memory but is
+   slow and reduces compression ratio; memLevel=9 uses maximum memory for
+   optimal speed.  The default value is 8.  See zconf.h for total memory usage
+   as a function of windowBits and memLevel.
+
+     The strategy parameter is used to tune the compression algorithm.  Use the
+   value Z_DEFAULT_STRATEGY for normal data, Z_FILTERED for data produced by a
+   filter (or predictor), Z_HUFFMAN_ONLY to force Huffman encoding only (no
+   string match), or Z_RLE to limit match distances to one (run-length
+   encoding).  Filtered data consists mostly of small values with a somewhat
+   random distribution.  In this case, the compression algorithm is tuned to
+   compress them better.  The effect of Z_FILTERED is to force more Huffman
+   coding and less string matching; it is somewhat intermediate between
+   Z_DEFAULT_STRATEGY and Z_HUFFMAN_ONLY.  Z_RLE is designed to be almost as
+   fast as Z_HUFFMAN_ONLY, but give better compression for PNG image data.  The
+   strategy parameter only affects the compression ratio but not the
+   correctness of the compressed output even if it is not set appropriately.
+   Z_FIXED prevents the use of dynamic Huffman codes, allowing for a simpler
+   decoder for special applications.
+
+     deflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_STREAM_ERROR if any parameter is invalid (such as an invalid
+   method), or Z_VERSION_ERROR if the zlib library version (zlib_version) is
+   incompatible with the version assumed by the caller (ZLIB_VERSION).  msg is
+   set to null if there is no error message.  deflateInit2 does not perform any
+   compression: this will be done by deflate().
+*/
+
+ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
+                                             const Bytef *dictionary,
+                                             uInt  dictLength));
+/*
+     Initializes the compression dictionary from the given byte sequence
+   without producing any compressed output.  When using the zlib format, this
+   function must be called immediately after deflateInit, deflateInit2 or
+   deflateReset, and before any call of deflate.  When doing raw deflate, this
+   function must be called either before any call of deflate, or immediately
+   after the completion of a deflate block, i.e. after all input has been
+   consumed and all output has been delivered when using any of the flush
+   options Z_BLOCK, Z_PARTIAL_FLUSH, Z_SYNC_FLUSH, or Z_FULL_FLUSH.  The
+   compressor and decompressor must use exactly the same dictionary (see
+   inflateSetDictionary).
+
+     The dictionary should consist of strings (byte sequences) that are likely
+   to be encountered later in the data to be compressed, with the most commonly
+   used strings preferably put towards the end of the dictionary.  Using a
+   dictionary is most useful when the data to be compressed is short and can be
+   predicted with good accuracy; the data can then be compressed better than
+   with the default empty dictionary.
+
+     Depending on the size of the compression data structures selected by
+   deflateInit or deflateInit2, a part of the dictionary may in effect be
+   discarded, for example if the dictionary is larger than the window size
+   provided in deflateInit or deflateInit2.  Thus the strings most likely to be
+   useful should be put at the end of the dictionary, not at the front.  In
+   addition, the current implementation of deflate will use at most the window
+   size minus 262 bytes of the provided dictionary.
+
+     Upon return of this function, strm->adler is set to the Adler-32 value
+   of the dictionary; the decompressor may later use this value to determine
+   which dictionary has been used by the compressor.  (The Adler-32 value
+   applies to the whole dictionary even if only a subset of the dictionary is
+   actually used by the compressor.) If a raw deflate was requested, then the
+   Adler-32 value is not computed and strm->adler is not set.
+
+     deflateSetDictionary returns Z_OK if success, or Z_STREAM_ERROR if a
+   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
+   inconsistent (for example if deflate has already been called for this stream
+   or if not at a block boundary for raw deflate).  deflateSetDictionary does
+   not perform any compression: this will be done by deflate().
+*/
+
+ZEXTERN int ZEXPORT deflateGetDictionary OF((z_streamp strm,
+                                             Bytef *dictionary,
+                                             uInt  *dictLength));
+/*
+     Returns the sliding dictionary being maintained by deflate.  dictLength is
+   set to the number of bytes in the dictionary, and that many bytes are copied
+   to dictionary.  dictionary must have enough space, where 32768 bytes is
+   always enough.  If deflateGetDictionary() is called with dictionary equal to
+   Z_NULL, then only the dictionary length is returned, and nothing is copied.
+   Similary, if dictLength is Z_NULL, then it is not set.
+
+     deflateGetDictionary() may return a length less than the window size, even
+   when more than the window size in input has been provided. It may return up
+   to 258 bytes less in that case, due to how zlib's implementation of deflate
+   manages the sliding window and lookahead for matches, where matches can be
+   up to 258 bytes long. If the application needs the last window-size bytes of
+   input, then that would need to be saved by the application outside of zlib.
+
+     deflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
+   stream state is inconsistent.
+*/
+
+ZEXTERN int ZEXPORT deflateCopy OF((z_streamp dest,
+                                    z_streamp source));
+/*
+     Sets the destination stream as a complete copy of the source stream.
+
+     This function can be useful when several compression strategies will be
+   tried, for example when there are several ways of pre-processing the input
+   data with a filter.  The streams that will be discarded should then be freed
+   by calling deflateEnd.  Note that deflateCopy duplicates the internal
+   compression state which can be quite large, so this strategy is slow and can
+   consume lots of memory.
+
+     deflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
+   destination.
+*/
+
+ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
+/*
+     This function is equivalent to deflateEnd followed by deflateInit, but
+   does not free and reallocate the internal compression state.  The stream
+   will leave the compression level and any other attributes that may have been
+   set unchanged.
+
+     deflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL).
+*/
+
+ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
+                                      int level,
+                                      int strategy));
+/*
+     Dynamically update the compression level and compression strategy.  The
+   interpretation of level and strategy is as in deflateInit2().  This can be
+   used to switch between compression and straight copy of the input data, or
+   to switch to a different kind of input data requiring a different strategy.
+   If the compression approach (which is a function of the level) or the
+   strategy is changed, and if any input has been consumed in a previous
+   deflate() call, then the input available so far is compressed with the old
+   level and strategy using deflate(strm, Z_BLOCK).  There are three approaches
+   for the compression levels 0, 1..3, and 4..9 respectively.  The new level
+   and strategy will take effect at the next call of deflate().
+
+     If a deflate(strm, Z_BLOCK) is performed by deflateParams(), and it does
+   not have enough output space to complete, then the parameter change will not
+   take effect.  In this case, deflateParams() can be called again with the
+   same parameters and more output space to try again.
+
+     In order to assure a change in the parameters on the first try, the
+   deflate stream should be flushed using deflate() with Z_BLOCK or other flush
+   request until strm.avail_out is not zero, before calling deflateParams().
+   Then no more input data should be provided before the deflateParams() call.
+   If this is done, the old level and strategy will be applied to the data
+   compressed before deflateParams(), and the new level and strategy will be
+   applied to the the data compressed after deflateParams().
+
+     deflateParams returns Z_OK on success, Z_STREAM_ERROR if the source stream
+   state was inconsistent or if a parameter was invalid, or Z_BUF_ERROR if
+   there was not enough output space to complete the compression of the
+   available input data before a change in the strategy or approach.  Note that
+   in the case of a Z_BUF_ERROR, the parameters are not changed.  A return
+   value of Z_BUF_ERROR is not fatal, in which case deflateParams() can be
+   retried with more output space.
+*/
+
+ZEXTERN int ZEXPORT deflateTune OF((z_streamp strm,
+                                    int good_length,
+                                    int max_lazy,
+                                    int nice_length,
+                                    int max_chain));
+/*
+     Fine tune deflate's internal compression parameters.  This should only be
+   used by someone who understands the algorithm used by zlib's deflate for
+   searching for the best matching string, and even then only by the most
+   fanatic optimizer trying to squeeze out the last compressed bit for their
+   specific input data.  Read the deflate.c source code for the meaning of the
+   max_lazy, good_length, nice_length, and max_chain parameters.
+
+     deflateTune() can be called after deflateInit() or deflateInit2(), and
+   returns Z_OK on success, or Z_STREAM_ERROR for an invalid deflate stream.
+ */
+
+ZEXTERN uLong ZEXPORT deflateBound OF((z_streamp strm,
+                                       uLong sourceLen));
+/*
+     deflateBound() returns an upper bound on the compressed size after
+   deflation of sourceLen bytes.  It must be called after deflateInit() or
+   deflateInit2(), and after deflateSetHeader(), if used.  This would be used
+   to allocate an output buffer for deflation in a single pass, and so would be
+   called before deflate().  If that first deflate() call is provided the
+   sourceLen input bytes, an output buffer allocated to the size returned by
+   deflateBound(), and the flush value Z_FINISH, then deflate() is guaranteed
+   to return Z_STREAM_END.  Note that it is possible for the compressed size to
+   be larger than the value returned by deflateBound() if flush options other
+   than Z_FINISH or Z_NO_FLUSH are used.
+*/
+
+ZEXTERN int ZEXPORT deflatePending OF((z_streamp strm,
+                                       unsigned *pending,
+                                       int *bits));
+/*
+     deflatePending() returns the number of bytes and bits of output that have
+   been generated, but not yet provided in the available output.  The bytes not
+   provided would be due to the available output space having being consumed.
+   The number of bits of output not provided are between 0 and 7, where they
+   await more bits to join them in order to fill out a full byte.  If pending
+   or bits are Z_NULL, then those values are not set.
+
+     deflatePending returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+ */
+
+ZEXTERN int ZEXPORT deflatePrime OF((z_streamp strm,
+                                     int bits,
+                                     int value));
+/*
+     deflatePrime() inserts bits in the deflate output stream.  The intent
+   is that this function is used to start off the deflate output with the bits
+   leftover from a previous deflate stream when appending to it.  As such, this
+   function can only be used for raw deflate, and must be used before the first
+   deflate() call after a deflateInit2() or deflateReset().  bits must be less
+   than or equal to 16, and that many of the least significant bits of value
+   will be inserted in the output.
+
+     deflatePrime returns Z_OK if success, Z_BUF_ERROR if there was not enough
+   room in the internal buffer to insert the bits, or Z_STREAM_ERROR if the
+   source stream state was inconsistent.
+*/
+
+ZEXTERN int ZEXPORT deflateSetHeader OF((z_streamp strm,
+                                         gz_headerp head));
+/*
+     deflateSetHeader() provides gzip header information for when a gzip
+   stream is requested by deflateInit2().  deflateSetHeader() may be called
+   after deflateInit2() or deflateReset() and before the first call of
+   deflate().  The text, time, os, extra field, name, and comment information
+   in the provided gz_header structure are written to the gzip header (xflag is
+   ignored -- the extra flags are set according to the compression level).  The
+   caller must assure that, if not Z_NULL, name and comment are terminated with
+   a zero byte, and that if extra is not Z_NULL, that extra_len bytes are
+   available there.  If hcrc is true, a gzip header crc is included.  Note that
+   the current versions of the command-line version of gzip (up through version
+   1.3.x) do not support header crc's, and will report that it is a "multi-part
+   gzip file" and give up.
+
+     If deflateSetHeader is not used, the default gzip header has text false,
+   the time set to zero, and os set to 255, with no extra, name, or comment
+   fields.  The gzip header is returned to the default state by deflateReset().
+
+     deflateSetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+*/
+
+/*
+ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
+                                     int  windowBits));
+
+     This is another version of inflateInit with an extra parameter.  The
+   fields next_in, avail_in, zalloc, zfree and opaque must be initialized
+   before by the caller.
+
+     The windowBits parameter is the base two logarithm of the maximum window
+   size (the size of the history buffer).  It should be in the range 8..15 for
+   this version of the library.  The default value is 15 if inflateInit is used
+   instead.  windowBits must be greater than or equal to the windowBits value
+   provided to deflateInit2() while compressing, or it must be equal to 15 if
+   deflateInit2() was not used.  If a compressed stream with a larger window
+   size is given as input, inflate() will return with the error code
+   Z_DATA_ERROR instead of trying to allocate a larger window.
+
+     windowBits can also be zero to request that inflate use the window size in
+   the zlib header of the compressed stream.
+
+     windowBits can also be -8..-15 for raw inflate.  In this case, -windowBits
+   determines the window size.  inflate() will then process raw deflate data,
+   not looking for a zlib or gzip header, not generating a check value, and not
+   looking for any check values for comparison at the end of the stream.  This
+   is for use with other formats that use the deflate compressed data format
+   such as zip.  Those formats provide their own check values.  If a custom
+   format is developed using the raw deflate format for compressed data, it is
+   recommended that a check value such as an Adler-32 or a CRC-32 be applied to
+   the uncompressed data as is done in the zlib, gzip, and zip formats.  For
+   most applications, the zlib format should be used as is.  Note that comments
+   above on the use in deflateInit2() applies to the magnitude of windowBits.
+
+     windowBits can also be greater than 15 for optional gzip decoding.  Add
+   32 to windowBits to enable zlib and gzip decoding with automatic header
+   detection, or add 16 to decode only the gzip format (the zlib format will
+   return a Z_DATA_ERROR).  If a gzip stream is being decoded, strm->adler is a
+   CRC-32 instead of an Adler-32.  Unlike the gunzip utility and gzread() (see
+   below), inflate() will not automatically decode concatenated gzip streams.
+   inflate() will return Z_STREAM_END at the end of the gzip stream.  The state
+   would need to be reset to continue decoding a subsequent gzip stream.
+
+     inflateInit2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_VERSION_ERROR if the zlib library version is incompatible with the
+   version assumed by the caller, or Z_STREAM_ERROR if the parameters are
+   invalid, such as a null pointer to the structure.  msg is set to null if
+   there is no error message.  inflateInit2 does not perform any decompression
+   apart from possibly reading the zlib header if present: actual decompression
+   will be done by inflate().  (So next_in and avail_in may be modified, but
+   next_out and avail_out are unused and unchanged.) The current implementation
+   of inflateInit2() does not process any header information -- that is
+   deferred until inflate() is called.
+*/
+
+ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
+                                             const Bytef *dictionary,
+                                             uInt  dictLength));
+/*
+     Initializes the decompression dictionary from the given uncompressed byte
+   sequence.  This function must be called immediately after a call of inflate,
+   if that call returned Z_NEED_DICT.  The dictionary chosen by the compressor
+   can be determined from the Adler-32 value returned by that call of inflate.
+   The compressor and decompressor must use exactly the same dictionary (see
+   deflateSetDictionary).  For raw inflate, this function can be called at any
+   time to set the dictionary.  If the provided dictionary is smaller than the
+   window and there is already data in the window, then the provided dictionary
+   will amend what's there.  The application must insure that the dictionary
+   that was used for compression is provided.
+
+     inflateSetDictionary returns Z_OK if success, Z_STREAM_ERROR if a
+   parameter is invalid (e.g.  dictionary being Z_NULL) or the stream state is
+   inconsistent, Z_DATA_ERROR if the given dictionary doesn't match the
+   expected one (incorrect Adler-32 value).  inflateSetDictionary does not
+   perform any decompression: this will be done by subsequent calls of
+   inflate().
+*/
+
+ZEXTERN int ZEXPORT inflateGetDictionary OF((z_streamp strm,
+                                             Bytef *dictionary,
+                                             uInt  *dictLength));
+/*
+     Returns the sliding dictionary being maintained by inflate.  dictLength is
+   set to the number of bytes in the dictionary, and that many bytes are copied
+   to dictionary.  dictionary must have enough space, where 32768 bytes is
+   always enough.  If inflateGetDictionary() is called with dictionary equal to
+   Z_NULL, then only the dictionary length is returned, and nothing is copied.
+   Similary, if dictLength is Z_NULL, then it is not set.
+
+     inflateGetDictionary returns Z_OK on success, or Z_STREAM_ERROR if the
+   stream state is inconsistent.
+*/
+
+ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
+/*
+     Skips invalid compressed data until a possible full flush point (see above
+   for the description of deflate with Z_FULL_FLUSH) can be found, or until all
+   available input is skipped.  No output is provided.
+
+     inflateSync searches for a 00 00 FF FF pattern in the compressed data.
+   All full flush points have this pattern, but not all occurrences of this
+   pattern are full flush points.
+
+     inflateSync returns Z_OK if a possible full flush point has been found,
+   Z_BUF_ERROR if no more input was provided, Z_DATA_ERROR if no flush point
+   has been found, or Z_STREAM_ERROR if the stream structure was inconsistent.
+   In the success case, the application may save the current current value of
+   total_in which indicates where valid compressed data was found.  In the
+   error case, the application may repeatedly call inflateSync, providing more
+   input each time, until success or end of the input data.
+*/
+
+ZEXTERN int ZEXPORT inflateCopy OF((z_streamp dest,
+                                    z_streamp source));
+/*
+     Sets the destination stream as a complete copy of the source stream.
+
+     This function can be useful when randomly accessing a large stream.  The
+   first pass through the stream can periodically record the inflate state,
+   allowing restarting inflate at those points when randomly accessing the
+   stream.
+
+     inflateCopy returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_STREAM_ERROR if the source stream state was inconsistent
+   (such as zalloc being Z_NULL).  msg is left unchanged in both source and
+   destination.
+*/
+
+ZEXTERN int ZEXPORT inflateReset OF((z_streamp strm));
+/*
+     This function is equivalent to inflateEnd followed by inflateInit,
+   but does not free and reallocate the internal decompression state.  The
+   stream will keep attributes that may have been set by inflateInit2.
+
+     inflateReset returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL).
+*/
+
+ZEXTERN int ZEXPORT inflateReset2 OF((z_streamp strm,
+                                      int windowBits));
+/*
+     This function is the same as inflateReset, but it also permits changing
+   the wrap and window size requests.  The windowBits parameter is interpreted
+   the same as it is for inflateInit2.  If the window size is changed, then the
+   memory allocated for the window is freed, and the window will be reallocated
+   by inflate() if needed.
+
+     inflateReset2 returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent (such as zalloc or state being Z_NULL), or if
+   the windowBits parameter is invalid.
+*/
+
+ZEXTERN int ZEXPORT inflatePrime OF((z_streamp strm,
+                                     int bits,
+                                     int value));
+/*
+     This function inserts bits in the inflate input stream.  The intent is
+   that this function is used to start inflating at a bit position in the
+   middle of a byte.  The provided bits will be used before any bytes are used
+   from next_in.  This function should only be used with raw inflate, and
+   should be used before the first inflate() call after inflateInit2() or
+   inflateReset().  bits must be less than or equal to 16, and that many of the
+   least significant bits of value will be inserted in the input.
+
+     If bits is negative, then the input stream bit buffer is emptied.  Then
+   inflatePrime() can be called again to put bits in the buffer.  This is used
+   to clear out bits leftover after feeding inflate a block description prior
+   to feeding inflate codes.
+
+     inflatePrime returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+*/
+
+ZEXTERN long ZEXPORT inflateMark OF((z_streamp strm));
+/*
+     This function returns two values, one in the lower 16 bits of the return
+   value, and the other in the remaining upper bits, obtained by shifting the
+   return value down 16 bits.  If the upper value is -1 and the lower value is
+   zero, then inflate() is currently decoding information outside of a block.
+   If the upper value is -1 and the lower value is non-zero, then inflate is in
+   the middle of a stored block, with the lower value equaling the number of
+   bytes from the input remaining to copy.  If the upper value is not -1, then
+   it is the number of bits back from the current bit position in the input of
+   the code (literal or length/distance pair) currently being processed.  In
+   that case the lower value is the number of bytes already emitted for that
+   code.
+
+     A code is being processed if inflate is waiting for more input to complete
+   decoding of the code, or if it has completed decoding but is waiting for
+   more output space to write the literal or match data.
+
+     inflateMark() is used to mark locations in the input data for random
+   access, which may be at bit positions, and to note those cases where the
+   output of a code may span boundaries of random access blocks.  The current
+   location in the input stream can be determined from avail_in and data_type
+   as noted in the description for the Z_BLOCK flush parameter for inflate.
+
+     inflateMark returns the value noted above, or -65536 if the provided
+   source stream state was inconsistent.
+*/
+
+ZEXTERN int ZEXPORT inflateGetHeader OF((z_streamp strm,
+                                         gz_headerp head));
+/*
+     inflateGetHeader() requests that gzip header information be stored in the
+   provided gz_header structure.  inflateGetHeader() may be called after
+   inflateInit2() or inflateReset(), and before the first call of inflate().
+   As inflate() processes the gzip stream, head->done is zero until the header
+   is completed, at which time head->done is set to one.  If a zlib stream is
+   being decoded, then head->done is set to -1 to indicate that there will be
+   no gzip header information forthcoming.  Note that Z_BLOCK or Z_TREES can be
+   used to force inflate() to return immediately after header processing is
+   complete and before any actual data is decompressed.
+
+     The text, time, xflags, and os fields are filled in with the gzip header
+   contents.  hcrc is set to true if there is a header CRC.  (The header CRC
+   was valid if done is set to one.) If extra is not Z_NULL, then extra_max
+   contains the maximum number of bytes to write to extra.  Once done is true,
+   extra_len contains the actual extra field length, and extra contains the
+   extra field, or that field truncated if extra_max is less than extra_len.
+   If name is not Z_NULL, then up to name_max characters are written there,
+   terminated with a zero unless the length is greater than name_max.  If
+   comment is not Z_NULL, then up to comm_max characters are written there,
+   terminated with a zero unless the length is greater than comm_max.  When any
+   of extra, name, or comment are not Z_NULL and the respective field is not
+   present in the header, then that field is set to Z_NULL to signal its
+   absence.  This allows the use of deflateSetHeader() with the returned
+   structure to duplicate the header.  However if those fields are set to
+   allocated memory, then the application will need to save those pointers
+   elsewhere so that they can be eventually freed.
+
+     If inflateGetHeader is not used, then the header information is simply
+   discarded.  The header is always checked for validity, including the header
+   CRC if present.  inflateReset() will reset the process to discard the header
+   information.  The application would need to call inflateGetHeader() again to
+   retrieve the header from the next gzip stream.
+
+     inflateGetHeader returns Z_OK if success, or Z_STREAM_ERROR if the source
+   stream state was inconsistent.
+*/
+
+/*
+ZEXTERN int ZEXPORT inflateBackInit OF((z_streamp strm, int windowBits,
+                                        unsigned char FAR *window));
+
+     Initialize the internal stream state for decompression using inflateBack()
+   calls.  The fields zalloc, zfree and opaque in strm must be initialized
+   before the call.  If zalloc and zfree are Z_NULL, then the default library-
+   derived memory allocation routines are used.  windowBits is the base two
+   logarithm of the window size, in the range 8..15.  window is a caller
+   supplied buffer of that size.  Except for special applications where it is
+   assured that deflate was used with small window sizes, windowBits must be 15
+   and a 32K byte window must be supplied to be able to decompress general
+   deflate streams.
+
+     See inflateBack() for the usage of these routines.
+
+     inflateBackInit will return Z_OK on success, Z_STREAM_ERROR if any of
+   the parameters are invalid, Z_MEM_ERROR if the internal state could not be
+   allocated, or Z_VERSION_ERROR if the version of the library does not match
+   the version of the header file.
+*/
+
+typedef unsigned (*in_func) OF((void FAR *,
+                                z_const unsigned char FAR * FAR *));
+typedef int (*out_func) OF((void FAR *, unsigned char FAR *, unsigned));
+
+ZEXTERN int ZEXPORT inflateBack OF((z_streamp strm,
+                                    in_func in, void FAR *in_desc,
+                                    out_func out, void FAR *out_desc));
+/*
+     inflateBack() does a raw inflate with a single call using a call-back
+   interface for input and output.  This is potentially more efficient than
+   inflate() for file i/o applications, in that it avoids copying between the
+   output and the sliding window by simply making the window itself the output
+   buffer.  inflate() can be faster on modern CPUs when used with large
+   buffers.  inflateBack() trusts the application to not change the output
+   buffer passed by the output function, at least until inflateBack() returns.
+
+     inflateBackInit() must be called first to allocate the internal state
+   and to initialize the state with the user-provided window buffer.
+   inflateBack() may then be used multiple times to inflate a complete, raw
+   deflate stream with each call.  inflateBackEnd() is then called to free the
+   allocated state.
+
+     A raw deflate stream is one with no zlib or gzip header or trailer.
+   This routine would normally be used in a utility that reads zip or gzip
+   files and writes out uncompressed files.  The utility would decode the
+   header and process the trailer on its own, hence this routine expects only
+   the raw deflate stream to decompress.  This is different from the default
+   behavior of inflate(), which expects a zlib header and trailer around the
+   deflate stream.
+
+     inflateBack() uses two subroutines supplied by the caller that are then
+   called by inflateBack() for input and output.  inflateBack() calls those
+   routines until it reads a complete deflate stream and writes out all of the
+   uncompressed data, or until it encounters an error.  The function's
+   parameters and return types are defined above in the in_func and out_func
+   typedefs.  inflateBack() will call in(in_desc, &buf) which should return the
+   number of bytes of provided input, and a pointer to that input in buf.  If
+   there is no input available, in() must return zero -- buf is ignored in that
+   case -- and inflateBack() will return a buffer error.  inflateBack() will
+   call out(out_desc, buf, len) to write the uncompressed data buf[0..len-1].
+   out() should return zero on success, or non-zero on failure.  If out()
+   returns non-zero, inflateBack() will return with an error.  Neither in() nor
+   out() are permitted to change the contents of the window provided to
+   inflateBackInit(), which is also the buffer that out() uses to write from.
+   The length written by out() will be at most the window size.  Any non-zero
+   amount of input may be provided by in().
+
+     For convenience, inflateBack() can be provided input on the first call by
+   setting strm->next_in and strm->avail_in.  If that input is exhausted, then
+   in() will be called.  Therefore strm->next_in must be initialized before
+   calling inflateBack().  If strm->next_in is Z_NULL, then in() will be called
+   immediately for input.  If strm->next_in is not Z_NULL, then strm->avail_in
+   must also be initialized, and then if strm->avail_in is not zero, input will
+   initially be taken from strm->next_in[0 ..  strm->avail_in - 1].
+
+     The in_desc and out_desc parameters of inflateBack() is passed as the
+   first parameter of in() and out() respectively when they are called.  These
+   descriptors can be optionally used to pass any information that the caller-
+   supplied in() and out() functions need to do their job.
+
+     On return, inflateBack() will set strm->next_in and strm->avail_in to
+   pass back any unused input that was provided by the last in() call.  The
+   return values of inflateBack() can be Z_STREAM_END on success, Z_BUF_ERROR
+   if in() or out() returned an error, Z_DATA_ERROR if there was a format error
+   in the deflate stream (in which case strm->msg is set to indicate the nature
+   of the error), or Z_STREAM_ERROR if the stream was not properly initialized.
+   In the case of Z_BUF_ERROR, an input or output error can be distinguished
+   using strm->next_in which will be Z_NULL only if in() returned an error.  If
+   strm->next_in is not Z_NULL, then the Z_BUF_ERROR was due to out() returning
+   non-zero.  (in() will always be called before out(), so strm->next_in is
+   assured to be defined if out() returns non-zero.)  Note that inflateBack()
+   cannot return Z_OK.
+*/
+
+ZEXTERN int ZEXPORT inflateBackEnd OF((z_streamp strm));
+/*
+     All memory allocated by inflateBackInit() is freed.
+
+     inflateBackEnd() returns Z_OK on success, or Z_STREAM_ERROR if the stream
+   state was inconsistent.
+*/
+
+ZEXTERN uLong ZEXPORT zlibCompileFlags OF((void));
+/* Return flags indicating compile-time options.
+
+    Type sizes, two bits each, 00 = 16 bits, 01 = 32, 10 = 64, 11 = other:
+     1.0: size of uInt
+     3.2: size of uLong
+     5.4: size of voidpf (pointer)
+     7.6: size of z_off_t
+
+    Compiler, assembler, and debug options:
+     8: ZLIB_DEBUG
+     9: ASMV or ASMINF -- use ASM code
+     10: ZLIB_WINAPI -- exported functions use the WINAPI calling convention
+     11: 0 (reserved)
+
+    One-time table building (smaller code, but not thread-safe if true):
+     12: BUILDFIXED -- build static block decoding tables when needed
+     13: DYNAMIC_CRC_TABLE -- build CRC calculation tables when needed
+     14,15: 0 (reserved)
+
+    Library content (indicates missing functionality):
+     16: NO_GZCOMPRESS -- gz* functions cannot compress (to avoid linking
+                          deflate code when not needed)
+     17: NO_GZIP -- deflate can't write gzip streams, and inflate can't detect
+                    and decode gzip streams (to avoid linking crc code)
+     18-19: 0 (reserved)
+
+    Operation variations (changes in library functionality):
+     20: PKZIP_BUG_WORKAROUND -- slightly more permissive inflate
+     21: FASTEST -- deflate algorithm with only one, lowest compression level
+     22,23: 0 (reserved)
+
+    The sprintf variant used by gzprintf (zero is best):
+     24: 0 = vs*, 1 = s* -- 1 means limited to 20 arguments after the format
+     25: 0 = *nprintf, 1 = *printf -- 1 means gzprintf() not secure!
+     26: 0 = returns value, 1 = void -- 1 means inferred string length returned
+
+    Remainder:
+     27-31: 0 (reserved)
+ */
+
+#ifndef Z_SOLO
+
+                        /* utility functions */
+
+/*
+     The following utility functions are implemented on top of the basic
+   stream-oriented functions.  To simplify the interface, some default options
+   are assumed (compression level and memory usage, standard memory allocation
+   functions).  The source code of these utility functions can be modified if
+   you need special options.
+*/
+
+ZEXTERN int ZEXPORT compress OF((Bytef *dest,   uLongf *destLen,
+                                 const Bytef *source, uLong sourceLen));
+/*
+     Compresses the source buffer into the destination buffer.  sourceLen is
+   the byte length of the source buffer.  Upon entry, destLen is the total size
+   of the destination buffer, which must be at least the value returned by
+   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
+   compressed data.  compress() is equivalent to compress2() with a level
+   parameter of Z_DEFAULT_COMPRESSION.
+
+     compress returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_BUF_ERROR if there was not enough room in the output
+   buffer.
+*/
+
+ZEXTERN int ZEXPORT compress2 OF((Bytef *dest,   uLongf *destLen,
+                                  const Bytef *source, uLong sourceLen,
+                                  int level));
+/*
+     Compresses the source buffer into the destination buffer.  The level
+   parameter has the same meaning as in deflateInit.  sourceLen is the byte
+   length of the source buffer.  Upon entry, destLen is the total size of the
+   destination buffer, which must be at least the value returned by
+   compressBound(sourceLen).  Upon exit, destLen is the actual size of the
+   compressed data.
+
+     compress2 returns Z_OK if success, Z_MEM_ERROR if there was not enough
+   memory, Z_BUF_ERROR if there was not enough room in the output buffer,
+   Z_STREAM_ERROR if the level parameter is invalid.
+*/
+
+ZEXTERN uLong ZEXPORT compressBound OF((uLong sourceLen));
+/*
+     compressBound() returns an upper bound on the compressed size after
+   compress() or compress2() on sourceLen bytes.  It would be used before a
+   compress() or compress2() call to allocate the destination buffer.
+*/
+
+ZEXTERN int ZEXPORT uncompress OF((Bytef *dest,   uLongf *destLen,
+                                   const Bytef *source, uLong sourceLen));
+/*
+     Decompresses the source buffer into the destination buffer.  sourceLen is
+   the byte length of the source buffer.  Upon entry, destLen is the total size
+   of the destination buffer, which must be large enough to hold the entire
+   uncompressed data.  (The size of the uncompressed data must have been saved
+   previously by the compressor and transmitted to the decompressor by some
+   mechanism outside the scope of this compression library.) Upon exit, destLen
+   is the actual size of the uncompressed data.
+
+     uncompress returns Z_OK if success, Z_MEM_ERROR if there was not
+   enough memory, Z_BUF_ERROR if there was not enough room in the output
+   buffer, or Z_DATA_ERROR if the input data was corrupted or incomplete.  In
+   the case where there is not enough room, uncompress() will fill the output
+   buffer with the uncompressed data up to that point.
+*/
+
+ZEXTERN int ZEXPORT uncompress2 OF((Bytef *dest,   uLongf *destLen,
+                                    const Bytef *source, uLong *sourceLen));
+/*
+     Same as uncompress, except that sourceLen is a pointer, where the
+   length of the source is *sourceLen.  On return, *sourceLen is the number of
+   source bytes consumed.
+*/
+
+                        /* gzip file access functions */
+
+/*
+     This library supports reading and writing files in gzip (.gz) format with
+   an interface similar to that of stdio, using the functions that start with
+   "gz".  The gzip format is different from the zlib format.  gzip is a gzip
+   wrapper, documented in RFC 1952, wrapped around a deflate stream.
+*/
+
+typedef struct gzFile_s *gzFile;    /* semi-opaque gzip file descriptor */
+
+/*
+ZEXTERN gzFile ZEXPORT gzopen OF((const char *path, const char *mode));
+
+     Opens a gzip (.gz) file for reading or writing.  The mode parameter is as
+   in fopen ("rb" or "wb") but can also include a compression level ("wb9") or
+   a strategy: 'f' for filtered data as in "wb6f", 'h' for Huffman-only
+   compression as in "wb1h", 'R' for run-length encoding as in "wb1R", or 'F'
+   for fixed code compression as in "wb9F".  (See the description of
+   deflateInit2 for more information about the strategy parameter.)  'T' will
+   request transparent writing or appending with no compression and not using
+   the gzip format.
+
+     "a" can be used instead of "w" to request that the gzip stream that will
+   be written be appended to the file.  "+" will result in an error, since
+   reading and writing to the same gzip file is not supported.  The addition of
+   "x" when writing will create the file exclusively, which fails if the file
+   already exists.  On systems that support it, the addition of "e" when
+   reading or writing will set the flag to close the file on an execve() call.
+
+     These functions, as well as gzip, will read and decode a sequence of gzip
+   streams in a file.  The append function of gzopen() can be used to create
+   such a file.  (Also see gzflush() for another way to do this.)  When
+   appending, gzopen does not test whether the file begins with a gzip stream,
+   nor does it look for the end of the gzip streams to begin appending.  gzopen
+   will simply append a gzip stream to the existing file.
+
+     gzopen can be used to read a file which is not in gzip format; in this
+   case gzread will directly read from the file without decompression.  When
+   reading, this will be detected automatically by looking for the magic two-
+   byte gzip header.
+
+     gzopen returns NULL if the file could not be opened, if there was
+   insufficient memory to allocate the gzFile state, or if an invalid mode was
+   specified (an 'r', 'w', or 'a' was not provided, or '+' was provided).
+   errno can be checked to determine if the reason gzopen failed was that the
+   file could not be opened.
+*/
+
+ZEXTERN gzFile ZEXPORT gzdopen OF((int fd, const char *mode));
+/*
+     gzdopen associates a gzFile with the file descriptor fd.  File descriptors
+   are obtained from calls like open, dup, creat, pipe or fileno (if the file
+   has been previously opened with fopen).  The mode parameter is as in gzopen.
+
+     The next call of gzclose on the returned gzFile will also close the file
+   descriptor fd, just like fclose(fdopen(fd, mode)) closes the file descriptor
+   fd.  If you want to keep fd open, use fd = dup(fd_keep); gz = gzdopen(fd,
+   mode);.  The duplicated descriptor should be saved to avoid a leak, since
+   gzdopen does not close fd if it fails.  If you are using fileno() to get the
+   file descriptor from a FILE *, then you will have to use dup() to avoid
+   double-close()ing the file descriptor.  Both gzclose() and fclose() will
+   close the associated file descriptor, so they need to have different file
+   descriptors.
+
+     gzdopen returns NULL if there was insufficient memory to allocate the
+   gzFile state, if an invalid mode was specified (an 'r', 'w', or 'a' was not
+   provided, or '+' was provided), or if fd is -1.  The file descriptor is not
+   used until the next gz* read, write, seek, or close operation, so gzdopen
+   will not detect if fd is invalid (unless fd is -1).
+*/
+
+ZEXTERN int ZEXPORT gzbuffer OF((gzFile file, unsigned size));
+/*
+     Set the internal buffer size used by this library's functions.  The
+   default buffer size is 8192 bytes.  This function must be called after
+   gzopen() or gzdopen(), and before any other calls that read or write the
+   file.  The buffer memory allocation is always deferred to the first read or
+   write.  Three times that size in buffer space is allocated.  A larger buffer
+   size of, for example, 64K or 128K bytes will noticeably increase the speed
+   of decompression (reading).
+
+     The new buffer size also affects the maximum length for gzprintf().
+
+     gzbuffer() returns 0 on success, or -1 on failure, such as being called
+   too late.
+*/
+
+ZEXTERN int ZEXPORT gzsetparams OF((gzFile file, int level, int strategy));
+/*
+     Dynamically update the compression level or strategy.  See the description
+   of deflateInit2 for the meaning of these parameters.  Previously provided
+   data is flushed before the parameter change.
+
+     gzsetparams returns Z_OK if success, Z_STREAM_ERROR if the file was not
+   opened for writing, Z_ERRNO if there is an error writing the flushed data,
+   or Z_MEM_ERROR if there is a memory allocation error.
+*/
+
+ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
+/*
+     Reads the given number of uncompressed bytes from the compressed file.  If
+   the input file is not in gzip format, gzread copies the given number of
+   bytes into the buffer directly from the file.
+
+     After reaching the end of a gzip stream in the input, gzread will continue
+   to read, looking for another gzip stream.  Any number of gzip streams may be
+   concatenated in the input file, and will all be decompressed by gzread().
+   If something other than a gzip stream is encountered after a gzip stream,
+   that remaining trailing garbage is ignored (and no error is returned).
+
+     gzread can be used to read a gzip file that is being concurrently written.
+   Upon reaching the end of the input, gzread will return with the available
+   data.  If the error code returned by gzerror is Z_OK or Z_BUF_ERROR, then
+   gzclearerr can be used to clear the end of file indicator in order to permit
+   gzread to be tried again.  Z_OK indicates that a gzip stream was completed
+   on the last gzread.  Z_BUF_ERROR indicates that the input file ended in the
+   middle of a gzip stream.  Note that gzread does not return -1 in the event
+   of an incomplete gzip stream.  This error is deferred until gzclose(), which
+   will return Z_BUF_ERROR if the last gzread ended in the middle of a gzip
+   stream.  Alternatively, gzerror can be used before gzclose to detect this
+   case.
+
+     gzread returns the number of uncompressed bytes actually read, less than
+   len for end of file, or -1 for error.  If len is too large to fit in an int,
+   then nothing is read, -1 is returned, and the error state is set to
+   Z_STREAM_ERROR.
+*/
+
+ZEXTERN z_size_t ZEXPORT gzfread OF((voidp buf, z_size_t size, z_size_t nitems,
+                                     gzFile file));
+/*
+     Read up to nitems items of size size from file to buf, otherwise operating
+   as gzread() does.  This duplicates the interface of stdio's fread(), with
+   size_t request and return types.  If the library defines size_t, then
+   z_size_t is identical to size_t.  If not, then z_size_t is an unsigned
+   integer type that can contain a pointer.
+
+     gzfread() returns the number of full items read of size size, or zero if
+   the end of the file was reached and a full item could not be read, or if
+   there was an error.  gzerror() must be consulted if zero is returned in
+   order to determine if there was an error.  If the multiplication of size and
+   nitems overflows, i.e. the product does not fit in a z_size_t, then nothing
+   is read, zero is returned, and the error state is set to Z_STREAM_ERROR.
+
+     In the event that the end of file is reached and only a partial item is
+   available at the end, i.e. the remaining uncompressed data length is not a
+   multiple of size, then the final partial item is nevetheless read into buf
+   and the end-of-file flag is set.  The length of the partial item read is not
+   provided, but could be inferred from the result of gztell().  This behavior
+   is the same as the behavior of fread() implementations in common libraries,
+   but it prevents the direct use of gzfread() to read a concurrently written
+   file, reseting and retrying on end-of-file, when size is not 1.
+*/
+
+ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
+                                voidpc buf, unsigned len));
+/*
+     Writes the given number of uncompressed bytes into the compressed file.
+   gzwrite returns the number of uncompressed bytes written or 0 in case of
+   error.
+*/
+
+ZEXTERN z_size_t ZEXPORT gzfwrite OF((voidpc buf, z_size_t size,
+                                      z_size_t nitems, gzFile file));
+/*
+     gzfwrite() writes nitems items of size size from buf to file, duplicating
+   the interface of stdio's fwrite(), with size_t request and return types.  If
+   the library defines size_t, then z_size_t is identical to size_t.  If not,
+   then z_size_t is an unsigned integer type that can contain a pointer.
+
+     gzfwrite() returns the number of full items written of size size, or zero
+   if there was an error.  If the multiplication of size and nitems overflows,
+   i.e. the product does not fit in a z_size_t, then nothing is written, zero
+   is returned, and the error state is set to Z_STREAM_ERROR.
+*/
+
+ZEXTERN int ZEXPORTVA gzprintf Z_ARG((gzFile file, const char *format, ...));
+/*
+     Converts, formats, and writes the arguments to the compressed file under
+   control of the format string, as in fprintf.  gzprintf returns the number of
+   uncompressed bytes actually written, or a negative zlib error code in case
+   of error.  The number of uncompressed bytes written is limited to 8191, or
+   one less than the buffer size given to gzbuffer().  The caller should assure
+   that this limit is not exceeded.  If it is exceeded, then gzprintf() will
+   return an error (0) with nothing written.  In this case, there may also be a
+   buffer overflow with unpredictable consequences, which is possible only if
+   zlib was compiled with the insecure functions sprintf() or vsprintf()
+   because the secure snprintf() or vsnprintf() functions were not available.
+   This can be determined using zlibCompileFlags().
+*/
+
+ZEXTERN int ZEXPORT gzputs OF((gzFile file, const char *s));
+/*
+     Writes the given null-terminated string to the compressed file, excluding
+   the terminating null character.
+
+     gzputs returns the number of characters written, or -1 in case of error.
+*/
+
+ZEXTERN char * ZEXPORT gzgets OF((gzFile file, char *buf, int len));
+/*
+     Reads bytes from the compressed file until len-1 characters are read, or a
+   newline character is read and transferred to buf, or an end-of-file
+   condition is encountered.  If any characters are read or if len == 1, the
+   string is terminated with a null character.  If no characters are read due
+   to an end-of-file or len < 1, then the buffer is left untouched.
+
+     gzgets returns buf which is a null-terminated string, or it returns NULL
+   for end-of-file or in case of error.  If there was an error, the contents at
+   buf are indeterminate.
+*/
+
+ZEXTERN int ZEXPORT gzputc OF((gzFile file, int c));
+/*
+     Writes c, converted to an unsigned char, into the compressed file.  gzputc
+   returns the value that was written, or -1 in case of error.
+*/
+
+ZEXTERN int ZEXPORT gzgetc OF((gzFile file));
+/*
+     Reads one byte from the compressed file.  gzgetc returns this byte or -1
+   in case of end of file or error.  This is implemented as a macro for speed.
+   As such, it does not do all of the checking the other functions do.  I.e.
+   it does not check to see if file is NULL, nor whether the structure file
+   points to has been clobbered or not.
+*/
+
+ZEXTERN int ZEXPORT gzungetc OF((int c, gzFile file));
+/*
+     Push one character back onto the stream to be read as the first character
+   on the next read.  At least one character of push-back is allowed.
+   gzungetc() returns the character pushed, or -1 on failure.  gzungetc() will
+   fail if c is -1, and may fail if a character has been pushed but not read
+   yet.  If gzungetc is used immediately after gzopen or gzdopen, at least the
+   output buffer size of pushed characters is allowed.  (See gzbuffer above.)
+   The pushed character will be discarded if the stream is repositioned with
+   gzseek() or gzrewind().
+*/
+
+ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
+/*
+     Flushes all pending output into the compressed file.  The parameter flush
+   is as in the deflate() function.  The return value is the zlib error number
+   (see function gzerror below).  gzflush is only permitted when writing.
+
+     If the flush parameter is Z_FINISH, the remaining data is written and the
+   gzip stream is completed in the output.  If gzwrite() is called again, a new
+   gzip stream will be started in the output.  gzread() is able to read such
+   concatenated gzip streams.
+
+     gzflush should be called only when strictly necessary because it will
+   degrade compression if called too often.
+*/
+
+/*
+ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
+                                   z_off_t offset, int whence));
+
+     Sets the starting position for the next gzread or gzwrite on the given
+   compressed file.  The offset represents a number of bytes in the
+   uncompressed data stream.  The whence parameter is defined as in lseek(2);
+   the value SEEK_END is not supported.
+
+     If the file is opened for reading, this function is emulated but can be
+   extremely slow.  If the file is opened for writing, only forward seeks are
+   supported; gzseek then compresses a sequence of zeroes up to the new
+   starting position.
+
+     gzseek returns the resulting offset location as measured in bytes from
+   the beginning of the uncompressed stream, or -1 in case of error, in
+   particular if the file is opened for writing and the new starting position
+   would be before the current position.
+*/
+
+ZEXTERN int ZEXPORT    gzrewind OF((gzFile file));
+/*
+     Rewinds the given file. This function is supported only for reading.
+
+     gzrewind(file) is equivalent to (int)gzseek(file, 0L, SEEK_SET)
+*/
+
+/*
+ZEXTERN z_off_t ZEXPORT    gztell OF((gzFile file));
+
+     Returns the starting position for the next gzread or gzwrite on the given
+   compressed file.  This position represents a number of bytes in the
+   uncompressed data stream, and is zero when starting, even if appending or
+   reading a gzip stream from the middle of a file using gzdopen().
+
+     gztell(file) is equivalent to gzseek(file, 0L, SEEK_CUR)
+*/
+
+/*
+ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile file));
+
+     Returns the current offset in the file being read or written.  This offset
+   includes the count of bytes that precede the gzip stream, for example when
+   appending or when using gzdopen() for reading.  When reading, the offset
+   does not include as yet unused buffered input.  This information can be used
+   for a progress indicator.  On error, gzoffset() returns -1.
+*/
+
+ZEXTERN int ZEXPORT gzeof OF((gzFile file));
+/*
+     Returns true (1) if the end-of-file indicator has been set while reading,
+   false (0) otherwise.  Note that the end-of-file indicator is set only if the
+   read tried to go past the end of the input, but came up short.  Therefore,
+   just like feof(), gzeof() may return false even if there is no more data to
+   read, in the event that the last read request was for the exact number of
+   bytes remaining in the input file.  This will happen if the input file size
+   is an exact multiple of the buffer size.
+
+     If gzeof() returns true, then the read functions will return no more data,
+   unless the end-of-file indicator is reset by gzclearerr() and the input file
+   has grown since the previous end of file was detected.
+*/
+
+ZEXTERN int ZEXPORT gzdirect OF((gzFile file));
+/*
+     Returns true (1) if file is being copied directly while reading, or false
+   (0) if file is a gzip stream being decompressed.
+
+     If the input file is empty, gzdirect() will return true, since the input
+   does not contain a gzip stream.
+
+     If gzdirect() is used immediately after gzopen() or gzdopen() it will
+   cause buffers to be allocated to allow reading the file to determine if it
+   is a gzip file.  Therefore if gzbuffer() is used, it should be called before
+   gzdirect().
+
+     When writing, gzdirect() returns true (1) if transparent writing was
+   requested ("wT" for the gzopen() mode), or false (0) otherwise.  (Note:
+   gzdirect() is not needed when writing.  Transparent writing must be
+   explicitly requested, so the application already knows the answer.  When
+   linking statically, using gzdirect() will include all of the zlib code for
+   gzip file reading and decompression, which may not be desired.)
+*/
+
+ZEXTERN int ZEXPORT    gzclose OF((gzFile file));
+/*
+     Flushes all pending output if necessary, closes the compressed file and
+   deallocates the (de)compression state.  Note that once file is closed, you
+   cannot call gzerror with file, since its structures have been deallocated.
+   gzclose must not be called more than once on the same file, just as free
+   must not be called more than once on the same allocation.
+
+     gzclose will return Z_STREAM_ERROR if file is not valid, Z_ERRNO on a
+   file operation error, Z_MEM_ERROR if out of memory, Z_BUF_ERROR if the
+   last read ended in the middle of a gzip stream, or Z_OK on success.
+*/
+
+ZEXTERN int ZEXPORT gzclose_r OF((gzFile file));
+ZEXTERN int ZEXPORT gzclose_w OF((gzFile file));
+/*
+     Same as gzclose(), but gzclose_r() is only for use when reading, and
+   gzclose_w() is only for use when writing or appending.  The advantage to
+   using these instead of gzclose() is that they avoid linking in zlib
+   compression or decompression code that is not used when only reading or only
+   writing respectively.  If gzclose() is used, then both compression and
+   decompression code will be included the application when linking to a static
+   zlib library.
+*/
+
+ZEXTERN const char * ZEXPORT gzerror OF((gzFile file, int *errnum));
+/*
+     Returns the error message for the last error which occurred on the given
+   compressed file.  errnum is set to zlib error number.  If an error occurred
+   in the file system and not in the compression library, errnum is set to
+   Z_ERRNO and the application may consult errno to get the exact error code.
+
+     The application must not modify the returned string.  Future calls to
+   this function may invalidate the previously returned string.  If file is
+   closed, then the string previously returned by gzerror will no longer be
+   available.
+
+     gzerror() should be used to distinguish errors from end-of-file for those
+   functions above that do not distinguish those cases in their return values.
+*/
+
+ZEXTERN void ZEXPORT gzclearerr OF((gzFile file));
+/*
+     Clears the error and end-of-file flags for file.  This is analogous to the
+   clearerr() function in stdio.  This is useful for continuing to read a gzip
+   file that is being written concurrently.
+*/
+
+#endif /* !Z_SOLO */
+
+                        /* checksum functions */
+
+/*
+     These functions are not related to compression but are exported
+   anyway because they might be useful in applications using the compression
+   library.
+*/
+
+ZEXTERN uLong ZEXPORT adler32 OF((uLong adler, const Bytef *buf, uInt len));
+/*
+     Update a running Adler-32 checksum with the bytes buf[0..len-1] and
+   return the updated checksum.  If buf is Z_NULL, this function returns the
+   required initial value for the checksum.
+
+     An Adler-32 checksum is almost as reliable as a CRC-32 but can be computed
+   much faster.
+
+   Usage example:
+
+     uLong adler = adler32(0L, Z_NULL, 0);
+
+     while (read_buffer(buffer, length) != EOF) {
+       adler = adler32(adler, buffer, length);
+     }
+     if (adler != original_adler) error();
+*/
+
+ZEXTERN uLong ZEXPORT adler32_z OF((uLong adler, const Bytef *buf,
+                                    z_size_t len));
+/*
+     Same as adler32(), but with a size_t length.
+*/
+
+/*
+ZEXTERN uLong ZEXPORT adler32_combine OF((uLong adler1, uLong adler2,
+                                          z_off_t len2));
+
+     Combine two Adler-32 checksums into one.  For two sequences of bytes, seq1
+   and seq2 with lengths len1 and len2, Adler-32 checksums were calculated for
+   each, adler1 and adler2.  adler32_combine() returns the Adler-32 checksum of
+   seq1 and seq2 concatenated, requiring only adler1, adler2, and len2.  Note
+   that the z_off_t type (like off_t) is a signed integer.  If len2 is
+   negative, the result has no meaning or utility.
+*/
+
+ZEXTERN uLong ZEXPORT crc32   OF((uLong crc, const Bytef *buf, uInt len));
+/*
+     Update a running CRC-32 with the bytes buf[0..len-1] and return the
+   updated CRC-32.  If buf is Z_NULL, this function returns the required
+   initial value for the crc.  Pre- and post-conditioning (one's complement) is
+   performed within this function so it shouldn't be done by the application.
+
+   Usage example:
+
+     uLong crc = crc32(0L, Z_NULL, 0);
+
+     while (read_buffer(buffer, length) != EOF) {
+       crc = crc32(crc, buffer, length);
+     }
+     if (crc != original_crc) error();
+*/
+
+ZEXTERN uLong ZEXPORT crc32_z OF((uLong adler, const Bytef *buf,
+                                  z_size_t len));
+/*
+     Same as crc32(), but with a size_t length.
+*/
+
+/*
+ZEXTERN uLong ZEXPORT crc32_combine OF((uLong crc1, uLong crc2, z_off_t len2));
+
+     Combine two CRC-32 check values into one.  For two sequences of bytes,
+   seq1 and seq2 with lengths len1 and len2, CRC-32 check values were
+   calculated for each, crc1 and crc2.  crc32_combine() returns the CRC-32
+   check value of seq1 and seq2 concatenated, requiring only crc1, crc2, and
+   len2.
+*/
+
+
+                        /* various hacks, don't look :) */
+
+/* deflateInit and inflateInit are macros to allow checking the zlib version
+ * and the compiler's view of z_stream:
+ */
+ZEXTERN int ZEXPORT deflateInit_ OF((z_streamp strm, int level,
+                                     const char *version, int stream_size));
+ZEXTERN int ZEXPORT inflateInit_ OF((z_streamp strm,
+                                     const char *version, int stream_size));
+ZEXTERN int ZEXPORT deflateInit2_ OF((z_streamp strm, int  level, int  method,
+                                      int windowBits, int memLevel,
+                                      int strategy, const char *version,
+                                      int stream_size));
+ZEXTERN int ZEXPORT inflateInit2_ OF((z_streamp strm, int  windowBits,
+                                      const char *version, int stream_size));
+ZEXTERN int ZEXPORT inflateBackInit_ OF((z_streamp strm, int windowBits,
+                                         unsigned char FAR *window,
+                                         const char *version,
+                                         int stream_size));
+#ifdef Z_PREFIX_SET
+#  define z_deflateInit(strm, level) \
+          deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
+#  define z_inflateInit(strm) \
+          inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
+#  define z_deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
+          deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
+                        (strategy), ZLIB_VERSION, (int)sizeof(z_stream))
+#  define z_inflateInit2(strm, windowBits) \
+          inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
+                        (int)sizeof(z_stream))
+#  define z_inflateBackInit(strm, windowBits, window) \
+          inflateBackInit_((strm), (windowBits), (window), \
+                           ZLIB_VERSION, (int)sizeof(z_stream))
+#else
+#  define deflateInit(strm, level) \
+          deflateInit_((strm), (level), ZLIB_VERSION, (int)sizeof(z_stream))
+#  define inflateInit(strm) \
+          inflateInit_((strm), ZLIB_VERSION, (int)sizeof(z_stream))
+#  define deflateInit2(strm, level, method, windowBits, memLevel, strategy) \
+          deflateInit2_((strm),(level),(method),(windowBits),(memLevel),\
+                        (strategy), ZLIB_VERSION, (int)sizeof(z_stream))
+#  define inflateInit2(strm, windowBits) \
+          inflateInit2_((strm), (windowBits), ZLIB_VERSION, \
+                        (int)sizeof(z_stream))
+#  define inflateBackInit(strm, windowBits, window) \
+          inflateBackInit_((strm), (windowBits), (window), \
+                           ZLIB_VERSION, (int)sizeof(z_stream))
+#endif
+
+#ifndef Z_SOLO
+
+/* gzgetc() macro and its supporting function and exposed data structure.  Note
+ * that the real internal state is much larger than the exposed structure.
+ * This abbreviated structure exposes just enough for the gzgetc() macro.  The
+ * user should not mess with these exposed elements, since their names or
+ * behavior could change in the future, perhaps even capriciously.  They can
+ * only be used by the gzgetc() macro.  You have been warned.
+ */
+struct gzFile_s {
+    unsigned have;
+    unsigned char *next;
+    z_off64_t pos;
+};
+ZEXTERN int ZEXPORT gzgetc_ OF((gzFile file));  /* backward compatibility */
+#ifdef Z_PREFIX_SET
+#  undef z_gzgetc
+#  define z_gzgetc(g) \
+          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g))
+#else
+#  define gzgetc(g) \
+          ((g)->have ? ((g)->have--, (g)->pos++, *((g)->next)++) : (gzgetc)(g))
+#endif
+
+/* provide 64-bit offset functions if _LARGEFILE64_SOURCE defined, and/or
+ * change the regular functions to 64 bits if _FILE_OFFSET_BITS is 64 (if
+ * both are true, the application gets the *64 functions, and the regular
+ * functions are changed to 64 bits) -- in case these are set on systems
+ * without large file support, _LFS64_LARGEFILE must also be true
+ */
+#ifdef Z_LARGE64
+   ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+   ZEXTERN z_off64_t ZEXPORT gzseek64 OF((gzFile, z_off64_t, int));
+   ZEXTERN z_off64_t ZEXPORT gztell64 OF((gzFile));
+   ZEXTERN z_off64_t ZEXPORT gzoffset64 OF((gzFile));
+   ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off64_t));
+   ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off64_t));
+#endif
+
+#if !defined(ZLIB_INTERNAL) && defined(Z_WANT64)
+#  ifdef Z_PREFIX_SET
+#    define z_gzopen z_gzopen64
+#    define z_gzseek z_gzseek64
+#    define z_gztell z_gztell64
+#    define z_gzoffset z_gzoffset64
+#    define z_adler32_combine z_adler32_combine64
+#    define z_crc32_combine z_crc32_combine64
+#  else
+#    define gzopen gzopen64
+#    define gzseek gzseek64
+#    define gztell gztell64
+#    define gzoffset gzoffset64
+#    define adler32_combine adler32_combine64
+#    define crc32_combine crc32_combine64
+#  endif
+#  ifndef Z_LARGE64
+     ZEXTERN gzFile ZEXPORT gzopen64 OF((const char *, const char *));
+     ZEXTERN z_off_t ZEXPORT gzseek64 OF((gzFile, z_off_t, int));
+     ZEXTERN z_off_t ZEXPORT gztell64 OF((gzFile));
+     ZEXTERN z_off_t ZEXPORT gzoffset64 OF((gzFile));
+     ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
+     ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
+#  endif
+#else
+   ZEXTERN gzFile ZEXPORT gzopen OF((const char *, const char *));
+   ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile, z_off_t, int));
+   ZEXTERN z_off_t ZEXPORT gztell OF((gzFile));
+   ZEXTERN z_off_t ZEXPORT gzoffset OF((gzFile));
+   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
+   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
+#endif
+
+#else /* Z_SOLO */
+
+   ZEXTERN uLong ZEXPORT adler32_combine OF((uLong, uLong, z_off_t));
+   ZEXTERN uLong ZEXPORT crc32_combine OF((uLong, uLong, z_off_t));
+
+#endif /* !Z_SOLO */
+
+/* undocumented functions */
+ZEXTERN const char   * ZEXPORT zError           OF((int));
+ZEXTERN int            ZEXPORT inflateSyncPoint OF((z_streamp));
+ZEXTERN const z_crc_t FAR * ZEXPORT get_crc_table    OF((void));
+ZEXTERN int            ZEXPORT inflateUndermine OF((z_streamp, int));
+ZEXTERN int            ZEXPORT inflateValidate OF((z_streamp, int));
+ZEXTERN unsigned long  ZEXPORT inflateCodesUsed OF ((z_streamp));
+ZEXTERN int            ZEXPORT inflateResetKeep OF((z_streamp));
+ZEXTERN int            ZEXPORT deflateResetKeep OF((z_streamp));
+#if (defined(_WIN32) || defined(__CYGWIN__)) && !defined(Z_SOLO)
+ZEXTERN gzFile         ZEXPORT gzopen_w OF((const wchar_t *path,
+                                            const char *mode));
+#endif
+#if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#  ifndef Z_SOLO
+ZEXTERN int            ZEXPORTVA gzvprintf Z_ARG((gzFile file,
+                                                  const char *format,
+                                                  va_list va));
+#  endif
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ZLIB_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/zutil.c	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,350 @@
+/*
+ * 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.
+ */
+
+/* zutil.c -- target dependent utility functions for the compression library
+ * Copyright (C) 1995-2017 Jean-loup Gailly
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* @(#) $Id$ */
+
+#include "zutil.h"
+
+#ifndef Z_SOLO
+#  include "gzguts.h"
+#endif
+
+z_const char * const z_errmsg[10] = {
+    (z_const char *)"need dictionary",     /* Z_NEED_DICT       2  */
+    (z_const char *)"stream end",          /* Z_STREAM_END      1  */
+    (z_const char *)"",                    /* Z_OK              0  */
+    (z_const char *)"file error",          /* Z_ERRNO         (-1) */
+    (z_const char *)"stream error",        /* Z_STREAM_ERROR  (-2) */
+    (z_const char *)"data error",          /* Z_DATA_ERROR    (-3) */
+    (z_const char *)"insufficient memory", /* Z_MEM_ERROR     (-4) */
+    (z_const char *)"buffer error",        /* Z_BUF_ERROR     (-5) */
+    (z_const char *)"incompatible version",/* Z_VERSION_ERROR (-6) */
+    (z_const char *)""
+};
+
+
+const char * ZEXPORT zlibVersion()
+{
+    return ZLIB_VERSION;
+}
+
+uLong ZEXPORT zlibCompileFlags()
+{
+    uLong flags;
+
+    flags = 0;
+    switch ((int)(sizeof(uInt))) {
+    case 2:     break;
+    case 4:     flags += 1;     break;
+    case 8:     flags += 2;     break;
+    default:    flags += 3;
+    }
+    switch ((int)(sizeof(uLong))) {
+    case 2:     break;
+    case 4:     flags += 1 << 2;        break;
+    case 8:     flags += 2 << 2;        break;
+    default:    flags += 3 << 2;
+    }
+    switch ((int)(sizeof(voidpf))) {
+    case 2:     break;
+    case 4:     flags += 1 << 4;        break;
+    case 8:     flags += 2 << 4;        break;
+    default:    flags += 3 << 4;
+    }
+    switch ((int)(sizeof(z_off_t))) {
+    case 2:     break;
+    case 4:     flags += 1 << 6;        break;
+    case 8:     flags += 2 << 6;        break;
+    default:    flags += 3 << 6;
+    }
+#ifdef ZLIB_DEBUG
+    flags += 1 << 8;
+#endif
+#if defined(ASMV) || defined(ASMINF)
+    flags += 1 << 9;
+#endif
+#ifdef ZLIB_WINAPI
+    flags += 1 << 10;
+#endif
+#ifdef BUILDFIXED
+    flags += 1 << 12;
+#endif
+#ifdef DYNAMIC_CRC_TABLE
+    flags += 1 << 13;
+#endif
+#ifdef NO_GZCOMPRESS
+    flags += 1L << 16;
+#endif
+#ifdef NO_GZIP
+    flags += 1L << 17;
+#endif
+#ifdef PKZIP_BUG_WORKAROUND
+    flags += 1L << 20;
+#endif
+#ifdef FASTEST
+    flags += 1L << 21;
+#endif
+#if defined(STDC) || defined(Z_HAVE_STDARG_H)
+#  ifdef NO_vsnprintf
+    flags += 1L << 25;
+#    ifdef HAS_vsprintf_void
+    flags += 1L << 26;
+#    endif
+#  else
+#    ifdef HAS_vsnprintf_void
+    flags += 1L << 26;
+#    endif
+#  endif
+#else
+    flags += 1L << 24;
+#  ifdef NO_snprintf
+    flags += 1L << 25;
+#    ifdef HAS_sprintf_void
+    flags += 1L << 26;
+#    endif
+#  else
+#    ifdef HAS_snprintf_void
+    flags += 1L << 26;
+#    endif
+#  endif
+#endif
+    return flags;
+}
+
+#ifdef ZLIB_DEBUG
+#include <stdlib.h>
+#  ifndef verbose
+#    define verbose 0
+#  endif
+int ZLIB_INTERNAL z_verbose = verbose;
+
+void ZLIB_INTERNAL z_error (m)
+    char *m;
+{
+    fprintf(stderr, "%s\n", m);
+    exit(1);
+}
+#endif
+
+/* exported to allow conversion of error code to string for compress() and
+ * uncompress()
+ */
+const char * ZEXPORT zError(err)
+    int err;
+{
+    return ERR_MSG(err);
+}
+
+#if defined(_WIN32_WCE)
+    /* The Microsoft C Run-Time Library for Windows CE doesn't have
+     * errno.  We define it as a global variable to simplify porting.
+     * Its value is always 0 and should not be used.
+     */
+    int errno = 0;
+#endif
+
+#ifndef HAVE_MEMCPY
+
+void ZLIB_INTERNAL zmemcpy(dest, source, len)
+    Bytef* dest;
+    const Bytef* source;
+    uInt  len;
+{
+    if (len == 0) return;
+    do {
+        *dest++ = *source++; /* ??? to be unrolled */
+    } while (--len != 0);
+}
+
+int ZLIB_INTERNAL zmemcmp(s1, s2, len)
+    const Bytef* s1;
+    const Bytef* s2;
+    uInt  len;
+{
+    uInt j;
+
+    for (j = 0; j < len; j++) {
+        if (s1[j] != s2[j]) return 2*(s1[j] > s2[j])-1;
+    }
+    return 0;
+}
+
+void ZLIB_INTERNAL zmemzero(dest, len)
+    Bytef* dest;
+    uInt  len;
+{
+    if (len == 0) return;
+    do {
+        *dest++ = 0;  /* ??? to be unrolled */
+    } while (--len != 0);
+}
+#endif
+
+#ifndef Z_SOLO
+
+#ifdef SYS16BIT
+
+#ifdef __TURBOC__
+/* Turbo C in 16-bit mode */
+
+#  define MY_ZCALLOC
+
+/* Turbo C malloc() does not allow dynamic allocation of 64K bytes
+ * and farmalloc(64K) returns a pointer with an offset of 8, so we
+ * must fix the pointer. Warning: the pointer must be put back to its
+ * original form in order to free it, use zcfree().
+ */
+
+#define MAX_PTR 10
+/* 10*64K = 640K */
+
+local int next_ptr = 0;
+
+typedef struct ptr_table_s {
+    voidpf org_ptr;
+    voidpf new_ptr;
+} ptr_table;
+
+local ptr_table table[MAX_PTR];
+/* This table is used to remember the original form of pointers
+ * to large buffers (64K). Such pointers are normalized with a zero offset.
+ * Since MSDOS is not a preemptive multitasking OS, this table is not
+ * protected from concurrent access. This hack doesn't work anyway on
+ * a protected system like OS/2. Use Microsoft C instead.
+ */
+
+voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, unsigned items, unsigned size)
+{
+    voidpf buf;
+    ulg bsize = (ulg)items*size;
+
+    (void)opaque;
+
+    /* If we allocate less than 65520 bytes, we assume that farmalloc
+     * will return a usable pointer which doesn't have to be normalized.
+     */
+    if (bsize < 65520L) {
+        buf = farmalloc(bsize);
+        if (*(ush*)&buf != 0) return buf;
+    } else {
+        buf = farmalloc(bsize + 16L);
+    }
+    if (buf == NULL || next_ptr >= MAX_PTR) return NULL;
+    table[next_ptr].org_ptr = buf;
+
+    /* Normalize the pointer to seg:0 */
+    *((ush*)&buf+1) += ((ush)((uch*)buf-0) + 15) >> 4;
+    *(ush*)&buf = 0;
+    table[next_ptr++].new_ptr = buf;
+    return buf;
+}
+
+void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
+{
+    int n;
+
+    (void)opaque;
+
+    if (*(ush*)&ptr != 0) { /* object < 64K */
+        farfree(ptr);
+        return;
+    }
+    /* Find the original pointer */
+    for (n = 0; n < next_ptr; n++) {
+        if (ptr != table[n].new_ptr) continue;
+
+        farfree(table[n].org_ptr);
+        while (++n < next_ptr) {
+            table[n-1] = table[n];
+        }
+        next_ptr--;
+        return;
+    }
+    Assert(0, "zcfree: ptr not found");
+}
+
+#endif /* __TURBOC__ */
+
+
+#ifdef M_I86
+/* Microsoft C in 16-bit mode */
+
+#  define MY_ZCALLOC
+
+#if (!defined(_MSC_VER) || (_MSC_VER <= 600))
+#  define _halloc  halloc
+#  define _hfree   hfree
+#endif
+
+voidpf ZLIB_INTERNAL zcalloc (voidpf opaque, uInt items, uInt size)
+{
+    (void)opaque;
+    return _halloc((long)items, size);
+}
+
+void ZLIB_INTERNAL zcfree (voidpf opaque, voidpf ptr)
+{
+    (void)opaque;
+    _hfree(ptr);
+}
+
+#endif /* M_I86 */
+
+#endif /* SYS16BIT */
+
+
+#ifndef MY_ZCALLOC /* Any system without a special alloc function */
+
+#ifndef STDC
+extern voidp  malloc OF((uInt size));
+extern voidp  calloc OF((uInt items, uInt size));
+extern void   free   OF((voidpf ptr));
+#endif
+
+voidpf ZLIB_INTERNAL zcalloc (opaque, items, size)
+    voidpf opaque;
+    unsigned items;
+    unsigned size;
+{
+    (void)opaque;
+    return sizeof(uInt) > 2 ? (voidpf)malloc(items * size) :
+                              (voidpf)calloc(items, size);
+}
+
+void ZLIB_INTERNAL zcfree (opaque, ptr)
+    voidpf opaque;
+    voidpf ptr;
+{
+    (void)opaque;
+    free(ptr);
+}
+
+#endif /* MY_ZCALLOC */
+
+#endif /* !Z_SOLO */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/share/native/libzip/zlib/zutil.h	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,295 @@
+/*
+ * 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.
+ */
+
+/* zutil.h -- internal interface and configuration of the compression library
+ * Copyright (C) 1995-2016 Jean-loup Gailly, Mark Adler
+ * For conditions of distribution and use, see copyright notice in zlib.h
+ */
+
+/* WARNING: this file should *not* be used by applications. It is
+   part of the implementation of the compression library and is
+   subject to change. Applications should only use zlib.h.
+ */
+
+/* @(#) $Id$ */
+
+#ifndef ZUTIL_H
+#define ZUTIL_H
+
+#ifdef HAVE_HIDDEN
+#  define ZLIB_INTERNAL __attribute__((visibility ("hidden")))
+#else
+#  define ZLIB_INTERNAL
+#endif
+
+#include "zlib.h"
+
+#if defined(STDC) && !defined(Z_SOLO)
+#  if !(defined(_WIN32_WCE) && defined(_MSC_VER))
+#    include <stddef.h>
+#  endif
+#  include <string.h>
+#  include <stdlib.h>
+#endif
+
+#ifdef Z_SOLO
+   typedef long ptrdiff_t;  /* guess -- will be caught if guess is wrong */
+#endif
+
+#ifndef local
+#  define local static
+#endif
+/* since "static" is used to mean two completely different things in C, we
+   define "local" for the non-static meaning of "static", for readability
+   (compile with -Dlocal if your debugger can't find static symbols) */
+
+typedef unsigned char  uch;
+typedef uch FAR uchf;
+typedef unsigned short ush;
+typedef ush FAR ushf;
+typedef unsigned long  ulg;
+
+extern z_const char * const z_errmsg[10]; /* indexed by 2-zlib_error */
+/* (size given to avoid silly warnings with Visual C++) */
+
+#define ERR_MSG(err) z_errmsg[Z_NEED_DICT-(err)]
+
+#define ERR_RETURN(strm,err) \
+  return (strm->msg = ERR_MSG(err), (err))
+/* To be used only when the state is known to be valid */
+
+        /* common constants */
+
+#ifndef DEF_WBITS
+#  define DEF_WBITS MAX_WBITS
+#endif
+/* default windowBits for decompression. MAX_WBITS is for compression only */
+
+#if MAX_MEM_LEVEL >= 8
+#  define DEF_MEM_LEVEL 8
+#else
+#  define DEF_MEM_LEVEL  MAX_MEM_LEVEL
+#endif
+/* default memLevel */
+
+#define STORED_BLOCK 0
+#define STATIC_TREES 1
+#define DYN_TREES    2
+/* The three kinds of block type */
+
+#define MIN_MATCH  3
+#define MAX_MATCH  258
+/* The minimum and maximum match lengths */
+
+#define PRESET_DICT 0x20 /* preset dictionary flag in zlib header */
+
+        /* target dependencies */
+
+#if defined(MSDOS) || (defined(WINDOWS) && !defined(WIN32))
+#  define OS_CODE  0x00
+#  ifndef Z_SOLO
+#    if defined(__TURBOC__) || defined(__BORLANDC__)
+#      if (__STDC__ == 1) && (defined(__LARGE__) || defined(__COMPACT__))
+         /* Allow compilation with ANSI keywords only enabled */
+         void _Cdecl farfree( void *block );
+         void *_Cdecl farmalloc( unsigned long nbytes );
+#      else
+#        include <alloc.h>
+#      endif
+#    else /* MSC or DJGPP */
+#      include <malloc.h>
+#    endif
+#  endif
+#endif
+
+#ifdef AMIGA
+#  define OS_CODE  1
+#endif
+
+#if defined(VAXC) || defined(VMS)
+#  define OS_CODE  2
+#  define F_OPEN(name, mode) \
+     fopen((name), (mode), "mbc=60", "ctx=stm", "rfm=fix", "mrs=512")
+#endif
+
+#ifdef __370__
+#  if __TARGET_LIB__ < 0x20000000
+#    define OS_CODE 4
+#  elif __TARGET_LIB__ < 0x40000000
+#    define OS_CODE 11
+#  else
+#    define OS_CODE 8
+#  endif
+#endif
+
+#if defined(ATARI) || defined(atarist)
+#  define OS_CODE  5
+#endif
+
+#ifdef OS2
+#  define OS_CODE  6
+#  if defined(M_I86) && !defined(Z_SOLO)
+#    include <malloc.h>
+#  endif
+#endif
+
+#if defined(MACOS) || defined(TARGET_OS_MAC)
+#  define OS_CODE  7
+#  ifndef Z_SOLO
+#    if defined(__MWERKS__) && __dest_os != __be_os && __dest_os != __win32_os
+#      include <unix.h> /* for fdopen */
+#    else
+#      ifndef fdopen
+#        define fdopen(fd,mode) NULL /* No fdopen() */
+#      endif
+#    endif
+#  endif
+#endif
+
+#ifdef __acorn
+#  define OS_CODE 13
+#endif
+
+#if defined(WIN32) && !defined(__CYGWIN__)
+#  define OS_CODE  10
+#endif
+
+#ifdef _BEOS_
+#  define OS_CODE  16
+#endif
+
+#ifdef __TOS_OS400__
+#  define OS_CODE 18
+#endif
+
+#ifdef __APPLE__
+#  define OS_CODE 19
+#endif
+
+#if defined(_BEOS_) || defined(RISCOS)
+#  define fdopen(fd,mode) NULL /* No fdopen() */
+#endif
+
+#if (defined(_MSC_VER) && (_MSC_VER > 600)) && !defined __INTERIX
+#  if defined(_WIN32_WCE)
+#    define fdopen(fd,mode) NULL /* No fdopen() */
+#    ifndef _PTRDIFF_T_DEFINED
+       typedef int ptrdiff_t;
+#      define _PTRDIFF_T_DEFINED
+#    endif
+#  else
+#    define fdopen(fd,type)  _fdopen(fd,type)
+#  endif
+#endif
+
+#if defined(__BORLANDC__) && !defined(MSDOS)
+  #pragma warn -8004
+  #pragma warn -8008
+  #pragma warn -8066
+#endif
+
+/* provide prototypes for these when building zlib without LFS */
+#if !defined(_WIN32) && \
+    (!defined(_LARGEFILE64_SOURCE) || _LFS64_LARGEFILE-0 == 0)
+    ZEXTERN uLong ZEXPORT adler32_combine64 OF((uLong, uLong, z_off_t));
+    ZEXTERN uLong ZEXPORT crc32_combine64 OF((uLong, uLong, z_off_t));
+#endif
+
+        /* common defaults */
+
+#ifndef OS_CODE
+#  define OS_CODE  3     /* assume Unix */
+#endif
+
+#ifndef F_OPEN
+#  define F_OPEN(name, mode) fopen((name), (mode))
+#endif
+
+         /* functions */
+
+#if defined(pyr) || defined(Z_SOLO)
+#  define NO_MEMCPY
+#endif
+#if defined(SMALL_MEDIUM) && !defined(_MSC_VER) && !defined(__SC__)
+ /* Use our own functions for small and medium model with MSC <= 5.0.
+  * You may have to use the same strategy for Borland C (untested).
+  * The __SC__ check is for Symantec.
+  */
+#  define NO_MEMCPY
+#endif
+#if defined(STDC) && !defined(HAVE_MEMCPY) && !defined(NO_MEMCPY)
+#  define HAVE_MEMCPY
+#endif
+#ifdef HAVE_MEMCPY
+#  ifdef SMALL_MEDIUM /* MSDOS small or medium model */
+#    define zmemcpy _fmemcpy
+#    define zmemcmp _fmemcmp
+#    define zmemzero(dest, len) _fmemset(dest, 0, len)
+#  else
+#    define zmemcpy memcpy
+#    define zmemcmp memcmp
+#    define zmemzero(dest, len) memset(dest, 0, len)
+#  endif
+#else
+   void ZLIB_INTERNAL zmemcpy OF((Bytef* dest, const Bytef* source, uInt len));
+   int ZLIB_INTERNAL zmemcmp OF((const Bytef* s1, const Bytef* s2, uInt len));
+   void ZLIB_INTERNAL zmemzero OF((Bytef* dest, uInt len));
+#endif
+
+/* Diagnostic functions */
+#ifdef ZLIB_DEBUG
+#  include <stdio.h>
+   extern int ZLIB_INTERNAL z_verbose;
+   extern void ZLIB_INTERNAL z_error OF((char *m));
+#  define Assert(cond,msg) {if(!(cond)) z_error(msg);}
+#  define Trace(x) {if (z_verbose>=0) fprintf x ;}
+#  define Tracev(x) {if (z_verbose>0) fprintf x ;}
+#  define Tracevv(x) {if (z_verbose>1) fprintf x ;}
+#  define Tracec(c,x) {if (z_verbose>0 && (c)) fprintf x ;}
+#  define Tracecv(c,x) {if (z_verbose>1 && (c)) fprintf x ;}
+#else
+#  define Assert(cond,msg)
+#  define Trace(x)
+#  define Tracev(x)
+#  define Tracevv(x)
+#  define Tracec(c,x)
+#  define Tracecv(c,x)
+#endif
+
+#ifndef Z_SOLO
+   voidpf ZLIB_INTERNAL zcalloc OF((voidpf opaque, unsigned items,
+                                    unsigned size));
+   void ZLIB_INTERNAL zcfree  OF((voidpf opaque, voidpf ptr));
+#endif
+
+#define ZALLOC(strm, items, size) \
+           (*((strm)->zalloc))((strm)->opaque, (items), (size))
+#define ZFREE(strm, addr)  (*((strm)->zfree))((strm)->opaque, (voidpf)(addr))
+#define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
+
+/* Reverse the bytes in a 32-bit value */
+#define ZSWAP32(q) ((((q) >> 24) & 0xff) + (((q) >> 8) & 0xff00) + \
+                    (((q) & 0xff00) << 8) + (((q) & 0xff) << 24))
+
+#endif /* ZUTIL_H */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/src/java.base/solaris/classes/sun/nio/ch/DefaultAsynchronousChannelProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,47 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+package sun.nio.ch;
+
+import java.nio.channels.spi.AsynchronousChannelProvider;
+
+/**
+ * Creates this platform's default AsynchronousChannelProvider
+ */
+
+public class DefaultAsynchronousChannelProvider {
+
+    /**
+     * Prevent instantiation.
+     */
+    private DefaultAsynchronousChannelProvider() { }
+
+    /**
+     * Returns the default AsynchronousChannelProvider.
+     */
+    public static AsynchronousChannelProvider create() {
+        return new SolarisAsynchronousChannelProvider();
+    }
+}
--- a/jdk/src/java.base/solaris/classes/sun/nio/ch/DefaultSelectorProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/solaris/classes/sun/nio/ch/DefaultSelectorProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -42,7 +42,6 @@
      * Returns the default SelectorProvider.
      */
     public static SelectorProvider create() {
-        return new sun.nio.ch.DevPollSelectorProvider();
+        return new DevPollSelectorProvider();
     }
-
 }
--- a/jdk/src/java.base/unix/classes/sun/nio/ch/DefaultAsynchronousChannelProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,75 +0,0 @@
-/*
- * Copyright (c) 2008, 2012, Oracle and/or its affiliates. All rights reserved.
- * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
- *
- * This code is free software; you can redistribute it and/or modify it
- * under the terms of the GNU General Public License version 2 only, as
- * published by the Free Software Foundation.  Oracle designates this
- * particular file as subject to the "Classpath" exception as provided
- * by Oracle in the LICENSE file that accompanied this code.
- *
- * This code is distributed in the hope that it will be useful, but WITHOUT
- * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
- * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
- * version 2 for more details (a copy is included in the LICENSE file that
- * accompanied this code).
- *
- * You should have received a copy of the GNU General Public License version
- * 2 along with this work; if not, write to the Free Software Foundation,
- * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
- *
- * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
- * or visit www.oracle.com if you need additional information or have any
- * questions.
- */
-
-package sun.nio.ch;
-
-import java.nio.channels.spi.AsynchronousChannelProvider;
-import sun.security.action.GetPropertyAction;
-
-/**
- * Creates this platform's default asynchronous channel provider
- */
-
-public class DefaultAsynchronousChannelProvider {
-
-    /**
-     * Prevent instantiation.
-     */
-    private DefaultAsynchronousChannelProvider() { }
-
-    @SuppressWarnings("unchecked")
-    private static AsynchronousChannelProvider createProvider(String cn) {
-        Class<AsynchronousChannelProvider> c;
-        try {
-            c = (Class<AsynchronousChannelProvider>)Class.forName(cn);
-        } catch (ClassNotFoundException x) {
-            throw new AssertionError(x);
-        }
-        try {
-            @SuppressWarnings("deprecation")
-            AsynchronousChannelProvider result = c.newInstance();
-            return result;
-        } catch (IllegalAccessException | InstantiationException x) {
-            throw new AssertionError(x);
-        }
-
-    }
-
-    /**
-     * Returns the default AsynchronousChannelProvider.
-     */
-    public static AsynchronousChannelProvider create() {
-        String osname = GetPropertyAction.privilegedGetProperty("os.name");
-        if (osname.equals("SunOS"))
-            return createProvider("sun.nio.ch.SolarisAsynchronousChannelProvider");
-        if (osname.equals("Linux"))
-            return createProvider("sun.nio.ch.LinuxAsynchronousChannelProvider");
-        if (osname.contains("OS X"))
-            return createProvider("sun.nio.ch.BsdAsynchronousChannelProvider");
-        if (osname.equals("AIX"))
-            return createProvider("sun.nio.ch.AixAsynchronousChannelProvider");
-        throw new InternalError("platform not recognized");
-    }
-}
--- a/jdk/src/java.base/unix/native/libnet/Inet4AddressImpl.c	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/unix/native/libnet/Inet4AddressImpl.c	Thu Mar 16 20:47:03 2017 +0000
@@ -46,7 +46,13 @@
 #define NI_MAXHOST 1025
 #endif
 
-/************************************************************************
+#define SET_NONBLOCKING(fd) {       \
+    int flags = fcntl(fd, F_GETFL); \
+    flags |= O_NONBLOCK;            \
+    fcntl(fd, F_SETFL, flags);      \
+}
+
+/*
  * Inet4AddressImpl
  */
 
@@ -57,35 +63,26 @@
  */
 JNIEXPORT jstring JNICALL
 Java_java_net_Inet4AddressImpl_getLocalHostName(JNIEnv *env, jobject this) {
-    char hostname[NI_MAXHOST+1];
+    char hostname[NI_MAXHOST + 1];
 
     hostname[0] = '\0';
-    if (gethostname(hostname, NI_MAXHOST)) {
-        /* Something went wrong, maybe networking is not setup? */
+    if (gethostname(hostname, NI_MAXHOST) != 0) {
         strcpy(hostname, "localhost");
     } else {
+        // try to resolve hostname via nameservice
+        // if it is known but getnameinfo fails, hostname will still be the
+        // value from gethostname
         struct addrinfo hints, *res;
-        int error;
 
+        // make sure string is null-terminated
         hostname[NI_MAXHOST] = '\0';
         memset(&hints, 0, sizeof(hints));
         hints.ai_flags = AI_CANONNAME;
         hints.ai_family = AF_INET;
 
-        error = getaddrinfo(hostname, NULL, &hints, &res);
-
-        if (error == 0) {/* host is known to name service */
-            getnameinfo(res->ai_addr,
-                        res->ai_addrlen,
-                        hostname,
-                        NI_MAXHOST,
-                        NULL,
-                        0,
-                        NI_NAMEREQD);
-
-            /* if getnameinfo fails hostname is still the value
-               from gethostname */
-
+        if (getaddrinfo(hostname, NULL, &hints, &res) == 0) {
+            getnameinfo(res->ai_addr, res->ai_addrlen, hostname, NI_MAXHOST,
+                        NULL, 0, NI_NAMEREQD);
             freeaddrinfo(res);
         }
     }
@@ -93,89 +90,70 @@
 }
 
 /*
- * Find an internet address for a given hostname.  Note that this
+ * Find an internet address for a given hostname. Note that this
  * code only works for addresses of type INET. The translation
  * of %d.%d.%d.%d to an address (int) occurs in java now, so the
- * String "host" shouldn't *ever* be a %d.%d.%d.%d string
+ * String "host" shouldn't be a %d.%d.%d.%d string. The only
+ * exception should be when any of the %d are out of range and
+ * we fallback to a lookup.
  *
  * Class:     java_net_Inet4AddressImpl
  * Method:    lookupAllHostAddr
  * Signature: (Ljava/lang/String;)[[B
  */
-
 JNIEXPORT jobjectArray JNICALL
 Java_java_net_Inet4AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
-                                                jstring host) {
+                                                 jstring host) {
+    jobjectArray ret = NULL;
     const char *hostname;
-    jobjectArray ret = 0;
-    int retLen = 0;
     int error = 0;
-    struct addrinfo hints, *res, *resNew = NULL;
+    struct addrinfo hints, *res = NULL, *resNew = NULL, *last = NULL,
+        *iterator;
 
     initInetAddressIDs(env);
     JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 
     if (IS_NULL(host)) {
-        JNU_ThrowNullPointerException(env, "host is null");
-        return 0;
+        JNU_ThrowNullPointerException(env, "host argument is null");
+        return NULL;
     }
     hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);
     CHECK_NULL_RETURN(hostname, NULL);
 
-    /* Try once, with our static buffer. */
+    // try once, with our static buffer
     memset(&hints, 0, sizeof(hints));
     hints.ai_flags = AI_CANONNAME;
     hints.ai_family = AF_INET;
 
-#ifdef __solaris__
-    /*
-     * Workaround for Solaris bug 4160367 - if a hostname contains a
-     * white space then 0.0.0.0 is returned
-     */
-    if (isspace((unsigned char)hostname[0])) {
-        JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException",
-                        (char *)hostname);
-        JNU_ReleaseStringPlatformChars(env, host, hostname);
-        return NULL;
-    }
-#endif
-
     error = getaddrinfo(hostname, NULL, &hints, &res);
 
-#ifdef MACOSX
     if (error) {
+#if defined(MACOSX)
         // If getaddrinfo fails try getifaddrs, see bug 8170910.
         ret = lookupIfLocalhost(env, hostname, JNI_FALSE);
         if (ret != NULL || (*env)->ExceptionCheck(env)) {
-            JNU_ReleaseStringPlatformChars(env, host, hostname);
-            return ret;
+            goto cleanupAndReturn;
         }
-    }
 #endif
-
-    if (error) {
-        /* report error */
+        // report error
         NET_ThrowUnknownHostExceptionWithGaiError(env, hostname, error);
-        JNU_ReleaseStringPlatformChars(env, host, hostname);
-        return NULL;
+        goto cleanupAndReturn;
     } else {
         int i = 0;
-        struct addrinfo *itr, *last = NULL, *iterator = res;
-
+        iterator = res;
         while (iterator != NULL) {
-            // remove the duplicate one
+            // skip duplicates
             int skip = 0;
-            itr = resNew;
-            while (itr != NULL) {
+            struct addrinfo *iteratorNew = resNew;
+            while (iteratorNew != NULL) {
                 struct sockaddr_in *addr1, *addr2;
                 addr1 = (struct sockaddr_in *)iterator->ai_addr;
-                addr2 = (struct sockaddr_in *)itr->ai_addr;
-                if (addr1->sin_addr.s_addr ==
-                    addr2->sin_addr.s_addr) {
+                addr2 = (struct sockaddr_in *)iteratorNew->ai_addr;
+                if (addr1->sin_addr.s_addr == addr2->sin_addr.s_addr) {
                     skip = 1;
                     break;
                 }
-                itr = itr->ai_next;
+                iteratorNew = iteratorNew->ai_next;
             }
 
             if (!skip) {
@@ -199,44 +177,37 @@
             iterator = iterator->ai_next;
         }
 
-        retLen = i;
-        iterator = resNew;
-
-        ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);
-
+        // allocate array - at this point i contains the number of addresses
+        ret = (*env)->NewObjectArray(env, i, ia_class, NULL);
         if (IS_NULL(ret)) {
-            /* we may have memory to free at the end of this */
             goto cleanupAndReturn;
         }
 
         i = 0;
+        iterator = resNew;
         while (iterator != NULL) {
             jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
             if (IS_NULL(iaObj)) {
                 ret = NULL;
                 goto cleanupAndReturn;
             }
-            setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in*)iterator->ai_addr)->sin_addr.s_addr));
+            setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in *)
+                                (iterator->ai_addr))->sin_addr.s_addr));
             setInetAddress_hostName(env, iaObj, host);
             (*env)->SetObjectArrayElement(env, ret, i++, iaObj);
             iterator = iterator->ai_next;
         }
     }
-
 cleanupAndReturn:
-    {
-        struct addrinfo *iterator, *tmp;
-        iterator = resNew;
-        while (iterator != NULL) {
-            tmp = iterator;
-            iterator = iterator->ai_next;
-            free(tmp);
-        }
-        JNU_ReleaseStringPlatformChars(env, host, hostname);
+    JNU_ReleaseStringPlatformChars(env, host, hostname);
+    while (resNew != NULL) {
+        last = resNew;
+        resNew = resNew->ai_next;
+        free(last);
     }
-
-    freeaddrinfo(res);
-
+    if (res != NULL) {
+        freeaddrinfo(res);
+    }
     return ret;
 }
 
@@ -244,164 +215,243 @@
  * Class:     java_net_Inet4AddressImpl
  * Method:    getHostByAddr
  * Signature: (I)Ljava/lang/String;
+ *
+ * Theoretically the UnknownHostException could be enriched with gai error
+ * information. But as it is silently ignored anyway, there's no need for this.
+ * It's only important that either a valid hostname is returned or an
+ * UnknownHostException is thrown.
  */
 JNIEXPORT jstring JNICALL
 Java_java_net_Inet4AddressImpl_getHostByAddr(JNIEnv *env, jobject this,
-                                            jbyteArray addrArray) {
+                                             jbyteArray addrArray) {
     jstring ret = NULL;
+    char host[NI_MAXHOST + 1];
+    jbyte caddr[4];
+    jint addr;
+    struct sockaddr_in sa;
 
-    char host[NI_MAXHOST+1];
-    int error = 0;
-    int len = 0;
-    jbyte caddr[4];
-
-    struct sockaddr_in him4;
-    struct sockaddr *sa;
-
-    jint addr;
+    // construct a sockaddr_in structure
+    memset((char *)&sa, 0, sizeof(struct sockaddr_in));
     (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
-    addr = ((caddr[0]<<24) & 0xff000000);
-    addr |= ((caddr[1] <<16) & 0xff0000);
-    addr |= ((caddr[2] <<8) & 0xff00);
+    addr = ((caddr[0] << 24) & 0xff000000);
+    addr |= ((caddr[1] << 16) & 0xff0000);
+    addr |= ((caddr[2] << 8) & 0xff00);
     addr |= (caddr[3] & 0xff);
-    memset((void *) &him4, 0, sizeof(him4));
-    him4.sin_addr.s_addr = htonl(addr);
-    him4.sin_family = AF_INET;
-    sa = (struct sockaddr *) &him4;
-    len = sizeof(him4);
+    sa.sin_addr.s_addr = htonl(addr);
+    sa.sin_family = AF_INET;
 
-    error = getnameinfo(sa, len, host, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
-
-    if (!error) {
+    if (getnameinfo((struct sockaddr *)&sa, sizeof(struct sockaddr_in),
+                    host, NI_MAXHOST, NULL, 0, NI_NAMEREQD)) {
+        JNU_ThrowByName(env, "java/net/UnknownHostException", NULL);
+    } else {
         ret = (*env)->NewStringUTF(env, host);
-    }
-
-    if (ret == NULL) {
-        JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", NULL);
+        if (ret == NULL) {
+            JNU_ThrowByName(env, "java/net/UnknownHostException", NULL);
+        }
     }
 
     return ret;
 }
 
-#define SET_NONBLOCKING(fd) {           \
-        int flags = fcntl(fd, F_GETFL); \
-        flags |= O_NONBLOCK;            \
-        fcntl(fd, F_SETFL, flags);      \
+/**
+ * ping implementation using tcp port 7 (echo)
+ */
+static jboolean
+tcp_ping4(JNIEnv *env, SOCKETADDRESS *sa, SOCKETADDRESS *netif, jint timeout,
+          jint ttl)
+{
+    jint fd;
+    int connect_rv = -1;
+
+    // open a TCP socket
+    fd = socket(AF_INET, SOCK_STREAM, 0);
+    if (fd == -1) {
+        // note: if you run out of fds, you may not be able to load
+        // the exception class, and get a NoClassDefFoundError instead.
+        NET_ThrowNew(env, errno, "Can't create socket");
+        return JNI_FALSE;
+    }
+
+    // set TTL
+    if (ttl > 0) {
+        setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
+    }
+
+    // A network interface was specified, so let's bind to it.
+    if (netif != NULL) {
+        if (bind(fd, &netif->sa, sizeof(struct sockaddr_in)) < 0) {
+            NET_ThrowNew(env, errno, "Can't bind socket");
+            close(fd);
+            return JNI_FALSE;
+        }
+    }
+
+    // Make the socket non blocking so we can use select/poll.
+    SET_NONBLOCKING(fd);
+
+    sa->sa4.sin_port = htons(7); // echo port
+    connect_rv = NET_Connect(fd, &sa->sa, sizeof(struct sockaddr_in));
+
+    // connection established or refused immediately, either way it means
+    // we were able to reach the host!
+    if (connect_rv == 0 || errno == ECONNREFUSED) {
+        close(fd);
+        return JNI_TRUE;
+    }
+
+    switch (errno) {
+    case ENETUNREACH:   // Network Unreachable
+    case EAFNOSUPPORT:  // Address Family not supported
+    case EADDRNOTAVAIL: // address is not available on the remote machine
+#if defined(__linux__) || defined(_AIX)
+        // On some Linux versions, when a socket is bound to the loopback
+        // interface, connect will fail and errno will be set to EINVAL
+        // or EHOSTUNREACH.  When that happens, don't throw an exception,
+        // just return false.
+    case EINVAL:
+    case EHOSTUNREACH:  // No route to host
+#endif
+        close(fd);
+        return JNI_FALSE;
+    case EINPROGRESS:   // this is expected as we'll probably have to wait
+        break;
+    default:
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
+                                     "connect failed");
+        close(fd);
+        return JNI_FALSE;
+    }
+
+    timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
+    if (timeout >= 0) {
+        // connection has been established, check for error condition
+        socklen_t optlen = (socklen_t)sizeof(connect_rv);
+        if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
+                       &optlen) <0)
+        {
+            connect_rv = errno;
+        }
+        if (connect_rv == 0 || connect_rv == ECONNREFUSED) {
+            close(fd);
+            return JNI_TRUE;
+        }
+    }
+    close(fd);
+    return JNI_FALSE;
 }
 
 /**
  * ping implementation.
- * Send a ICMP_ECHO_REQUEST packet every second until either the timeout
- * expires or a answer is received.
- * Returns true is an ECHO_REPLY is received, otherwise, false.
+ * Send an ICMP_ECHO_REQUEST packet every second until either the timeout
+ * expires or an answer is received.
+ * Returns true if an ECHO_REPLY is received, false otherwise.
  */
 static jboolean
-ping4(JNIEnv *env, jint fd, struct sockaddr_in* him, jint timeout,
-      struct sockaddr_in* netif, jint ttl) {
-    jint size;
-    jint n, hlen1, icmplen;
+ping4(JNIEnv *env, jint fd, SOCKETADDRESS *sa, SOCKETADDRESS *netif,
+      jint timeout, jint ttl)
+{
+    jint n, size = 60 * 1024, hlen, tmout2, seq = 1;
     socklen_t len;
-    char sendbuf[1500];
-    char recvbuf[1500];
+    unsigned char sendbuf[1500], recvbuf[1500];
     struct icmp *icmp;
     struct ip *ip;
     struct sockaddr_in sa_recv;
     jchar pid;
-    jint tmout2, seq = 1;
     struct timeval tv;
-    size_t plen;
+    size_t plen = ICMP_ADVLENMIN + sizeof(tv);
 
-    /* icmp_id is a 16 bit data type, therefore down cast the pid */
-    pid = (jchar)getpid();
-    size = 60*1024;
     setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
-    /*
-     * sets the ttl (max number of hops)
-     */
+
+    // sets the ttl (max number of hops)
     if (ttl > 0) {
-      setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
+        setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
     }
-    /*
-     * a specific interface was specified, so let's bind the socket
-     * to that interface to ensure the requests are sent only through it.
-     */
+
+    // a specific interface was specified, so let's bind the socket
+    // to that interface to ensure the requests are sent only through it.
     if (netif != NULL) {
-      if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in)) < 0) {
-        NET_ThrowNew(env, errno, "Can't bind socket");
-        close(fd);
-        return JNI_FALSE;
-      }
+        if (bind(fd, &netif->sa, sizeof(struct sockaddr_in)) < 0) {
+            NET_ThrowNew(env, errno, "Can't bind socket");
+            close(fd);
+            return JNI_FALSE;
+        }
     }
-    /*
-     * Make the socket non blocking so we can use select
-     */
+
+    // icmp_id is a 16 bit data type, therefore down cast the pid
+    pid = (jchar)getpid();
+
+    // Make the socket non blocking so we can use select
     SET_NONBLOCKING(fd);
     do {
-      /*
-       * create the ICMP request
-       */
-      icmp = (struct icmp *) sendbuf;
-      icmp->icmp_type = ICMP_ECHO;
-      icmp->icmp_code = 0;
-      icmp->icmp_id = htons(pid);
-      icmp->icmp_seq = htons(seq);
-      seq++;
-      gettimeofday(&tv, NULL);
-      memcpy(icmp->icmp_data, &tv, sizeof(tv));
-      plen = ICMP_ADVLENMIN + sizeof(tv);
-      icmp->icmp_cksum = 0;
-      icmp->icmp_cksum = in_cksum((u_short *)icmp, plen);
-      /*
-       * send it
-       */
-      n = sendto(fd, sendbuf, plen, 0, (struct sockaddr *)him,
-                 sizeof(struct sockaddr));
-      if (n < 0 && errno != EINPROGRESS ) {
-#ifdef __linux__
-        if (errno != EINVAL && errno != EHOSTUNREACH)
-          /*
-           * On some Linux versions, when a socket is bound to the loopback
-           * interface, sendto will fail and errno will be set to
-           * EINVAL or EHOSTUNREACH. When that happens, don't throw an
-           * exception, just return false.
-           */
-#endif /*__linux__ */
-          NET_ThrowNew(env, errno, "Can't send ICMP packet");
-        close(fd);
-        return JNI_FALSE;
-      }
+        // create the ICMP request
+        icmp = (struct icmp *)sendbuf;
+        icmp->icmp_type = ICMP_ECHO;
+        icmp->icmp_code = 0;
+        // let's tag the ECHO packet with our pid so we can identify it
+        icmp->icmp_id = htons(pid);
+        icmp->icmp_seq = htons(seq);
+        seq++;
+        gettimeofday(&tv, NULL);
+        memcpy(icmp->icmp_data, &tv, sizeof(tv));
+        icmp->icmp_cksum = 0;
+        // manually calculate checksum
+        icmp->icmp_cksum = in_cksum((u_short *)icmp, plen);
+        // send it
+        n = sendto(fd, sendbuf, plen, 0, &sa->sa, sizeof(struct sockaddr_in));
+        if (n < 0 && errno != EINPROGRESS) {
+#if defined(__linux__)
+            /*
+             * On some Linux versions, when a socket is bound to the loopback
+             * interface, sendto will fail and errno will be set to
+             * EINVAL or EHOSTUNREACH. When that happens, don't throw an
+             * exception, just return false.
+             */
+            if (errno != EINVAL && errno != EHOSTUNREACH) {
+                NET_ThrowNew(env, errno, "Can't send ICMP packet");
+            }
+#else
+            NET_ThrowNew(env, errno, "Can't send ICMP packet");
+#endif
+            close(fd);
+            return JNI_FALSE;
+        }
 
-      tmout2 = timeout > 1000 ? 1000 : timeout;
-      do {
-        tmout2 = NET_Wait(env, fd, NET_WAIT_READ, tmout2);
-        if (tmout2 >= 0) {
-          len = sizeof(sa_recv);
-          n = recvfrom(fd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr *)&sa_recv, &len);
-          ip = (struct ip*) recvbuf;
-          hlen1 = (ip->ip_hl) << 2;
-          icmp = (struct icmp *) (recvbuf + hlen1);
-          icmplen = n - hlen1;
-          /*
-           * We did receive something, but is it what we were expecting?
-           * I.E.: A ICMP_ECHOREPLY packet with the proper PID.
-           */
-          if (icmplen >= 8 && icmp->icmp_type == ICMP_ECHOREPLY
-               && (ntohs(icmp->icmp_id) == pid)) {
-            if ((him->sin_addr.s_addr == sa_recv.sin_addr.s_addr)) {
-              close(fd);
-              return JNI_TRUE;
+        tmout2 = timeout > 1000 ? 1000 : timeout;
+        do {
+            tmout2 = NET_Wait(env, fd, NET_WAIT_READ, tmout2);
+            if (tmout2 >= 0) {
+                len = sizeof(sa_recv);
+                n = recvfrom(fd, recvbuf, sizeof(recvbuf), 0,
+                             (struct sockaddr *)&sa_recv, &len);
+                // check if we received enough data
+                if (n < (jint)sizeof(struct ip)) {
+                    continue;
+                }
+                ip = (struct ip *)recvbuf;
+                hlen = ((jint)(unsigned int)(ip->ip_hl)) << 2;
+                // check if we received enough data
+                if (n < (jint)(hlen + sizeof(struct icmp))) {
+                    continue;
+                }
+                icmp = (struct icmp *)(recvbuf + hlen);
+                // We did receive something, but is it what we were expecting?
+                // I.E.: An ICMP_ECHO_REPLY packet with the proper PID and
+                //       from the host that we are trying to determine is reachable.
+                if (icmp->icmp_type == ICMP_ECHOREPLY &&
+                    (ntohs(icmp->icmp_id) == pid))
+                {
+                    if (sa->sa4.sin_addr.s_addr == sa_recv.sin_addr.s_addr) {
+                        close(fd);
+                        return JNI_TRUE;
+                    } else if (sa->sa4.sin_addr.s_addr == 0) {
+                        close(fd);
+                        return JNI_TRUE;
+                    }
+                }
             }
-
-            if (him->sin_addr.s_addr == 0) {
-              close(fd);
-              return JNI_TRUE;
-            }
-         }
-
-        }
-      } while (tmout2 > 0);
-      timeout -= 1000;
-    } while (timeout >0);
+        } while (tmout2 > 0);
+        timeout -= 1000;
+    } while (timeout > 0);
     close(fd);
     return JNI_FALSE;
 }
@@ -413,149 +463,51 @@
  */
 JNIEXPORT jboolean JNICALL
 Java_java_net_Inet4AddressImpl_isReachable0(JNIEnv *env, jobject this,
-                                           jbyteArray addrArray,
-                                           jint timeout,
-                                           jbyteArray ifArray,
-                                           jint ttl) {
-    jint addr;
+                                            jbyteArray addrArray, jint timeout,
+                                            jbyteArray ifArray, jint ttl)
+{
     jbyte caddr[4];
-    jint fd;
-    struct sockaddr_in him;
-    struct sockaddr_in* netif = NULL;
-    struct sockaddr_in inf;
-    int len = 0;
-    int connect_rv = -1;
-    int sz;
+    jint addr = 0, sz, fd;
+    SOCKETADDRESS sa, inf, *netif = NULL;
 
-    memset((char *) caddr, 0, sizeof(caddr));
-    memset((char *) &him, 0, sizeof(him));
-    memset((char *) &inf, 0, sizeof(inf));
+    // check if address array size is 4 (IPv4 address)
     sz = (*env)->GetArrayLength(env, addrArray);
     if (sz != 4) {
       return JNI_FALSE;
     }
+
+    // convert IP address from byte array to integer
+    memset((char *)caddr, 0, sizeof(caddr));
     (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
-    addr = ((caddr[0]<<24) & 0xff000000);
-    addr |= ((caddr[1] <<16) & 0xff0000);
-    addr |= ((caddr[2] <<8) & 0xff00);
+    addr = ((caddr[0] << 24) & 0xff000000);
+    addr |= ((caddr[1] << 16) & 0xff0000);
+    addr |= ((caddr[2] << 8) & 0xff00);
     addr |= (caddr[3] & 0xff);
-    addr = htonl(addr);
-    him.sin_addr.s_addr = addr;
-    him.sin_family = AF_INET;
-    len = sizeof(him);
-    /*
-     * If a network interface was specified, let's create the address
-     * for it.
-     */
-    if (!(IS_NULL(ifArray))) {
-      memset((char *) caddr, 0, sizeof(caddr));
-      (*env)->GetByteArrayRegion(env, ifArray, 0, 4, caddr);
-      addr = ((caddr[0]<<24) & 0xff000000);
-      addr |= ((caddr[1] <<16) & 0xff0000);
-      addr |= ((caddr[2] <<8) & 0xff00);
-      addr |= (caddr[3] & 0xff);
-      addr = htonl(addr);
-      inf.sin_addr.s_addr = addr;
-      inf.sin_family = AF_INET;
-      inf.sin_port = 0;
-      netif = &inf;
-    }
+    memset((char *)&sa, 0, sizeof(SOCKETADDRESS));
+    sa.sa4.sin_addr.s_addr = htonl(addr);
+    sa.sa4.sin_family = AF_INET;
 
-    /*
-     * Let's try to create a RAW socket to send ICMP packets
-     * This usually requires "root" privileges, so it's likely to fail.
-     */
-    fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
-    if (fd != -1) {
-      /*
-       * It didn't fail, so we can use ICMP_ECHO requests.
-       */
-      return ping4(env, fd, &him, timeout, netif, ttl);
-    }
-
-    /*
-     * Can't create a raw socket, so let's try a TCP socket
-     */
-    fd = socket(AF_INET, SOCK_STREAM, 0);
-    if (fd == -1) {
-        /* note: if you run out of fds, you may not be able to load
-         * the exception class, and get a NoClassDefFoundError
-         * instead.
-         */
-        NET_ThrowNew(env, errno, "Can't create socket");
-        return JNI_FALSE;
-    }
-    if (ttl > 0) {
-      setsockopt(fd, IPPROTO_IP, IP_TTL, &ttl, sizeof(ttl));
+    // If a network interface was specified, let's convert its address as well.
+    if (!(IS_NULL(ifArray))) {
+        memset((char *)caddr, 0, sizeof(caddr));
+        (*env)->GetByteArrayRegion(env, ifArray, 0, 4, caddr);
+        addr = ((caddr[0] << 24) & 0xff000000);
+        addr |= ((caddr[1] << 16) & 0xff0000);
+        addr |= ((caddr[2] << 8) & 0xff00);
+        addr |= (caddr[3] & 0xff);
+        memset((char *)&inf, 0, sizeof(SOCKETADDRESS));
+        inf.sa4.sin_addr.s_addr = htonl(addr);
+        inf.sa4.sin_family = AF_INET;
+        netif = &inf;
     }
 
-    /*
-     * A network interface was specified, so let's bind to it.
-     */
-    if (netif != NULL) {
-      if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in)) < 0) {
-        NET_ThrowNew(env, errno, "Can't bind socket");
-        close(fd);
-        return JNI_FALSE;
-      }
-    }
-
-    /*
-     * Make the socket non blocking so we can use select/poll.
-     */
-    SET_NONBLOCKING(fd);
-
-    him.sin_port = htons(7);    /* Echo */
-    connect_rv = NET_Connect(fd, (struct sockaddr *)&him, len);
-
-    /**
-     * connection established or refused immediately, either way it means
-     * we were able to reach the host!
-     */
-    if (connect_rv == 0 || errno == ECONNREFUSED) {
-        close(fd);
-        return JNI_TRUE;
+    // Let's try to create a RAW socket to send ICMP packets.
+    // This usually requires "root" privileges, so it's likely to fail.
+    fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
+    if (fd == -1) {
+        return tcp_ping4(env, &sa, netif, timeout, ttl);
     } else {
-        socklen_t optlen = (socklen_t)sizeof(connect_rv);
-
-        switch (errno) {
-        case ENETUNREACH: /* Network Unreachable */
-        case EAFNOSUPPORT: /* Address Family not supported */
-        case EADDRNOTAVAIL: /* address is not available on  the  remote machine */
-#if defined(__linux__) || defined(_AIX)
-        case EINVAL:
-        case EHOSTUNREACH: /* No route to host */
-          /*
-           * On some Linux versions, when a socket is bound to the loopback
-           * interface, connect will fail and errno will be set to EINVAL
-           * or EHOSTUNREACH.  When that happens, don't throw an exception,
-           * just return false.
-           */
-#endif /* __linux__ */
-          close(fd);
-          return JNI_FALSE;
-        }
-
-        if (errno != EINPROGRESS) {
-          NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
-                                       "connect failed");
-          close(fd);
-          return JNI_FALSE;
-        }
-
-        timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
-        if (timeout >= 0) {
-          /* has connection been established? */
-          if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
-                         &optlen) <0) {
-            connect_rv = errno;
-          }
-          if (connect_rv == 0 || connect_rv == ECONNREFUSED) {
-            close(fd);
-            return JNI_TRUE;
-          }
-        }
-        close(fd);
-        return JNI_FALSE;
+        // It didn't fail, so we can use ICMP_ECHO requests.
+        return ping4(env, fd, &sa, netif, timeout, ttl);
     }
 }
--- a/jdk/src/java.base/unix/native/libnet/Inet6AddressImpl.c	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/unix/native/libnet/Inet6AddressImpl.c	Thu Mar 16 20:47:03 2017 +0000
@@ -38,17 +38,22 @@
 
 #include "net_util.h"
 
+#include "java_net_InetAddress.h"
 #include "java_net_Inet4AddressImpl.h"
 #include "java_net_Inet6AddressImpl.h"
-#include "java_net_InetAddress.h"
 
 /* the initial size of our hostent buffers */
 #ifndef NI_MAXHOST
 #define NI_MAXHOST 1025
 #endif
 
+#define SET_NONBLOCKING(fd) {       \
+    int flags = fcntl(fd, F_GETFL); \
+    flags |= O_NONBLOCK;            \
+    fcntl(fd, F_SETFL, flags);      \
+}
 
-/************************************************************************
+/*
  * Inet6AddressImpl
  */
 
@@ -59,58 +64,40 @@
  */
 JNIEXPORT jstring JNICALL
 Java_java_net_Inet6AddressImpl_getLocalHostName(JNIEnv *env, jobject this) {
-    int ret;
-    char hostname[NI_MAXHOST+1];
+    char hostname[NI_MAXHOST + 1];
 
     hostname[0] = '\0';
-    ret = gethostname(hostname, NI_MAXHOST);
-    if (ret == -1) {
-        /* Something went wrong, maybe networking is not setup? */
+    if (gethostname(hostname, NI_MAXHOST) != 0) {
         strcpy(hostname, "localhost");
-    } else {
-        // ensure null-terminated
-        hostname[NI_MAXHOST] = '\0';
-    }
-
 #if defined(__solaris__)
-    if (ret == 0) {
-        /* Solaris doesn't want to give us a fully qualified domain name.
-         * We do a reverse lookup to try and get one.  This works
-         * if DNS occurs before NIS in /etc/resolv.conf, but fails
-         * if NIS comes first (it still gets only a partial name).
-         * We use thread-safe system calls.
-         */
-        struct addrinfo  hints, *res;
-        int error;
+    } else {
+        // try to resolve hostname via nameservice
+        // if it is known but getnameinfo fails, hostname will still be the
+        // value from gethostname
+        struct addrinfo hints, *res;
 
+        // make sure string is null-terminated
+        hostname[NI_MAXHOST] = '\0';
         memset(&hints, 0, sizeof(hints));
         hints.ai_flags = AI_CANONNAME;
         hints.ai_family = AF_UNSPEC;
 
-        error = getaddrinfo(hostname, NULL, &hints, &res);
-
-        if (error == 0) {
-            /* host is known to name service */
-            error = getnameinfo(res->ai_addr,
-                                res->ai_addrlen,
-                                hostname,
-                                NI_MAXHOST,
-                                NULL,
-                                0,
-                                NI_NAMEREQD);
-
-            /* if getnameinfo fails hostname is still the value
-               from gethostname */
-
+        if (getaddrinfo(hostname, NULL, &hints, &res) == 0) {
+            getnameinfo(res->ai_addr, res->ai_addrlen, hostname, NI_MAXHOST,
+                        NULL, 0, NI_NAMEREQD);
             freeaddrinfo(res);
         }
     }
+#else
+    } else {
+        // make sure string is null-terminated
+        hostname[NI_MAXHOST] = '\0';
+    }
 #endif
-
     return (*env)->NewStringUTF(env, hostname);
 }
 
-#ifdef MACOSX
+#if defined(MACOSX)
 /* also called from Inet4AddressImpl.c */
 __private_extern__ jobjectArray
 lookupIfLocalhost(JNIEnv *env, const char *hostname, jboolean includeV6)
@@ -163,7 +150,7 @@
     struct ifaddrs *iter = ifa;
     while (iter) {
         int family = iter->ifa_addr->sa_family;
-        if (iter->ifa_name[0] != '\0'  &&  iter->ifa_addr)
+        if (iter->ifa_name[0] != '\0' && iter->ifa_addr)
         {
             jboolean isLoopback = iter->ifa_flags & IFF_LOOPBACK;
             if (family == AF_INET) {
@@ -172,9 +159,7 @@
             } else if (family == AF_INET6 && includeV6) {
                 addrs6++;
                 if (isLoopback) numV6Loopbacks++;
-            } else {
-                /* We don't care e.g. AF_LINK */
-            }
+            } // else we don't care, e.g. AF_LINK
         }
         iter = iter->ifa_next;
     }
@@ -205,9 +190,9 @@
         jboolean isLoopback = iter->ifa_flags & IFF_LOOPBACK;
         int family = iter->ifa_addr->sa_family;
 
-        if (iter->ifa_name[0] != '\0'  &&  iter->ifa_addr
-            && (family == AF_INET || (family == AF_INET6 && includeV6))
-            && (!isLoopback || includeLoopback))
+        if (iter->ifa_name[0] != '\0' && iter->ifa_addr &&
+            (family == AF_INET || (family == AF_INET6 && includeV6)) &&
+            (!isLoopback || includeLoopback))
         {
             int port;
             int index = (family == AF_INET) ? i++ : j++;
@@ -234,93 +219,65 @@
 #endif
 
 /*
- * Find an internet address for a given hostname.  Note that this
- * code only works for addresses of type INET. The translation
- * of %d.%d.%d.%d to an address (int) occurs in java now, so the
- * String "host" shouldn't *ever* be a %d.%d.%d.%d string
- *
  * Class:     java_net_Inet6AddressImpl
  * Method:    lookupAllHostAddr
  * Signature: (Ljava/lang/String;)[[B
  */
-
 JNIEXPORT jobjectArray JNICALL
 Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
-                                                jstring host) {
+                                                 jstring host) {
+    jobjectArray ret = NULL;
     const char *hostname;
-    jobjectArray ret = 0;
-    int retLen = 0;
-
-    int getaddrinfo_error=0;
-    struct addrinfo hints, *res, *resNew = NULL;
+    int error = 0;
+    struct addrinfo hints, *res = NULL, *resNew = NULL, *last = NULL,
+        *iterator;
 
     initInetAddressIDs(env);
     JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 
     if (IS_NULL(host)) {
-        JNU_ThrowNullPointerException(env, "host is null");
-        return 0;
+        JNU_ThrowNullPointerException(env, "host argument is null");
+        return NULL;
     }
     hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);
     CHECK_NULL_RETURN(hostname, NULL);
 
-    /* Try once, with our static buffer. */
+    // try once, with our static buffer
     memset(&hints, 0, sizeof(hints));
     hints.ai_flags = AI_CANONNAME;
     hints.ai_family = AF_UNSPEC;
 
-#ifdef __solaris__
-    /*
-     * Workaround for Solaris bug 4160367 - if a hostname contains a
-     * white space then 0.0.0.0 is returned
-     */
-    if (isspace((unsigned char)hostname[0])) {
-        JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException",
-                        hostname);
-        JNU_ReleaseStringPlatformChars(env, host, hostname);
-        return NULL;
-    }
-#endif
+    error = getaddrinfo(hostname, NULL, &hints, &res);
 
-    getaddrinfo_error = getaddrinfo(hostname, NULL, &hints, &res);
-
-#ifdef MACOSX
-    if (getaddrinfo_error) {
-        /*
-         * If getaddrinfo fails looking up the local machine, attempt to get the
-         * address from getifaddrs. This ensures we get an IPv6 address for the
-         * local machine.
-         */
+    if (error) {
+#if defined(MACOSX)
+        // if getaddrinfo fails try getifaddrs
         ret = lookupIfLocalhost(env, hostname, JNI_TRUE);
         if (ret != NULL || (*env)->ExceptionCheck(env)) {
-            JNU_ReleaseStringPlatformChars(env, host, hostname);
-            return ret;
+            goto cleanupAndReturn;
         }
-    }
 #endif
-
-    if (getaddrinfo_error) {
-        /* report error */
-        NET_ThrowUnknownHostExceptionWithGaiError(
-            env, hostname, getaddrinfo_error);
-        JNU_ReleaseStringPlatformChars(env, host, hostname);
-        return NULL;
+        // report error
+        NET_ThrowUnknownHostExceptionWithGaiError(env, hostname, error);
+        goto cleanupAndReturn;
     } else {
-        int i = 0, addressPreference = -1;
-        int inetCount = 0, inet6Count = 0, inetIndex = 0, inet6Index = 0, originalIndex = 0;
-        struct addrinfo *itr, *last = NULL, *iterator = res;
+        int i = 0, inetCount = 0, inet6Count = 0, inetIndex = 0,
+            inet6Index = 0, originalIndex = 0;
+        int addressPreference =
+            (*env)->GetStaticIntField(env, ia_class, ia_preferIPv6AddressID);;
+        iterator = res;
         while (iterator != NULL) {
+            // skip duplicates
             int skip = 0;
-            itr = resNew;
-            while (itr != NULL) {
-                if (iterator->ai_family == itr->ai_family &&
-                    iterator->ai_addrlen == itr->ai_addrlen) {
-                    if (itr->ai_family == AF_INET) { /* AF_INET */
+            struct addrinfo *iteratorNew = resNew;
+            while (iteratorNew != NULL) {
+                if (iterator->ai_family == iteratorNew->ai_family &&
+                    iterator->ai_addrlen == iteratorNew->ai_addrlen) {
+                    if (iteratorNew->ai_family == AF_INET) { /* AF_INET */
                         struct sockaddr_in *addr1, *addr2;
                         addr1 = (struct sockaddr_in *)iterator->ai_addr;
-                        addr2 = (struct sockaddr_in *)itr->ai_addr;
-                        if (addr1->sin_addr.s_addr ==
-                            addr2->sin_addr.s_addr) {
+                        addr2 = (struct sockaddr_in *)iteratorNew->ai_addr;
+                        if (addr1->sin_addr.s_addr == addr2->sin_addr.s_addr) {
                             skip = 1;
                             break;
                         }
@@ -328,7 +285,7 @@
                         int t;
                         struct sockaddr_in6 *addr1, *addr2;
                         addr1 = (struct sockaddr_in6 *)iterator->ai_addr;
-                        addr2 = (struct sockaddr_in6 *)itr->ai_addr;
+                        addr2 = (struct sockaddr_in6 *)iteratorNew->ai_addr;
 
                         for (t = 0; t < 16; t++) {
                             if (addr1->sin6_addr.s6_addr[t] !=
@@ -337,7 +294,7 @@
                             }
                         }
                         if (t < 16) {
-                            itr = itr->ai_next;
+                            iteratorNew = iteratorNew->ai_next;
                             continue;
                         } else {
                             skip = 1;
@@ -346,16 +303,16 @@
                     }
                 } else if (iterator->ai_family != AF_INET &&
                            iterator->ai_family != AF_INET6) {
-                    /* we can't handle other family types */
+                    // we can't handle other family types
                     skip = 1;
                     break;
                 }
-                itr = itr->ai_next;
+                iteratorNew = iteratorNew->ai_next;
             }
 
             if (!skip) {
                 struct addrinfo *next
-                    = (struct addrinfo*) malloc(sizeof(struct addrinfo));
+                    = (struct addrinfo *)malloc(sizeof(struct addrinfo));
                 if (!next) {
                     JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed");
                     ret = NULL;
@@ -371,39 +328,33 @@
                 last = next;
                 i++;
                 if (iterator->ai_family == AF_INET) {
-                    inetCount ++;
+                    inetCount++;
                 } else if (iterator->ai_family == AF_INET6) {
-                    inet6Count ++;
+                    inet6Count++;
                 }
             }
             iterator = iterator->ai_next;
         }
-        retLen = i;
-        iterator = resNew;
 
-        ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);
-
+        // allocate array - at this point i contains the number of addresses
+        ret = (*env)->NewObjectArray(env, i, ia_class, NULL);
         if (IS_NULL(ret)) {
             /* we may have memory to free at the end of this */
             goto cleanupAndReturn;
         }
 
-        addressPreference = (*env)->GetStaticIntField(env, ia_class, ia_preferIPv6AddressID);
-
         if (addressPreference == java_net_InetAddress_PREFER_IPV6_VALUE) {
-            /* AF_INET addresses will be offset by inet6Count */
             inetIndex = inet6Count;
             inet6Index = 0;
         } else if (addressPreference == java_net_InetAddress_PREFER_IPV4_VALUE) {
-            /* AF_INET6 addresses will be offset by inetCount */
             inetIndex = 0;
             inet6Index = inetCount;
         } else if (addressPreference == java_net_InetAddress_PREFER_SYSTEM_VALUE) {
             inetIndex = inet6Index = originalIndex = 0;
         }
 
+        iterator = resNew;
         while (iterator != NULL) {
-            jboolean ret1;
             if (iterator->ai_family == AF_INET) {
                 jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
                 if (IS_NULL(iaObj)) {
@@ -416,7 +367,7 @@
                 inetIndex++;
             } else if (iterator->ai_family == AF_INET6) {
                 jint scope = 0;
-
+                jboolean ret1;
                 jobject iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
                 if (IS_NULL(iaObj)) {
                     ret = NULL;
@@ -427,9 +378,8 @@
                     ret = NULL;
                     goto cleanupAndReturn;
                 }
-
-                scope = ((struct sockaddr_in6*)iterator->ai_addr)->sin6_scope_id;
-                if (scope != 0) { /* zero is default value, no need to set */
+                scope = ((struct sockaddr_in6 *)iterator->ai_addr)->sin6_scope_id;
+                if (scope != 0) { // zero is default value, no need to set
                     setInet6Address_scopeid(env, iaObj, scope);
                 }
                 setInetAddress_hostName(env, iaObj, host);
@@ -443,21 +393,16 @@
             iterator = iterator->ai_next;
         }
     }
-
- cleanupAndReturn:
-    {
-      struct addrinfo *iterator, *tmp;
-        iterator = resNew;
-        while (iterator != NULL) {
-            tmp = iterator;
-            iterator = iterator->ai_next;
-            free(tmp);
-        }
-        JNU_ReleaseStringPlatformChars(env, host, hostname);
+cleanupAndReturn:
+    JNU_ReleaseStringPlatformChars(env, host, hostname);
+    while (resNew != NULL) {
+        last = resNew;
+        resNew = resNew->ai_next;
+        free(last);
     }
-
-    freeaddrinfo(res);
-
+    if (res != NULL) {
+        freeaddrinfo(res);
+    }
     return ret;
 }
 
@@ -465,171 +410,252 @@
  * Class:     java_net_Inet6AddressImpl
  * Method:    getHostByAddr
  * Signature: (I)Ljava/lang/String;
+ *
+ * Theoretically the UnknownHostException could be enriched with gai error
+ * information. But as it is silently ignored anyway, there's no need for this.
+ * It's only important that either a valid hostname is returned or an
+ * UnknownHostException is thrown.
  */
 JNIEXPORT jstring JNICALL
 Java_java_net_Inet6AddressImpl_getHostByAddr(JNIEnv *env, jobject this,
-                                            jbyteArray addrArray) {
-
+                                             jbyteArray addrArray) {
     jstring ret = NULL;
-
-    char host[NI_MAXHOST+1];
-    int error = 0;
+    char host[NI_MAXHOST + 1];
     int len = 0;
     jbyte caddr[16];
+    SOCKETADDRESS sa;
 
-    struct sockaddr_in him4;
-    struct sockaddr_in6 him6;
-    struct sockaddr *sa;
+    memset((void *)&sa, 0, sizeof(SOCKETADDRESS));
 
-    /*
-     * For IPv4 addresses construct a sockaddr_in structure.
-     */
+    // construct a sockaddr_in structure (AF_INET or AF_INET6)
     if ((*env)->GetArrayLength(env, addrArray) == 4) {
         jint addr;
         (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
-        addr = ((caddr[0]<<24) & 0xff000000);
-        addr |= ((caddr[1] <<16) & 0xff0000);
-        addr |= ((caddr[2] <<8) & 0xff00);
+        addr = ((caddr[0] << 24) & 0xff000000);
+        addr |= ((caddr[1] << 16) & 0xff0000);
+        addr |= ((caddr[2] << 8) & 0xff00);
         addr |= (caddr[3] & 0xff);
-        memset((void *) &him4, 0, sizeof(him4));
-        him4.sin_addr.s_addr = htonl(addr);
-        him4.sin_family = AF_INET;
-        sa = (struct sockaddr *)&him4;
-        len = sizeof(him4);
+        sa.sa4.sin_addr.s_addr = htonl(addr);
+        sa.sa4.sin_family = AF_INET;
+        len = sizeof(struct sockaddr_in);
     } else {
-        /*
-         * For IPv6 address construct a sockaddr_in6 structure.
-         */
         (*env)->GetByteArrayRegion(env, addrArray, 0, 16, caddr);
-        memset((void *)&him6, 0, sizeof(him6));
-        memcpy((void *)&(him6.sin6_addr), caddr, sizeof(struct in6_addr));
-        him6.sin6_family = AF_INET6;
-        sa = (struct sockaddr *)&him6;
-        len = sizeof(him6);
+        memcpy((void *)&sa.sa6.sin6_addr, caddr, sizeof(struct in6_addr));
+        sa.sa6.sin6_family = AF_INET6;
+        len = sizeof(struct sockaddr_in6);
     }
 
-    error = getnameinfo(sa, len, host, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
-
-    if (!error) {
+    if (getnameinfo(&sa.sa, len, host, NI_MAXHOST, NULL, 0, NI_NAMEREQD)) {
+        JNU_ThrowByName(env, "java/net/UnknownHostException", NULL);
+    } else {
         ret = (*env)->NewStringUTF(env, host);
-        CHECK_NULL_RETURN(ret, NULL);
-    }
-
-    if (ret == NULL) {
-        JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", NULL);
+        if (ret == NULL) {
+            JNU_ThrowByName(env, "java/net/UnknownHostException", NULL);
+        }
     }
 
     return ret;
 }
 
-#define SET_NONBLOCKING(fd) {           \
-        int flags = fcntl(fd, F_GETFL); \
-        flags |= O_NONBLOCK;            \
-        fcntl(fd, F_SETFL, flags);      \
+/**
+ * ping implementation using tcp port 7 (echo)
+ */
+static jboolean
+tcp_ping6(JNIEnv *env, SOCKETADDRESS *sa, SOCKETADDRESS *netif, jint timeout,
+          jint ttl)
+{
+    jint fd;
+    int connect_rv = -1;
+
+    // open a TCP socket
+    fd = socket(AF_INET6, SOCK_STREAM, 0);
+    if (fd == -1) {
+        // note: if you run out of fds, you may not be able to load
+        // the exception class, and get a NoClassDefFoundError instead.
+        NET_ThrowNew(env, errno, "Can't create socket");
+        return JNI_FALSE;
+    }
+
+    // set TTL
+    if (ttl > 0) {
+        setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof(ttl));
+    }
+
+    // A network interface was specified, so let's bind to it.
+    if (netif != NULL) {
+        if (bind(fd, &netif->sa, sizeof(struct sockaddr_in6)) <0) {
+            NET_ThrowNew(env, errno, "Can't bind socket");
+            close(fd);
+            return JNI_FALSE;
+        }
+    }
+
+    // Make the socket non blocking so we can use select/poll.
+    SET_NONBLOCKING(fd);
+
+    sa->sa6.sin6_port = htons(7); // echo port
+    connect_rv = NET_Connect(fd, &sa->sa, sizeof(struct sockaddr_in6));
+
+    // connection established or refused immediately, either way it means
+    // we were able to reach the host!
+    if (connect_rv == 0 || errno == ECONNREFUSED) {
+        close(fd);
+        return JNI_TRUE;
+    }
+
+    switch (errno) {
+    case ENETUNREACH:   // Network Unreachable
+    case EAFNOSUPPORT:  // Address Family not supported
+    case EADDRNOTAVAIL: // address is not available on the remote machine
+#if defined(__linux__) || defined(_AIX)
+        // On some Linux versions, when a socket is bound to the loopback
+        // interface, connect will fail and errno will be set to EINVAL
+        // or EHOSTUNREACH.  When that happens, don't throw an exception,
+        // just return false.
+    case EINVAL:
+    case EHOSTUNREACH:  // No route to host
+#endif
+        close(fd);
+        return JNI_FALSE;
+    case EINPROGRESS:   // this is expected as we'll probably have to wait
+        break;
+    default:
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
+                                     "connect failed");
+        close(fd);
+        return JNI_FALSE;
+    }
+
+    timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
+    if (timeout >= 0) {
+        // connection has been established, check for error condition
+        socklen_t optlen = (socklen_t)sizeof(connect_rv);
+        if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
+                       &optlen) <0)
+        {
+            connect_rv = errno;
+        }
+        if (connect_rv == 0 || connect_rv == ECONNREFUSED) {
+            close(fd);
+            return JNI_TRUE;
+        }
+    }
+    close(fd);
+    return JNI_FALSE;
 }
 
+/**
+ * ping implementation.
+ * Send an ICMP_ECHO_REQUEST packet every second until either the timeout
+ * expires or an answer is received.
+ * Returns true if an ECHO_REPLY is received, false otherwise.
+ */
 static jboolean
-ping6(JNIEnv *env, jint fd, struct sockaddr_in6* him, jint timeout,
-      struct sockaddr_in6* netif, jint ttl) {
-    jint size;
-    jint n;
+ping6(JNIEnv *env, jint fd, SOCKETADDRESS *sa, SOCKETADDRESS *netif,
+      jint timeout, jint ttl)
+{
+    jint n, size = 60 * 1024, tmout2, seq = 1;
     socklen_t len;
-    char sendbuf[1500];
-    unsigned char recvbuf[1500];
+    unsigned char sendbuf[1500], recvbuf[1500];
     struct icmp6_hdr *icmp6;
     struct sockaddr_in6 sa_recv;
-    jbyte *caddr, *recv_caddr;
     jchar pid;
-    jint tmout2, seq = 1;
     struct timeval tv;
-    size_t plen;
+    size_t plen = sizeof(struct icmp6_hdr) + sizeof(tv);
 
-#ifdef __linux__
-    {
-    int csum_offset;
+#if defined(__linux__)
     /**
      * For some strange reason, the linux kernel won't calculate the
      * checksum of ICMPv6 packets unless you set this socket option
      */
-    csum_offset = 2;
+    int csum_offset = 2;
     setsockopt(fd, SOL_RAW, IPV6_CHECKSUM, &csum_offset, sizeof(int));
-    }
 #endif
 
-    caddr = (jbyte *)&(him->sin6_addr);
+    setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
 
-    /* icmp_id is a 16 bit data type, therefore down cast the pid */
-    pid = (jchar)getpid();
-    size = 60*1024;
-    setsockopt(fd, SOL_SOCKET, SO_RCVBUF, &size, sizeof(size));
+    // sets the ttl (max number of hops)
     if (ttl > 0) {
-      setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof(ttl));
+        setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof(ttl));
     }
+
+    // a specific interface was specified, so let's bind the socket
+    // to that interface to ensure the requests are sent only through it.
     if (netif != NULL) {
-      if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in6)) <0) {
-        NET_ThrowNew(env, errno, "Can't bind socket");
-        close(fd);
-        return JNI_FALSE;
-      }
+        if (bind(fd, &netif->sa, sizeof(struct sockaddr_in6)) <0) {
+            NET_ThrowNew(env, errno, "Can't bind socket");
+            close(fd);
+            return JNI_FALSE;
+        }
     }
+
+    // icmp_id is a 16 bit data type, therefore down cast the pid
+    pid = (jchar)getpid();
+
+    // Make the socket non blocking so we can use select
     SET_NONBLOCKING(fd);
-
     do {
-      icmp6 = (struct icmp6_hdr *) sendbuf;
-      icmp6->icmp6_type = ICMP6_ECHO_REQUEST;
-      icmp6->icmp6_code = 0;
-      /* let's tag the ECHO packet with our pid so we can identify it */
-      icmp6->icmp6_id = htons(pid);
-      icmp6->icmp6_seq = htons(seq);
-      seq++;
-      icmp6->icmp6_cksum = 0;
-      gettimeofday(&tv, NULL);
-      memcpy(sendbuf + sizeof(struct icmp6_hdr), &tv, sizeof(tv));
-      plen = sizeof(struct icmp6_hdr) + sizeof(tv);
-      n = sendto(fd, sendbuf, plen, 0, (struct sockaddr*) him, sizeof(struct sockaddr_in6));
-      if (n < 0 && errno != EINPROGRESS) {
-#ifdef __linux__
-        if (errno != EINVAL && errno != EHOSTUNREACH)
-          /*
-           * On some Linux versions, when a socket is  bound to the
-           * loopback interface, sendto will fail and errno will be
-           * set to EINVAL or EHOSTUNREACH.
-           * When that happens, don't throw an exception, just return false.
-           */
-#endif /*__linux__ */
-        NET_ThrowNew(env, errno, "Can't send ICMP packet");
-        close(fd);
-        return JNI_FALSE;
-      }
+        // create the ICMP request
+        icmp6 = (struct icmp6_hdr *)sendbuf;
+        icmp6->icmp6_type = ICMP6_ECHO_REQUEST;
+        icmp6->icmp6_code = 0;
+        // let's tag the ECHO packet with our pid so we can identify it
+        icmp6->icmp6_id = htons(pid);
+        icmp6->icmp6_seq = htons(seq);
+        seq++;
+        gettimeofday(&tv, NULL);
+        memcpy(sendbuf + sizeof(struct icmp6_hdr), &tv, sizeof(tv));
+        icmp6->icmp6_cksum = 0;
+        // send it
+        n = sendto(fd, sendbuf, plen, 0, &sa->sa, sizeof(struct sockaddr_in6));
+        if (n < 0 && errno != EINPROGRESS) {
+#if defined(__linux__)
+            /*
+             * On some Linux versions, when a socket is bound to the loopback
+             * interface, sendto will fail and errno will be set to
+             * EINVAL or EHOSTUNREACH. When that happens, don't throw an
+             * exception, just return false.
+             */
+            if (errno != EINVAL && errno != EHOSTUNREACH) {
+                NET_ThrowNew(env, errno, "Can't send ICMP packet");
+            }
+#else
+            NET_ThrowNew(env, errno, "Can't send ICMP packet");
+#endif
+            close(fd);
+            return JNI_FALSE;
+        }
 
-      tmout2 = timeout > 1000 ? 1000 : timeout;
-      do {
-        tmout2 = NET_Wait(env, fd, NET_WAIT_READ, tmout2);
-
-        if (tmout2 >= 0) {
-          len = sizeof(sa_recv);
-          n = recvfrom(fd, recvbuf, sizeof(recvbuf), 0, (struct sockaddr*) &sa_recv, &len);
-          icmp6 = (struct icmp6_hdr *) (recvbuf);
-          recv_caddr = (jbyte *)&(sa_recv.sin6_addr);
-          /*
-           * We did receive something, but is it what we were expecting?
-           * I.E.: An ICMP6_ECHO_REPLY packet with the proper PID and
-           *       from the host that we are trying to determine is reachable.
-           */
-          if (n >= 8 && icmp6->icmp6_type == ICMP6_ECHO_REPLY &&
-              (ntohs(icmp6->icmp6_id) == pid)) {
-            if (NET_IsEqual(caddr, recv_caddr)) {
-              close(fd);
-              return JNI_TRUE;
+        tmout2 = timeout > 1000 ? 1000 : timeout;
+        do {
+            tmout2 = NET_Wait(env, fd, NET_WAIT_READ, tmout2);
+            if (tmout2 >= 0) {
+                len = sizeof(sa_recv);
+                n = recvfrom(fd, recvbuf, sizeof(recvbuf), 0,
+                             (struct sockaddr *)&sa_recv, &len);
+                // check if we received enough data
+                if (n < (jint)sizeof(struct icmp6_hdr)) {
+                    continue;
+                }
+                icmp6 = (struct icmp6_hdr *)recvbuf;
+                // We did receive something, but is it what we were expecting?
+                // I.E.: An ICMP6_ECHO_REPLY packet with the proper PID and
+                //       from the host that we are trying to determine is reachable.
+                if (icmp6->icmp6_type == ICMP6_ECHO_REPLY &&
+                    (ntohs(icmp6->icmp6_id) == pid))
+                {
+                    if (NET_IsEqual((jbyte *)&sa->sa6.sin6_addr,
+                                    (jbyte *)&sa_recv.sin6_addr)) {
+                        close(fd);
+                        return JNI_TRUE;
+                    } else if (NET_IsZeroAddr((jbyte *)&sa->sa6.sin6_addr)) {
+                        close(fd);
+                        return JNI_TRUE;
+                    }
+                }
             }
-            if (NET_IsZeroAddr(caddr)) {
-              close(fd);
-              return JNI_TRUE;
-            }
-          }
-        }
-      } while (tmout2 > 0);
-      timeout -= 1000;
+        } while (tmout2 > 0);
+        timeout -= 1000;
     } while (timeout > 0);
     close(fd);
     return JNI_FALSE;
@@ -642,157 +668,61 @@
  */
 JNIEXPORT jboolean JNICALL
 Java_java_net_Inet6AddressImpl_isReachable0(JNIEnv *env, jobject this,
-                                           jbyteArray addrArray,
-                                           jint scope,
-                                           jint timeout,
-                                           jbyteArray ifArray,
-                                           jint ttl, jint if_scope) {
+                                            jbyteArray addrArray, jint scope,
+                                            jint timeout, jbyteArray ifArray,
+                                            jint ttl, jint if_scope)
+{
     jbyte caddr[16];
-    jint fd, sz;
-    struct sockaddr_in6 him6;
-    struct sockaddr_in6 inf6;
-    struct sockaddr_in6* netif = NULL;
-    int len = 0;
-    int connect_rv = -1;
+    jint sz, fd;
+    SOCKETADDRESS sa, inf, *netif = NULL;
 
-    /*
-     * If IPv6 is not enable, then we can't reach an IPv6 address, can we?
-     */
+    // If IPv6 is not enabled, then we can't reach an IPv6 address, can we?
+    // Actually, we probably shouldn't even get here.
     if (!ipv6_available()) {
-      return JNI_FALSE;
-    }
-    /*
-     * If it's an IPv4 address, ICMP won't work with IPv4 mapped address,
-     * therefore, let's delegate to the Inet4Address method.
-     */
-    sz = (*env)->GetArrayLength(env, addrArray);
-    if (sz == 4) {
-      return Java_java_net_Inet4AddressImpl_isReachable0(env, this,
-                                                         addrArray,
-                                                         timeout,
-                                                         ifArray, ttl);
+        return JNI_FALSE;
     }
 
-    memset((void *) caddr, 0, 16);
-    memset((void *) &him6, 0, sizeof(him6));
-    (*env)->GetByteArrayRegion(env, addrArray, 0, 16, caddr);
-    memcpy((void *)&(him6.sin6_addr), caddr, sizeof(struct in6_addr) );
-    him6.sin6_family = AF_INET6;
-#ifdef __linux__
-    if (scope > 0)
-      him6.sin6_scope_id = scope;
-    else
-      him6.sin6_scope_id = getDefaultIPv6Interface( &(him6.sin6_addr));
-    len = sizeof(struct sockaddr_in6);
-#else
-    if (scope > 0)
-      him6.sin6_scope_id = scope;
-    len = sizeof(struct sockaddr_in6);
-#endif
-    /*
-     * If a network interface was specified, let's create the address
-     * for it.
-     */
-    if (!(IS_NULL(ifArray))) {
-      memset((void *) caddr, 0, 16);
-      memset((void *) &inf6, 0, sizeof(inf6));
-      (*env)->GetByteArrayRegion(env, ifArray, 0, 16, caddr);
-      memcpy((void *)&(inf6.sin6_addr), caddr, sizeof(struct in6_addr) );
-      inf6.sin6_family = AF_INET6;
-      inf6.sin6_scope_id = if_scope;
-      netif = &inf6;
-    }
-    /*
-     * If we can create a RAW socket, then when can use the ICMP ECHO_REQUEST
-     * otherwise we'll try a tcp socket to the Echo port (7).
-     * Note that this is empiric, and not connecting could mean it's blocked
-     * or the echo service has been disabled.
-     */
-
-    fd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
-
-    if (fd != -1) { /* Good to go, let's do a ping */
-        return ping6(env, fd, &him6, timeout, netif, ttl);
+    // If it's an IPv4 address, ICMP won't work with IPv4 mapped address,
+    // therefore, let's delegate to the Inet4Address method.
+    sz = (*env)->GetArrayLength(env, addrArray);
+    if (sz == 4) {
+        return Java_java_net_Inet4AddressImpl_isReachable0(env, this,
+                                                           addrArray, timeout,
+                                                           ifArray, ttl);
     }
 
-    /* No good, let's fall back on TCP */
-    fd = socket(AF_INET6, SOCK_STREAM, 0);
-    if (fd == -1) {
-        /* note: if you run out of fds, you may not be able to load
-         * the exception class, and get a NoClassDefFoundError
-         * instead.
-         */
-        NET_ThrowNew(env, errno, "Can't create socket");
-        return JNI_FALSE;
-    }
-    if (ttl > 0) {
-      setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, &ttl, sizeof(ttl));
+    // load address to SOCKETADDRESS
+    memset((char *)caddr, 0, 16);
+    (*env)->GetByteArrayRegion(env, addrArray, 0, 16, caddr);
+    memset((char *)&sa, 0, sizeof(SOCKETADDRESS));
+    memcpy((void *)&sa.sa6.sin6_addr, caddr, sizeof(struct in6_addr));
+    sa.sa6.sin6_family = AF_INET6;
+    if (scope > 0) {
+        sa.sa6.sin6_scope_id = scope;
+#if defined(__linux__)
+    } else {
+        sa.sa6.sin6_scope_id = getDefaultIPv6Interface(&sa.sa6.sin6_addr);
+#endif
     }
 
-    /*
-     * A network interface was specified, so let's bind to it.
-     */
-    if (netif != NULL) {
-      if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in6)) <0) {
-        NET_ThrowNew(env, errno, "Can't bind socket");
-        close(fd);
-        return JNI_FALSE;
-      }
+    // load network interface address to SOCKETADDRESS, if specified
+    if (!(IS_NULL(ifArray))) {
+        memset((char *)caddr, 0, 16);
+        (*env)->GetByteArrayRegion(env, ifArray, 0, 16, caddr);
+        memset((char *)&inf, 0, sizeof(SOCKETADDRESS));
+        memcpy((void *)&inf.sa6.sin6_addr, caddr, sizeof(struct in6_addr));
+        inf.sa6.sin6_family = AF_INET6;
+        inf.sa6.sin6_scope_id = if_scope;
+        netif = &inf;
     }
-    SET_NONBLOCKING(fd);
-
-    him6.sin6_port = htons((short) 7); /* Echo port */
-    connect_rv = NET_Connect(fd, (struct sockaddr *)&him6, len);
-
-    /**
-     * connection established or refused immediately, either way it means
-     * we were able to reach the host!
-     */
-    if (connect_rv == 0 || errno == ECONNREFUSED) {
-        close(fd);
-        return JNI_TRUE;
-    } else {
-        socklen_t optlen = (socklen_t)sizeof(connect_rv);
 
-        switch (errno) {
-        case ENETUNREACH: /* Network Unreachable */
-        case EAFNOSUPPORT: /* Address Family not supported */
-        case EADDRNOTAVAIL: /* address is not available on  the  remote machine */
-#if defined(__linux__) || defined(_AIX)
-        case EINVAL:
-        case EHOSTUNREACH: /* No route to host */
-          /*
-           * On some Linux versions, when  a socket is bound to the
-           * loopback interface, connect will fail and errno will
-           * be set to EINVAL or EHOSTUNREACH.  When that happens,
-           * don't throw an exception, just return false.
-           */
-#endif /* __linux__ */
-          close(fd);
-          return JNI_FALSE;
-        }
-
-        if (errno != EINPROGRESS) {
-            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
-                                         "connect failed");
-            close(fd);
-            return JNI_FALSE;
-        }
-
-        timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
-
-        if (timeout >= 0) {
-          /* has connection been established */
-          if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
-                         &optlen) <0) {
-            connect_rv = errno;
-          }
-          if (connect_rv == 0 || connect_rv == ECONNREFUSED) {
-            close(fd);
-            return JNI_TRUE;
-          }
-        }
-        close(fd);
-        return JNI_FALSE;
+    // Let's try to create a RAW socket to send ICMP packets.
+    // This usually requires "root" privileges, so it's likely to fail.
+    fd = socket(AF_INET6, SOCK_RAW, IPPROTO_ICMPV6);
+    if (fd == -1) {
+        return tcp_ping6(env, &sa, netif, timeout, ttl);
+    } else {
+        // It didn't fail, so we can use ICMP_ECHO requests.
+        return ping6(env, fd, &sa, netif, timeout, ttl);
     }
 }
--- a/jdk/src/java.base/unix/native/libnio/ch/DatagramChannelImpl.c	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/unix/native/libnio/ch/DatagramChannelImpl.c	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2017, 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
@@ -90,29 +90,16 @@
 #if defined(__solaris__)
     rv = connect(fd, 0, 0);
 #else
-    int len;
     SOCKETADDRESS sa;
+    socklen_t len = isIPv6 ? sizeof(struct sockaddr_in6) :
+                             sizeof(struct sockaddr_in);
 
     memset(&sa, 0, sizeof(sa));
-
-#ifdef AF_INET6
-    if (isIPv6) {
 #if defined(_ALLBSD_SOURCE)
-        sa.sa6.sin6_family = AF_INET6;
+    sa.sa.sa_family = isIPv6 ? AF_INET6 : AF_INET;
 #else
-        sa.sa6.sin6_family = AF_UNSPEC;
+    sa.sa.sa_family = AF_UNSPEC;
 #endif
-        len = sizeof(struct sockaddr_in6);
-    } else
-#endif
-    {
-#if defined(_ALLBSD_SOURCE)
-        sa.sa4.sin_family = AF_INET;
-#else
-        sa.sa4.sin_family = AF_UNSPEC;
-#endif
-        len = sizeof(struct sockaddr_in);
-    }
 
     rv = connect(fd, &sa.sa, len);
 
@@ -126,8 +113,9 @@
      */
     if (rv < 0 && errno == EAFNOSUPPORT)
         rv = errno = 0;
-#endif
-#endif
+#endif // defined(_ALLBSD_SOURCE) || defined(_AIX)
+
+#endif // defined(__solaris__)
 
     if (rv < 0)
         handleSocketError(env, errno);
--- a/jdk/src/java.base/unix/native/libnio/ch/InheritedChannel.c	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/unix/native/libnio/ch/InheritedChannel.c	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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,14 +37,8 @@
 
 #include "sun_nio_ch_InheritedChannel.h"
 
-static int matchFamily(struct sockaddr *sa) {
-    int family = sa->sa_family;
-#ifdef AF_INET6
-    if (ipv6_available()) {
-        return (family == AF_INET6);
-    }
-#endif
-    return (family == AF_INET);
+static int matchFamily(SOCKETADDRESS *sa) {
+    return (sa->sa.sa_family == (ipv6_available() ? AF_INET6 : AF_INET));
 }
 
 JNIEXPORT void JNICALL
@@ -63,7 +57,7 @@
     jint remote_port;
 
     if (getpeername(fd, &sa.sa, &len) == 0) {
-        if (matchFamily(&sa.sa)) {
+        if (matchFamily(&sa)) {
             remote_ia = NET_SockaddrToInetAddress(env, &sa, (int *)&remote_port);
         }
     }
@@ -71,7 +65,6 @@
     return remote_ia;
 }
 
-
 JNIEXPORT jint JNICALL
 Java_sun_nio_ch_InheritedChannel_peerPort0(JNIEnv *env, jclass cla, jint fd)
 {
@@ -80,7 +73,7 @@
     jint remote_port = -1;
 
     if (getpeername(fd, &sa.sa, &len) == 0) {
-        if (matchFamily(&sa.sa)) {
+        if (matchFamily(&sa)) {
             NET_SockaddrToInetAddress(env, &sa, (int *)&remote_port);
         }
     }
@@ -92,7 +85,7 @@
 Java_sun_nio_ch_InheritedChannel_soType0(JNIEnv *env, jclass cla, jint fd)
 {
     int sotype;
-    socklen_t arglen=sizeof(sotype);
+    socklen_t arglen = sizeof(sotype);
     if (getsockopt(fd, SOL_SOCKET, SO_TYPE, (void *)&sotype, &arglen) == 0) {
         if (sotype == SOCK_STREAM)
             return sun_nio_ch_InheritedChannel_SOCK_STREAM;
@@ -123,7 +116,7 @@
 JNIEXPORT jint JNICALL
 Java_sun_nio_ch_InheritedChannel_open0(JNIEnv *env, jclass cla, jstring path, jint oflag)
 {
-    const char* str;
+    const char *str;
     int oflag_actual;
 
     /* convert to OS specific value */
--- a/jdk/src/java.base/unix/native/libnio/ch/Net.c	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/unix/native/libnio/ch/Net.c	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2017, 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
@@ -101,23 +101,21 @@
  * Copy IPv6 group, interface index, and IPv6 source address
  * into group_source_req structure.
  */
-#ifdef AF_INET6
 static void initGroupSourceReq(JNIEnv* env, jbyteArray group, jint index,
-                               jbyteArray source, struct group_source_req* req)
+                               jbyteArray source, struct group_source_req *req)
 {
     struct sockaddr_in6* sin6;
 
     req->gsr_interface = (uint32_t)index;
 
-    sin6 = (struct sockaddr_in6*)&(req->gsr_group);
+    sin6 = (struct sockaddr_in6 *)&(req->gsr_group);
     sin6->sin6_family = AF_INET6;
-    COPY_INET6_ADDRESS(env, group, (jbyte*)&(sin6->sin6_addr));
+    COPY_INET6_ADDRESS(env, group, (jbyte *)&(sin6->sin6_addr));
 
-    sin6 = (struct sockaddr_in6*)&(req->gsr_source);
+    sin6 = (struct sockaddr_in6 *)&(req->gsr_source);
     sin6->sin6_family = AF_INET6;
-    COPY_INET6_ADDRESS(env, source, (jbyte*)&(sin6->sin6_addr));
+    COPY_INET6_ADDRESS(env, source, (jbyte *)&(sin6->sin6_addr));
 }
-#endif
 
 #ifdef _AIX
 
@@ -199,18 +197,13 @@
 {
     int fd;
     int type = (stream ? SOCK_STREAM : SOCK_DGRAM);
-#ifdef AF_INET6
     int domain = (ipv6_available() && preferIPv6) ? AF_INET6 : AF_INET;
-#else
-    int domain = AF_INET;
-#endif
 
     fd = socket(domain, type, 0);
     if (fd < 0) {
         return handleSocketError(env, errno);
     }
 
-#ifdef AF_INET6
     /* Disable IPV6_V6ONLY to ensure dual-socket support */
     if (domain == AF_INET6) {
         int arg = 0;
@@ -223,7 +216,6 @@
             return -1;
         }
     }
-#endif
 
     if (reuse) {
         int arg = 1;
@@ -250,9 +242,7 @@
             return -1;
         }
     }
-#endif
 
-#if defined(__linux__) && defined(AF_INET6)
     /* By default, Linux uses the route default */
     if (domain == AF_INET6 && type == SOCK_DGRAM) {
         int arg = 1;
@@ -569,7 +559,6 @@
 Java_sun_nio_ch_Net_joinOrDrop6(JNIEnv *env, jobject this, jboolean join, jobject fdo,
                                 jbyteArray group, jint index, jbyteArray source)
 {
-#ifdef AF_INET6
     struct ipv6_mreq mreq6;
     struct group_source_req req;
     int opt, n, optlen;
@@ -600,21 +589,16 @@
         handleSocketError(env, errno);
     }
     return 0;
-#else
-    JNU_ThrowInternalError(env, "Should not get here");
-    return IOS_THROWN;
-#endif  /* AF_INET6 */
 }
 
 JNIEXPORT jint JNICALL
 Java_sun_nio_ch_Net_blockOrUnblock6(JNIEnv *env, jobject this, jboolean block, jobject fdo,
                                     jbyteArray group, jint index, jbyteArray source)
 {
-#ifdef AF_INET6
-  #ifdef __APPLE__
+#ifdef __APPLE__
     /* no IPv6 exclude-mode filtering for now */
     return IOS_UNAVAILABLE;
-  #else
+#else
     struct group_source_req req;
     int n;
     int opt = (block) ? MCAST_BLOCK_SOURCE : MCAST_UNBLOCK_SOURCE;
@@ -629,10 +613,6 @@
         handleSocketError(env, errno);
     }
     return 0;
-  #endif
-#else
-    JNU_ThrowInternalError(env, "Should not get here");
-    return IOS_THROWN;
 #endif
 }
 
--- a/jdk/src/java.base/windows/native/libjli/cmdtoargs.c	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/windows/native/libjli/cmdtoargs.c	Thu Mar 16 20:47:03 2017 +0000
@@ -205,9 +205,9 @@
     size_t i, cnt;
 
     JLI_List envArgs = JLI_List_new(1);
-    if (JLI_AddArgsFromEnvVar(envArgs, JAVA_OPTIONS)) {
+    if (JLI_AddArgsFromEnvVar(envArgs, JDK_JAVA_OPTIONS)) {
         // JLI_SetTraceLauncher is not called yet
-        // Show _JAVA_OPTIONS content along with JAVA_OPTIONS to aid diagnosis
+        // Show _JAVA_OPTIONS content along with JDK_JAVA_OPTIONS to aid diagnosis
         if (getenv(JLDEBUG_ENV_ENTRY)) {
             char *tmp = getenv("_JAVA_OPTIONS");
             if (NULL != tmp) {
--- a/jdk/src/java.base/windows/native/libnet/Inet4AddressImpl.c	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/windows/native/libnet/Inet4AddressImpl.c	Thu Mar 16 20:47:03 2017 +0000
@@ -30,60 +30,6 @@
 #include "java_net_Inet4AddressImpl.h"
 
 /*
- * Returns true if hostname is in dotted IP address format. Note that this
- * function performs a syntax check only. For each octet it just checks that
- * the octet is at most 3 digits.
- */
-jboolean isDottedIPAddress(const char *hostname, unsigned int *addrp) {
-    char *c = (char *)hostname;
-    int octets = 0;
-    unsigned int cur = 0;
-    int digit_cnt = 0;
-
-    while (*c) {
-        if (*c == '.') {
-            if (digit_cnt == 0) {
-                return JNI_FALSE;
-            } else {
-                if (octets < 4) {
-                    addrp[octets++] = cur;
-                    cur = 0;
-                    digit_cnt = 0;
-                } else {
-                    return JNI_FALSE;
-                }
-            }
-            c++;
-            continue;
-        }
-
-        if ((*c < '0') || (*c > '9')) {
-            return JNI_FALSE;
-        }
-
-        digit_cnt++;
-        if (digit_cnt > 3) {
-            return JNI_FALSE;
-        }
-
-        /* don't check if current octet > 255 */
-        cur = cur*10 + (*c - '0');
-
-        /* Move onto next character and check for EOF */
-        c++;
-        if (*c == '\0') {
-            if (octets < 4) {
-                addrp[octets++] = cur;
-            } else {
-                return JNI_FALSE;
-            }
-        }
-    }
-
-    return (jboolean)(octets == 4);
-}
-
-/*
  * Inet4AddressImpl
  */
 
@@ -93,17 +39,17 @@
  * Signature: ()Ljava/lang/String;
  */
 JNIEXPORT jstring JNICALL
-Java_java_net_Inet4AddressImpl_getLocalHostName (JNIEnv *env, jobject this) {
+Java_java_net_Inet4AddressImpl_getLocalHostName(JNIEnv *env, jobject this) {
     char hostname[256];
 
-    if (gethostname(hostname, sizeof hostname) == -1) {
+    if (gethostname(hostname, sizeof(hostname)) == -1) {
         strcpy(hostname, "localhost");
     }
     return JNU_NewStringPlatform(env, hostname);
 }
 
 /*
- * Find an internet address for a given hostname.  Not this this
+ * Find an internet address for a given hostname. Note that this
  * code only works for addresses of type INET. The translation
  * of %d.%d.%d.%d to an address (int) occurs in java now, so the
  * String "host" shouldn't be a %d.%d.%d.%d string. The only
@@ -120,7 +66,6 @@
     jobjectArray ret = NULL;
     const char *hostname;
     int error = 0;
-    unsigned int addr[4];
     struct addrinfo hints, *res = NULL, *resNew = NULL, *last = NULL,
         *iterator;
 
@@ -134,57 +79,6 @@
     hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);
     CHECK_NULL_RETURN(hostname, NULL);
 
-    /*
-     * The NT/2000 resolver tolerates a space in front of localhost. This
-     * is not consistent with other implementations of gethostbyname.
-     * In addition we must do a white space check on Solaris to avoid a
-     * bug whereby 0.0.0.0 is returned if any host name has a white space.
-     */
-    if (isspace(hostname[0])) {
-        JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", hostname);
-        goto cleanupAndReturn;
-    }
-
-    /*
-     * If the format is x.x.x.x then don't use gethostbyname as Windows
-     * is unable to handle octets which are out of range.
-     */
-    if (isDottedIPAddress(hostname, &addr[0])) {
-        unsigned int address;
-        jobject iaObj;
-
-        /*
-         * Are any of the octets out of range?
-         */
-        if (addr[0] > 255 || addr[1] > 255 || addr[2] > 255 || addr[3] > 255) {
-            JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", hostname);
-            goto cleanupAndReturn;
-        }
-
-        /*
-         * Return an byte array with the populated address.
-         */
-        address = (addr[3] << 24) & 0xff000000;
-        address |= (addr[2] << 16) & 0xff0000;
-        address |= (addr[1] << 8) & 0xff00;
-        address |= addr[0];
-
-        ret = (*env)->NewObjectArray(env, 1, ia_class, NULL);
-
-        if (IS_NULL(ret)) {
-            goto cleanupAndReturn;
-        }
-
-        iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
-        if (IS_NULL(iaObj)) {
-            ret = NULL;
-            goto cleanupAndReturn;
-        }
-        setInetAddress_addr(env, iaObj, ntohl(address));
-        (*env)->SetObjectArrayElement(env, ret, 0, iaObj);
-        goto cleanupAndReturn;
-    }
-
     // try once, with our static buffer
     memset(&hints, 0, sizeof(hints));
     hints.ai_flags = AI_CANONNAME;
@@ -193,6 +87,7 @@
     error = getaddrinfo(hostname, NULL, &hints, &res);
 
     if (error) {
+        // report error
         NET_ThrowByNameWithLastError(env, "java/net/UnknownHostException",
                                      hostname);
         goto cleanupAndReturn;
@@ -311,145 +206,86 @@
     return ret;
 }
 
+/**
+ * ping implementation using tcp port 7 (echo)
+ */
 static jboolean
-tcp_ping4(JNIEnv *env,
-          jbyteArray addrArray,
-          jint timeout,
-          jbyteArray ifArray,
+tcp_ping4(JNIEnv *env, SOCKETADDRESS *sa, SOCKETADDRESS *netif, jint timeout,
           jint ttl)
 {
-    jint addr;
-    jbyte caddr[4];
     jint fd;
-    struct sockaddr_in him;
-    struct sockaddr_in* netif = NULL;
-    struct sockaddr_in inf;
-    int len = 0;
+    int connect_rv = -1;
     WSAEVENT hEvent;
-    int connect_rv = -1;
-    int sz;
 
-    /**
-     * Convert IP address from byte array to integer
-     */
-    sz = (*env)->GetArrayLength(env, addrArray);
-    if (sz != 4) {
-        return JNI_FALSE;
-    }
-    memset((char *) &him, 0, sizeof(him));
-    memset((char *) caddr, 0, sizeof(caddr));
-    (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
-    addr = ((caddr[0]<<24) & 0xff000000);
-    addr |= ((caddr[1] <<16) & 0xff0000);
-    addr |= ((caddr[2] <<8) & 0xff00);
-    addr |= (caddr[3] & 0xff);
-    addr = htonl(addr);
-    /**
-     * Socket address
-     */
-    him.sin_addr.s_addr = addr;
-    him.sin_family = AF_INET;
-    len = sizeof(him);
-
-    /**
-     * If a network interface was specified, let's convert its address
-     * as well.
-     */
-    if (!(IS_NULL(ifArray))) {
-        memset((char *) caddr, 0, sizeof(caddr));
-        (*env)->GetByteArrayRegion(env, ifArray, 0, 4, caddr);
-        addr = ((caddr[0]<<24) & 0xff000000);
-        addr |= ((caddr[1] <<16) & 0xff0000);
-        addr |= ((caddr[2] <<8) & 0xff00);
-        addr |= (caddr[3] & 0xff);
-        addr = htonl(addr);
-        inf.sin_addr.s_addr = addr;
-        inf.sin_family = AF_INET;
-        inf.sin_port = 0;
-        netif = &inf;
-    }
-
-    /*
-     * Can't create a raw socket, so let's try a TCP socket
-     */
+    // open a TCP socket
     fd = NET_Socket(AF_INET, SOCK_STREAM, 0);
-    if (fd == -1) {
-        /* note: if you run out of fds, you may not be able to load
-         * the exception class, and get a NoClassDefFoundError
-         * instead.
-         */
+    if (fd == SOCKET_ERROR) {
+        // note: if you run out of fds, you may not be able to load
+        // the exception class, and get a NoClassDefFoundError instead.
         NET_ThrowNew(env, WSAGetLastError(), "Can't create socket");
         return JNI_FALSE;
     }
+
+    // set TTL
     if (ttl > 0) {
         setsockopt(fd, IPPROTO_IP, IP_TTL, (const char *)&ttl, sizeof(ttl));
     }
-    /*
-     * A network interface was specified, so let's bind to it.
-     */
+
+    // A network interface was specified, so let's bind to it.
     if (netif != NULL) {
-        if (bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in)) < 0) {
+        if (bind(fd, &netif->sa, sizeof(struct sockaddr_in)) < 0) {
             NET_ThrowNew(env, WSAGetLastError(), "Can't bind socket");
             closesocket(fd);
             return JNI_FALSE;
         }
     }
 
-    /*
-     * Make the socket non blocking so we can use select/poll.
-     */
+    // Make the socket non blocking so we can use select/poll.
     hEvent = WSACreateEvent();
     WSAEventSelect(fd, hEvent, FD_READ|FD_CONNECT|FD_CLOSE);
 
-    /* no need to use NET_Connect as non-blocking */
-    him.sin_port = htons(7);    /* Echo */
-    connect_rv = connect(fd, (struct sockaddr *)&him, len);
+    sa->sa4.sin_port = htons(7); // echo port
+    connect_rv = connect(fd, &sa->sa, sizeof(struct sockaddr_in));
 
-    /**
-     * connection established or refused immediately, either way it means
-     * we were able to reach the host!
-     */
+    // connection established or refused immediately, either way it means
+    // we were able to reach the host!
     if (connect_rv == 0 || WSAGetLastError() == WSAECONNREFUSED) {
         WSACloseEvent(hEvent);
         closesocket(fd);
         return JNI_TRUE;
-    } else {
-        int optlen;
+    }
 
-        switch (WSAGetLastError()) {
-        case WSAEHOSTUNREACH:   /* Host Unreachable */
-        case WSAENETUNREACH:    /* Network Unreachable */
-        case WSAENETDOWN:       /* Network is down */
-        case WSAEPFNOSUPPORT:   /* Protocol Family unsupported */
-            WSACloseEvent(hEvent);
-            closesocket(fd);
-            return JNI_FALSE;
+    switch (WSAGetLastError()) {
+    case WSAEHOSTUNREACH:   // Host Unreachable
+    case WSAENETUNREACH:    // Network Unreachable
+    case WSAENETDOWN:       // Network is down
+    case WSAEPFNOSUPPORT:   // Protocol Family unsupported
+        WSACloseEvent(hEvent);
+        closesocket(fd);
+        return JNI_FALSE;
+    case WSAEWOULDBLOCK:    // this is expected as we'll probably have to wait
+        break;
+    default:
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
+                                     "connect failed");
+        WSACloseEvent(hEvent);
+        closesocket(fd);
+        return JNI_FALSE;
+    }
+
+    timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
+    if (timeout >= 0) {
+        // connection has been established, check for error condition
+        int optlen = sizeof(connect_rv);
+        if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&connect_rv,
+                       &optlen) < 0)
+        {
+            connect_rv = WSAGetLastError();
         }
-
-        if (WSAGetLastError() != WSAEWOULDBLOCK) {
-            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
-                                         "connect failed");
+        if (connect_rv == 0 || connect_rv == WSAECONNREFUSED) {
             WSACloseEvent(hEvent);
             closesocket(fd);
-            return JNI_FALSE;
-        }
-
-        timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
-
-        /* has connection been established */
-
-        if (timeout >= 0) {
-            optlen = sizeof(connect_rv);
-            if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
-                           &optlen) <0) {
-                connect_rv = WSAGetLastError();
-            }
-
-            if (connect_rv == 0 || connect_rv == WSAECONNREFUSED) {
-                WSACloseEvent(hEvent);
-                closesocket(fd);
-                return JNI_TRUE;
-            }
+            return JNI_TRUE;
         }
     }
     WSACloseEvent(hEvent);
@@ -464,21 +300,17 @@
  * Returns true is an ECHO_REPLY is received, otherwise, false.
  */
 static jboolean
-ping4(JNIEnv *env,
-      unsigned long src_addr,
-      unsigned long dest_addr,
-      jint timeout,
-      HANDLE hIcmpFile)
+ping4(JNIEnv *env, HANDLE hIcmpFile, SOCKETADDRESS *sa,
+      SOCKETADDRESS *netif, jint timeout)
 {
-    // See https://msdn.microsoft.com/en-us/library/aa366050%28VS.85%29.aspx
-
     DWORD dwRetVal = 0;
     char SendData[32] = {0};
     LPVOID ReplyBuffer = NULL;
     DWORD ReplySize = 0;
     jboolean ret = JNI_FALSE;
 
-    // https://msdn.microsoft.com/en-us/library/windows/desktop/aa366051%28v=vs.85%29.aspx
+    // See https://msdn.microsoft.com/en-us/library/aa366050%28VS.85%29.aspx
+    // or https://msdn.microsoft.com/en-us/library/windows/desktop/aa366051%28v=vs.85%29.aspx
     ReplySize = sizeof(ICMP_ECHO_REPLY)   // The buffer should be large enough
                                           // to hold at least one ICMP_ECHO_REPLY
                                           // structure
@@ -487,16 +319,16 @@
                                           // to also hold 8 more bytes of data
                                           // (the size of an ICMP error message)
 
-    ReplyBuffer = (VOID*) malloc(ReplySize);
+    ReplyBuffer = (VOID *)malloc(ReplySize);
     if (ReplyBuffer == NULL) {
         IcmpCloseHandle(hIcmpFile);
         NET_ThrowNew(env, WSAGetLastError(), "Unable to allocate memory");
         return JNI_FALSE;
     }
 
-    if (src_addr == 0) {
+    if (netif == NULL) {
         dwRetVal = IcmpSendEcho(hIcmpFile,  // HANDLE IcmpHandle,
-                                dest_addr,  // IPAddr DestinationAddress,
+                                sa->sa4.sin_addr.s_addr, // IPAddr DestinationAddress,
                                 SendData,   // LPVOID RequestData,
                                 sizeof(SendData),   // WORD RequestSize,
                                 NULL,       // PIP_OPTION_INFORMATION RequestOptions,
@@ -506,20 +338,20 @@
                                 // seem to have an undocumented minimum
                                 // timeout of 1000ms below which the
                                 // api behaves inconsistently.
-                                (timeout < 1000) ? 1000 : timeout);   // DWORD Timeout
+                                (timeout < 1000) ? 1000 : timeout); // DWORD Timeout
     } else {
         dwRetVal = IcmpSendEcho2Ex(hIcmpFile,  // HANDLE IcmpHandle,
                                    NULL,       // HANDLE Event
                                    NULL,       // PIO_APC_ROUTINE ApcRoutine
                                    NULL,       // ApcContext
-                                   src_addr,   // IPAddr SourceAddress,
-                                   dest_addr,  // IPAddr DestinationAddress,
+                                   netif->sa4.sin_addr.s_addr, // IPAddr SourceAddress,
+                                   sa->sa4.sin_addr.s_addr, // IPAddr DestinationAddress,
                                    SendData,   // LPVOID RequestData,
-                                   sizeof(SendData),   // WORD RequestSize,
+                                   sizeof(SendData), // WORD RequestSize,
                                    NULL,       // PIP_OPTION_INFORMATION RequestOptions,
                                    ReplyBuffer,// LPVOID ReplyBuffer,
                                    ReplySize,  // DWORD ReplySize,
-                                   (timeout < 1000) ? 1000 : timeout);   // DWORD Timeout
+                                   (timeout < 1000) ? 1000 : timeout); // DWORD Timeout
     }
 
     if (dwRetVal == 0) { // if the call failed
@@ -544,8 +376,8 @@
                 break;
             default:
                 FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
-                        NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-                        (LPTSTR)&buf, 0, NULL);
+                              NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
+                              (LPTSTR)&buf, 0, NULL);
                 NET_ThrowNew(env, err, buf);
                 LocalFree(buf);
                 break;
@@ -558,8 +390,8 @@
         // We perform an extra check to make sure that our
         // roundtrip time was less than our desired timeout
         // for cases where that timeout is < 1000ms.
-        if (pEchoReply->Status == IP_SUCCESS
-                && (int)pEchoReply->RoundTripTime <= timeout)
+        if (pEchoReply->Status == IP_SUCCESS &&
+            (int)pEchoReply->RoundTripTime <= timeout)
         {
             ret = JNI_TRUE;
         }
@@ -578,57 +410,58 @@
  */
 JNIEXPORT jboolean JNICALL
 Java_java_net_Inet4AddressImpl_isReachable0(JNIEnv *env, jobject this,
-                                           jbyteArray addrArray,
-                                           jint timeout,
-                                           jbyteArray ifArray,
-                                           jint ttl) {
-    jint src_addr = 0;
-    jint dest_addr = 0;
+                                            jbyteArray addrArray, jint timeout,
+                                            jbyteArray ifArray, jint ttl)
+{
     jbyte caddr[4];
-    int sz;
+    jint addr = 0, sz;
+    SOCKETADDRESS sa, inf, *netif = NULL;
     HANDLE hIcmpFile;
 
-    /**
-     * Convert IP address from byte array to integer
-     */
+    // check if address array size is 4 (IPv4 address)
     sz = (*env)->GetArrayLength(env, addrArray);
     if (sz != 4) {
       return JNI_FALSE;
     }
-    memset((char *) caddr, 0, sizeof(caddr));
+
+    // convert IP address from byte array to integer
+    memset((char *)caddr, 0, sizeof(caddr));
     (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
-    dest_addr = ((caddr[0]<<24) & 0xff000000);
-    dest_addr |= ((caddr[1] <<16) & 0xff0000);
-    dest_addr |= ((caddr[2] <<8) & 0xff00);
-    dest_addr |= (caddr[3] & 0xff);
-    dest_addr = htonl(dest_addr);
+    addr = ((caddr[0] << 24) & 0xff000000);
+    addr |= ((caddr[1] << 16) & 0xff0000);
+    addr |= ((caddr[2] << 8) & 0xff00);
+    addr |= (caddr[3] & 0xff);
+    memset((char *)&sa, 0, sizeof(SOCKETADDRESS));
+    sa.sa4.sin_addr.s_addr = htonl(addr);
+    sa.sa4.sin_family = AF_INET;
 
-    /**
-     * If a network interface was specified, let's convert its address
-     * as well.
-     */
+    // If a network interface was specified, let's convert its address as well.
     if (!(IS_NULL(ifArray))) {
-        memset((char *) caddr, 0, sizeof(caddr));
+        memset((char *)caddr, 0, sizeof(caddr));
         (*env)->GetByteArrayRegion(env, ifArray, 0, 4, caddr);
-        src_addr = ((caddr[0]<<24) & 0xff000000);
-        src_addr |= ((caddr[1] <<16) & 0xff0000);
-        src_addr |= ((caddr[2] <<8) & 0xff00);
-        src_addr |= (caddr[3] & 0xff);
-        src_addr = htonl(src_addr);
+        addr = ((caddr[0] << 24) & 0xff000000);
+        addr |= ((caddr[1] << 16) & 0xff0000);
+        addr |= ((caddr[2] << 8) & 0xff00);
+        addr |= (caddr[3] & 0xff);
+        memset((char *)&inf, 0, sizeof(SOCKETADDRESS));
+        inf.sa4.sin_addr.s_addr = htonl(addr);
+        inf.sa4.sin_family = AF_INET;
+        netif = &inf;
     }
 
+    // Let's try to create an ICMP handle.
     hIcmpFile = IcmpCreateFile();
     if (hIcmpFile == INVALID_HANDLE_VALUE) {
         int err = WSAGetLastError();
         if (err == ERROR_ACCESS_DENIED) {
             // fall back to TCP echo if access is denied to ICMP
-            return tcp_ping4(env, addrArray, timeout, ifArray, ttl);
+            return tcp_ping4(env, &sa, netif, timeout, ttl);
         } else {
             NET_ThrowNew(env, err, "Unable to create ICMP file handle");
             return JNI_FALSE;
         }
     } else {
-        return ping4(env, src_addr, dest_addr, timeout, hIcmpFile);
+        // It didn't fail, so we can use ICMP.
+        return ping4(env, hIcmpFile, &sa, netif, timeout);
     }
 }
-
--- a/jdk/src/java.base/windows/native/libnet/Inet6AddressImpl.c	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.base/windows/native/libnet/Inet6AddressImpl.c	Thu Mar 16 20:47:03 2017 +0000
@@ -40,41 +40,40 @@
  * Signature: ()Ljava/lang/String;
  */
 JNIEXPORT jstring JNICALL
-Java_java_net_Inet6AddressImpl_getLocalHostName (JNIEnv *env, jobject this) {
-    char hostname [256];
+Java_java_net_Inet6AddressImpl_getLocalHostName(JNIEnv *env, jobject this) {
+    char hostname[256];
 
-    if (gethostname (hostname, sizeof (hostname)) == -1) {
-        strcpy (hostname, "localhost");
+    if (gethostname(hostname, sizeof(hostname)) == -1) {
+        strcpy(hostname, "localhost");
     }
-    return JNU_NewStringPlatform (env, hostname);
+    return JNU_NewStringPlatform(env, hostname);
 }
 
+/*
+ * Class:     java_net_Inet6AddressImpl
+ * Method:    lookupAllHostAddr
+ * Signature: (Ljava/lang/String;)[[B
+ */
 JNIEXPORT jobjectArray JNICALL
 Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
-                                                jstring host) {
+                                                 jstring host) {
+    jobjectArray ret = NULL;
     const char *hostname;
-    jobjectArray ret = 0;
-    int retLen = 0;
-    jboolean preferIPv6Address;
-
-    int error=0;
-    struct addrinfo hints, *res = NULL, *resNew = NULL;
+    int error = 0;
+    struct addrinfo hints, *res = NULL, *resNew = NULL, *last = NULL,
+        *iterator;
 
     initInetAddressIDs(env);
     JNU_CHECK_EXCEPTION_RETURN(env, NULL);
 
     if (IS_NULL(host)) {
-        JNU_ThrowNullPointerException(env, "host is null");
-        return 0;
+        JNU_ThrowNullPointerException(env, "host argument is null");
+        return NULL;
     }
     hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);
     CHECK_NULL_RETURN(hostname, NULL);
 
-    /* get the address preference */
-    preferIPv6Address
-        = (*env)->GetStaticIntField(env, ia_class, ia_preferIPv6AddressID);
-
-    /* Try once, with our static buffer. */
+    // try once, with our static buffer
     memset(&hints, 0, sizeof(hints));
     hints.ai_flags = AI_CANONNAME;
     hints.ai_family = AF_UNSPEC;
@@ -82,35 +81,28 @@
     error = getaddrinfo(hostname, NULL, &hints, &res);
 
     if (error) {
-        if (WSAGetLastError() == WSATRY_AGAIN) {
-            NET_ThrowByNameWithLastError(env,
-                                         JNU_JAVANETPKG "UnknownHostException",
-                                         hostname);
-            JNU_ReleaseStringPlatformChars(env, host, hostname);
-            return NULL;
-        } else {
-            /* report error */
-            JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException",
-                            (char *)hostname);
-            JNU_ReleaseStringPlatformChars(env, host, hostname);
-            return NULL;
-        }
+        // report error
+        NET_ThrowByNameWithLastError(env, "java/net/UnknownHostException",
+                                     hostname);
+        goto cleanupAndReturn;
     } else {
-        int i = 0;
-        int inetCount = 0, inet6Count = 0, inetIndex = 0, inet6Index = 0, originalIndex = 0;
-        struct addrinfo *itr, *last, *iterator = res;
+        int i = 0, inetCount = 0, inet6Count = 0, inetIndex = 0,
+            inet6Index = 0, originalIndex = 0;
+        int addressPreference =
+            (*env)->GetStaticIntField(env, ia_class, ia_preferIPv6AddressID);
+        iterator = res;
         while (iterator != NULL) {
+            // skip duplicates
             int skip = 0;
-            itr = resNew;
-            while (itr != NULL) {
-                if (iterator->ai_family == itr->ai_family &&
-                    iterator->ai_addrlen == itr->ai_addrlen) {
-                    if (itr->ai_family == AF_INET) { /* AF_INET */
+            struct addrinfo *iteratorNew = resNew;
+            while (iteratorNew != NULL) {
+                if (iterator->ai_family == iteratorNew->ai_family &&
+                    iterator->ai_addrlen == iteratorNew->ai_addrlen) {
+                    if (iteratorNew->ai_family == AF_INET) { /* AF_INET */
                         struct sockaddr_in *addr1, *addr2;
                         addr1 = (struct sockaddr_in *)iterator->ai_addr;
-                        addr2 = (struct sockaddr_in *)itr->ai_addr;
-                        if (addr1->sin_addr.s_addr ==
-                            addr2->sin_addr.s_addr) {
+                        addr2 = (struct sockaddr_in *)iteratorNew->ai_addr;
+                        if (addr1->sin_addr.s_addr == addr2->sin_addr.s_addr) {
                             skip = 1;
                             break;
                         }
@@ -118,7 +110,7 @@
                         int t;
                         struct sockaddr_in6 *addr1, *addr2;
                         addr1 = (struct sockaddr_in6 *)iterator->ai_addr;
-                        addr2 = (struct sockaddr_in6 *)itr->ai_addr;
+                        addr2 = (struct sockaddr_in6 *)iteratorNew->ai_addr;
 
                         for (t = 0; t < 16; t++) {
                             if (addr1->sin6_addr.s6_addr[t] !=
@@ -127,7 +119,7 @@
                             }
                         }
                         if (t < 16) {
-                            itr = itr->ai_next;
+                            iteratorNew = iteratorNew->ai_next;
                             continue;
                         } else {
                             skip = 1;
@@ -136,16 +128,16 @@
                     }
                 } else if (iterator->ai_family != AF_INET &&
                            iterator->ai_family != AF_INET6) {
-                    /* we can't handle other family types */
+                    // we can't handle other family types
                     skip = 1;
                     break;
                 }
-                itr = itr->ai_next;
+                iteratorNew = iteratorNew->ai_next;
             }
 
             if (!skip) {
                 struct addrinfo *next
-                    = (struct addrinfo*) malloc(sizeof(struct addrinfo));
+                    = (struct addrinfo *)malloc(sizeof(struct addrinfo));
                 if (!next) {
                     JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed");
                     ret = NULL;
@@ -161,87 +153,81 @@
                 last = next;
                 i++;
                 if (iterator->ai_family == AF_INET) {
-                    inetCount ++;
+                    inetCount++;
                 } else if (iterator->ai_family == AF_INET6) {
-                    inet6Count ++;
+                    inet6Count++;
                 }
             }
             iterator = iterator->ai_next;
         }
-        retLen = i;
-        iterator = resNew;
-        i = 0;
-        ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);
 
+        // allocate array - at this point i contains the number of addresses
+        ret = (*env)->NewObjectArray(env, i, ia_class, NULL);
         if (IS_NULL(ret)) {
             /* we may have memory to free at the end of this */
             goto cleanupAndReturn;
         }
 
-        if (preferIPv6Address == java_net_InetAddress_PREFER_IPV6_VALUE) {
+        if (addressPreference == java_net_InetAddress_PREFER_IPV6_VALUE) {
             inetIndex = inet6Count;
             inet6Index = 0;
-        } else if (preferIPv6Address == java_net_InetAddress_PREFER_IPV4_VALUE) {
+        } else if (addressPreference == java_net_InetAddress_PREFER_IPV4_VALUE) {
             inetIndex = 0;
             inet6Index = inetCount;
-        } else if (preferIPv6Address == java_net_InetAddress_PREFER_SYSTEM_VALUE) {
+        } else if (addressPreference == java_net_InetAddress_PREFER_SYSTEM_VALUE) {
             inetIndex = inet6Index = originalIndex = 0;
         }
 
+        iterator = resNew;
         while (iterator != NULL) {
             if (iterator->ai_family == AF_INET) {
-              jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
-              if (IS_NULL(iaObj)) {
-                ret = NULL;
-                goto cleanupAndReturn;
-              }
-              setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in*)iterator->ai_addr)->sin_addr.s_addr));
-              setInetAddress_hostName(env, iaObj, host);
-              (*env)->SetObjectArrayElement(env, ret, (inetIndex | originalIndex), iaObj);
-              inetIndex ++;
+                jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+                if (IS_NULL(iaObj)) {
+                    ret = NULL;
+                    goto cleanupAndReturn;
+                }
+                setInetAddress_addr(env, iaObj, ntohl(((struct sockaddr_in*)iterator->ai_addr)->sin_addr.s_addr));
+                setInetAddress_hostName(env, iaObj, host);
+                (*env)->SetObjectArrayElement(env, ret, (inetIndex | originalIndex), iaObj);
+                inetIndex++;
             } else if (iterator->ai_family == AF_INET6) {
-              jint scope = 0;
-              jboolean ret1;
-              jobject iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
-              if (IS_NULL(iaObj)) {
-                ret = NULL;
-                goto cleanupAndReturn;
-              }
-              ret1 = setInet6Address_ipaddress(env, iaObj, (jbyte *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
-              if (ret1 == JNI_FALSE) {
-                ret = NULL;
-                goto cleanupAndReturn;
-              }
-              scope = ((struct sockaddr_in6*)iterator->ai_addr)->sin6_scope_id;
-              if (scope != 0) { /* zero is default value, no need to set */
-                setInet6Address_scopeid(env, iaObj, scope);
-              }
-              setInetAddress_hostName(env, iaObj, host);
-              (*env)->SetObjectArrayElement(env, ret, (inet6Index | originalIndex), iaObj);
-              inet6Index ++;
+                jint scope = 0;
+                jboolean ret1;
+                jobject iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
+                if (IS_NULL(iaObj)) {
+                    ret = NULL;
+                    goto cleanupAndReturn;
+                }
+                ret1 = setInet6Address_ipaddress(env, iaObj, (char *)&(((struct sockaddr_in6*)iterator->ai_addr)->sin6_addr));
+                if (ret1 == JNI_FALSE) {
+                    ret = NULL;
+                    goto cleanupAndReturn;
+                }
+                scope = ((struct sockaddr_in6 *)iterator->ai_addr)->sin6_scope_id;
+                if (scope != 0) { // zero is default value, no need to set
+                    setInet6Address_scopeid(env, iaObj, scope);
+                }
+                setInetAddress_hostName(env, iaObj, host);
+                (*env)->SetObjectArrayElement(env, ret, (inet6Index | originalIndex), iaObj);
+                inet6Index++;
             }
-            if (preferIPv6Address == java_net_InetAddress_PREFER_SYSTEM_VALUE) {
+            if (addressPreference == java_net_InetAddress_PREFER_SYSTEM_VALUE) {
                 originalIndex++;
                 inetIndex = inet6Index = 0;
             }
             iterator = iterator->ai_next;
         }
     }
-
 cleanupAndReturn:
-    {
-        struct addrinfo *iterator, *tmp;
-        iterator = resNew;
-        while (iterator != NULL) {
-            tmp = iterator;
-            iterator = iterator->ai_next;
-            free(tmp);
-        }
-        JNU_ReleaseStringPlatformChars(env, host, hostname);
+    JNU_ReleaseStringPlatformChars(env, host, hostname);
+    while (resNew != NULL) {
+        last = resNew;
+        resNew = resNew->ai_next;
+        free(last);
     }
-
-    freeaddrinfo(res);
-
+    if (res != NULL) {
+        freeaddrinfo(res);
+    }
     return ret;
 }
 
@@ -249,57 +235,48 @@
  * Class:     java_net_Inet6AddressImpl
  * Method:    getHostByAddr
  * Signature: (I)Ljava/lang/String;
+ *
+ * Theoretically the UnknownHostException could be enriched with gai error
+ * information. But as it is silently ignored anyway, there's no need for this.
+ * It's only important that either a valid hostname is returned or an
+ * UnknownHostException is thrown.
  */
 JNIEXPORT jstring JNICALL
 Java_java_net_Inet6AddressImpl_getHostByAddr(JNIEnv *env, jobject this,
-                                            jbyteArray addrArray) {
+                                             jbyteArray addrArray) {
     jstring ret = NULL;
-
-    char host[NI_MAXHOST+1];
-    int error = 0;
+    char host[NI_MAXHOST + 1];
     int len = 0;
     jbyte caddr[16];
+    SOCKETADDRESS sa;
 
-    struct sockaddr_in him4;
-    struct sockaddr_in6 him6;
-    struct sockaddr *sa;
+    memset((void *)&sa, 0, sizeof(SOCKETADDRESS));
 
-    /*
-     * For IPv4 addresses construct a sockaddr_in structure.
-     */
+    // construct a sockaddr_in structure (AF_INET or AF_INET6)
     if ((*env)->GetArrayLength(env, addrArray) == 4) {
         jint addr;
         (*env)->GetByteArrayRegion(env, addrArray, 0, 4, caddr);
-        addr = ((caddr[0]<<24) & 0xff000000);
-        addr |= ((caddr[1] <<16) & 0xff0000);
-        addr |= ((caddr[2] <<8) & 0xff00);
+        addr = ((caddr[0] << 24) & 0xff000000);
+        addr |= ((caddr[1] << 16) & 0xff0000);
+        addr |= ((caddr[2] << 8) & 0xff00);
         addr |= (caddr[3] & 0xff);
-        memset((char *) &him4, 0, sizeof(him4));
-        him4.sin_addr.s_addr = htonl(addr);
-        him4.sin_family = AF_INET;
-        sa = (struct sockaddr *) &him4;
-        len = sizeof(him4);
+        sa.sa4.sin_addr.s_addr = htonl(addr);
+        sa.sa4.sin_family = AF_INET;
+        len = sizeof(struct sockaddr_in);
     } else {
-        /*
-         * For IPv6 address construct a sockaddr_in6 structure.
-         */
         (*env)->GetByteArrayRegion(env, addrArray, 0, 16, caddr);
-        memset((char *) &him6, 0, sizeof(him6));
-        memcpy((void *)&(him6.sin6_addr), caddr, sizeof(struct in6_addr) );
-        him6.sin6_family = AF_INET6;
-        sa = (struct sockaddr *) &him6 ;
-        len = sizeof(him6) ;
+        memcpy((void *)&sa.sa6.sin6_addr, caddr, sizeof(struct in6_addr));
+        sa.sa6.sin6_family = AF_INET6;
+        len = sizeof(struct sockaddr_in6);
     }
 
-    error = getnameinfo(sa, len, host, NI_MAXHOST, NULL, 0, NI_NAMEREQD);
-
-    if (!error) {
+    if (getnameinfo(&sa.sa, len, host, NI_MAXHOST, NULL, 0, NI_NAMEREQD)) {
+        JNU_ThrowByName(env, "java/net/UnknownHostException", NULL);
+    } else {
         ret = (*env)->NewStringUTF(env, host);
-        CHECK_NULL_RETURN(ret, NULL);
-    }
-
-    if (ret == NULL) {
-        JNU_ThrowByName(env, JNU_JAVANETPKG "UnknownHostException", NULL);
+        if (ret == NULL) {
+            JNU_ThrowByName(env, "java/net/UnknownHostException", NULL);
+        }
     }
 
     return ret;
@@ -309,99 +286,82 @@
  * ping implementation using tcp port 7 (echo)
  */
 static jboolean
-tcp_ping6(JNIEnv *env,
-          jint timeout,
-          jint ttl,
-          struct sockaddr_in6 him6,
-          struct sockaddr_in6* netif,
-          int len)
+tcp_ping6(JNIEnv *env, SOCKETADDRESS *sa, SOCKETADDRESS *netif, jint timeout,
+          jint ttl)
 {
     jint fd;
+    int connect_rv = -1;
     WSAEVENT hEvent;
-    int connect_rv = -1;
 
+    // open a TCP socket
     fd = NET_Socket(AF_INET6, SOCK_STREAM, 0);
     if (fd == SOCKET_ERROR) {
-        /* note: if you run out of fds, you may not be able to load
-         * the exception class, and get a NoClassDefFoundError
-         * instead.
-         */
-        NET_ThrowNew(env, errno, "Can't create socket");
+        // note: if you run out of fds, you may not be able to load
+        // the exception class, and get a NoClassDefFoundError instead.
+        NET_ThrowNew(env, WSAGetLastError(), "Can't create socket");
         return JNI_FALSE;
     }
 
-    /**
-     * A TTL was specified, let's set the socket option.
-     */
+    // set TTL
     if (ttl > 0) {
-      setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, (const char *)&ttl, sizeof(ttl));
+        setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, (const char *)&ttl, sizeof(ttl));
     }
 
-    /**
-     * A network interface was specified, let's bind to it.
-     */
+    // A network interface was specified, so let's bind to it.
     if (netif != NULL) {
-      if (NET_Bind(fd, (struct sockaddr*)netif, sizeof(struct sockaddr_in6)) < 0) {
-        NET_ThrowNew(env, WSAGetLastError(), "Can't bind socket to interface");
-        closesocket(fd);
-        return JNI_FALSE;
-      }
+        if (bind(fd, &netif->sa, sizeof(struct sockaddr_in6)) < 0) {
+            NET_ThrowNew(env, WSAGetLastError(), "Can't bind socket to interface");
+            closesocket(fd);
+            return JNI_FALSE;
+        }
     }
 
-    /**
-     * Make the socket non blocking.
-     */
+    // Make the socket non blocking so we can use select/poll.
     hEvent = WSACreateEvent();
     WSAEventSelect(fd, hEvent, FD_READ|FD_CONNECT|FD_CLOSE);
 
-    /* no need to use NET_Connect as non-blocking */
-    him6.sin6_port = htons((short) 7); /* Echo port */
-    connect_rv = connect(fd, (struct sockaddr *)&him6, len);
+    sa->sa6.sin6_port = htons(7); // echo port
+    connect_rv = connect(fd, &sa->sa, sizeof(struct sockaddr_in6));
 
-    /**
-     * connection established or refused immediately, either way it means
-     * we were able to reach the host!
-     */
+    // connection established or refused immediately, either way it means
+    // we were able to reach the host!
     if (connect_rv == 0 || WSAGetLastError() == WSAECONNREFUSED) {
         WSACloseEvent(hEvent);
         closesocket(fd);
         return JNI_TRUE;
-    } else {
-        int optlen;
-
-        switch (WSAGetLastError()) {
-        case WSAEHOSTUNREACH:   /* Host Unreachable */
-        case WSAENETUNREACH:    /* Network Unreachable */
-        case WSAENETDOWN:       /* Network is down */
-        case WSAEPFNOSUPPORT:   /* Protocol Family unsupported */
-          WSACloseEvent(hEvent);
-          closesocket(fd);
-          return JNI_FALSE;
-        }
+    }
 
-        if (WSAGetLastError() != WSAEWOULDBLOCK) {
-            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
-                                         "connect failed");
-            WSACloseEvent(hEvent);
-            closesocket(fd);
-            return JNI_FALSE;
-        }
-
-        timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
+    switch (WSAGetLastError()) {
+    case WSAEHOSTUNREACH:   // Host Unreachable
+    case WSAENETUNREACH:    // Network Unreachable
+    case WSAENETDOWN:       // Network is down
+    case WSAEPFNOSUPPORT:   // Protocol Family unsupported
+        WSACloseEvent(hEvent);
+        closesocket(fd);
+        return JNI_FALSE;
+    case WSAEWOULDBLOCK:    // this is expected as we'll probably have to wait
+        break;
+    default:
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "ConnectException",
+                                     "connect failed");
+        WSACloseEvent(hEvent);
+        closesocket(fd);
+        return JNI_FALSE;
+    }
 
-        if (timeout >= 0) {
-          /* has connection been established? */
-          optlen = sizeof(connect_rv);
-          if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void*)&connect_rv,
-                         &optlen) <0) {
+    timeout = NET_Wait(env, fd, NET_WAIT_CONNECT, timeout);
+    if (timeout >= 0) {
+        // connection has been established, check for error condition
+        int optlen = sizeof(connect_rv);
+        if (getsockopt(fd, SOL_SOCKET, SO_ERROR, (void *)&connect_rv,
+                       &optlen) < 0)
+        {
             connect_rv = WSAGetLastError();
-          }
-
-          if (connect_rv == 0 || connect_rv == WSAECONNREFUSED) {
+        }
+        if (connect_rv == 0 || connect_rv == WSAECONNREFUSED) {
             WSACloseEvent(hEvent);
             closesocket(fd);
             return JNI_TRUE;
-          }
         }
     }
     WSACloseEvent(hEvent);
@@ -416,21 +376,18 @@
  * Returns true is an ECHO_REPLY is received, otherwise, false.
  */
 static jboolean
-ping6(JNIEnv *env,
-      struct sockaddr_in6* src,
-      struct sockaddr_in6* dest,
-      jint timeout,
-      HANDLE hIcmpFile)
+ping6(JNIEnv *env, HANDLE hIcmpFile, SOCKETADDRESS *sa,
+      SOCKETADDRESS *netif, jint timeout)
 {
     DWORD dwRetVal = 0;
     char SendData[32] = {0};
     LPVOID ReplyBuffer = NULL;
     DWORD ReplySize = 0;
     IP_OPTION_INFORMATION ipInfo = {255, 0, 0, 0, NULL};
-    struct sockaddr_in6 sa6Source;
+    SOCKETADDRESS dftNetif;
 
     ReplySize = sizeof(ICMPV6_ECHO_REPLY) + sizeof(SendData);
-    ReplyBuffer = (VOID*) malloc(ReplySize);
+    ReplyBuffer = (VOID *)malloc(ReplySize);
     if (ReplyBuffer == NULL) {
         IcmpCloseHandle(hIcmpFile);
         NET_ThrowNew(env, WSAGetLastError(), "Unable to allocate memory");
@@ -438,17 +395,20 @@
     }
 
     //define local source information
-    sa6Source.sin6_addr = in6addr_any;
-    sa6Source.sin6_family = AF_INET6;
-    sa6Source.sin6_flowinfo = 0;
-    sa6Source.sin6_port = 0;
+    if (netif == NULL) {
+        dftNetif.sa6.sin6_addr = in6addr_any;
+        dftNetif.sa6.sin6_family = AF_INET6;
+        dftNetif.sa6.sin6_flowinfo = 0;
+        dftNetif.sa6.sin6_port = 0;
+        netif = &dftNetif;
+    }
 
     dwRetVal = Icmp6SendEcho2(hIcmpFile,    // HANDLE IcmpHandle,
                               NULL,         // HANDLE Event,
                               NULL,         // PIO_APC_ROUTINE ApcRoutine,
                               NULL,         // PVOID ApcContext,
-                              &sa6Source,   // struct sockaddr_in6 *SourceAddress,
-                              dest,         // struct sockaddr_in6 *DestinationAddress,
+                              &netif->sa6,  // struct sockaddr_in6 *SourceAddress,
+                              &sa->sa6,     // struct sockaddr_in6 *DestinationAddress,
                               SendData,     // LPVOID RequestData,
                               sizeof(SendData), // WORD RequestSize,
                               &ipInfo,      // PIP_OPTION_INFORMATION RequestOptions,
@@ -459,11 +419,10 @@
     free(ReplyBuffer);
     IcmpCloseHandle(hIcmpFile);
 
-
-    if (dwRetVal != 0) {
+    if (dwRetVal == 0) { // if the call failed
+        return JNI_FALSE;
+    } else {
         return JNI_TRUE;
-    } else {
-        return JNI_FALSE;
     }
 }
 
@@ -474,75 +433,64 @@
  */
 JNIEXPORT jboolean JNICALL
 Java_java_net_Inet6AddressImpl_isReachable0(JNIEnv *env, jobject this,
-                                           jbyteArray addrArray,
-                                           jint scope,
-                                           jint timeout,
-                                           jbyteArray ifArray,
-                                           jint ttl, jint if_scope) {
+                                            jbyteArray addrArray, jint scope,
+                                            jint timeout, jbyteArray ifArray,
+                                            jint ttl, jint if_scope)
+{
     jbyte caddr[16];
     jint sz;
-    struct sockaddr_in6 him6;
-    struct sockaddr_in6* netif = NULL;
-    struct sockaddr_in6 inf6;
-    int len = 0;
+    SOCKETADDRESS sa, inf, *netif = NULL;
     HANDLE hIcmpFile;
 
-    /*
-     * If IPv6 is not enable, then we can't reach an IPv6 address, can we?
-     * Actually, we probably shouldn't even get here.
-     */
+    // If IPv6 is not enabled, then we can't reach an IPv6 address, can we?
+    // Actually, we probably shouldn't even get here.
     if (!ipv6_available()) {
-      return JNI_FALSE;
+        return JNI_FALSE;
     }
-    /*
-     * If it's an IPv4 address, ICMP won't work with IPv4 mapped address,
-     * therefore, let's delegate to the Inet4Address method.
-     */
+
+    // If it's an IPv4 address, ICMP won't work with IPv4 mapped address,
+    // therefore, let's delegate to the Inet4Address method.
     sz = (*env)->GetArrayLength(env, addrArray);
     if (sz == 4) {
-      return Java_java_net_Inet4AddressImpl_isReachable0(env, this,
-                                                         addrArray,
-                                                         timeout,
-                                                         ifArray, ttl);
+        return Java_java_net_Inet4AddressImpl_isReachable0(env, this,
+                                                           addrArray, timeout,
+                                                           ifArray, ttl);
     }
 
-    memset((char *) caddr, 0, 16);
-    memset((char *) &him6, 0, sizeof(him6));
+    // load address to SOCKETADDRESS
+    memset((char *)caddr, 0, 16);
     (*env)->GetByteArrayRegion(env, addrArray, 0, 16, caddr);
-    memcpy((void *)&(him6.sin6_addr), caddr, sizeof(struct in6_addr) );
-    him6.sin6_family = AF_INET6;
+    memset((char *)&sa, 0, sizeof(SOCKETADDRESS));
+    memcpy((void *)&sa.sa6.sin6_addr, caddr, sizeof(struct in6_addr));
+    sa.sa6.sin6_family = AF_INET6;
     if (scope > 0) {
-      him6.sin6_scope_id = scope;
-    }
-    len = sizeof(struct sockaddr_in6);
-
-    /**
-     * A network interface was specified, let's convert the address
-     */
-    if (!(IS_NULL(ifArray))) {
-      memset((char *) caddr, 0, 16);
-      memset((char *) &inf6, 0, sizeof(inf6));
-      (*env)->GetByteArrayRegion(env, ifArray, 0, 16, caddr);
-      memcpy((void *)&(inf6.sin6_addr), caddr, sizeof(struct in6_addr) );
-      inf6.sin6_family = AF_INET6;
-      inf6.sin6_port = 0;
-      inf6.sin6_scope_id = if_scope;
-      netif = &inf6;
+        sa.sa6.sin6_scope_id = scope;
     }
 
+    // load network interface address to SOCKETADDRESS, if specified
+    if (!(IS_NULL(ifArray))) {
+        memset((char *)caddr, 0, 16);
+        (*env)->GetByteArrayRegion(env, ifArray, 0, 16, caddr);
+        memset((char *)&inf, 0, sizeof(SOCKETADDRESS));
+        memcpy((void *)&inf.sa6.sin6_addr, caddr, sizeof(struct in6_addr));
+        inf.sa6.sin6_family = AF_INET6;
+        inf.sa6.sin6_scope_id = if_scope;
+        netif = &inf;
+    }
+
+    // Let's try to create an ICMP handle.
     hIcmpFile = Icmp6CreateFile();
     if (hIcmpFile == INVALID_HANDLE_VALUE) {
         int err = WSAGetLastError();
         if (err == ERROR_ACCESS_DENIED) {
             // fall back to TCP echo if access is denied to ICMP
-            return tcp_ping6(env, timeout, ttl, him6, netif, len);
+            return tcp_ping6(env, &sa, netif, timeout, ttl);
         } else {
             NET_ThrowNew(env, err, "Unable to create ICMP file handle");
             return JNI_FALSE;
         }
     } else {
-        return ping6(env, netif, &him6, timeout, hIcmpFile);
+        // It didn't fail, so we can use ICMP.
+        return ping6(env, hIcmpFile, &sa, netif, timeout);
     }
-
-    return JNI_FALSE;
 }
--- a/jdk/src/java.datatransfer/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.datatransfer/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines an API for transferring data between and within applications.
+ *
+ * @since 9
  */
 module java.datatransfer {
     exports java.awt.datatransfer;
--- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxPopup.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaComboBoxPopup.java	Thu Mar 16 20:47:03 2017 +0000
@@ -154,9 +154,15 @@
     protected JList<Object> createList() {
         return new JList<Object>(comboBox.getModel()) {
             @Override
+            @SuppressWarnings("deprecation")
             public void processMouseEvent(MouseEvent e) {
                 if (e.isMetaDown()) {
-                    e = new MouseEvent((Component)e.getSource(), e.getID(), e.getWhen(), e.getModifiers() ^ InputEvent.META_MASK, e.getX(), e.getY(), e.getXOnScreen(), e.getYOnScreen(), e.getClickCount(), e.isPopupTrigger(), MouseEvent.NOBUTTON);
+                    e = new MouseEvent((Component) e.getSource(), e.getID(),
+                                       e.getWhen(),
+                                       e.getModifiers() ^ InputEvent.META_MASK,
+                                       e.getX(), e.getY(), e.getXOnScreen(),
+                                       e.getYOnScreen(), e.getClickCount(),
+                                       e.isPopupTrigger(), MouseEvent.NOBUTTON);
                 }
                 super.processMouseEvent(e);
             }
--- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFrameDockIconUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFrameDockIconUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -137,6 +137,7 @@
     }
 
     @Override
+    @SuppressWarnings("deprecation")
     public void mouseEntered(final MouseEvent e) {
         if ((e.getModifiers() & InputEvent.BUTTON1_MASK) != 0) return;
         String title = fFrame.getTitle();
@@ -146,6 +147,7 @@
     }
 
     @Override
+    @SuppressWarnings("deprecation")
     public void mouseExited(final MouseEvent e) {
         if (fDockLabel != null && (e.getModifiers() & InputEvent.BUTTON1_MASK) == 0) fDockLabel.hide();
     }
--- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFrameUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaInternalFrameUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -555,6 +555,7 @@
         }
 
         @Override
+        @SuppressWarnings("deprecation")
         public void mouseDragged(final MouseEvent e) {
 // do not forward drags
 //            if (didForwardEvent(e)) return;
@@ -621,7 +622,7 @@
 
             return didForwardEvent;
         }
-
+        @SuppressWarnings("deprecation")
         boolean didForwardEventInternal(final MouseEvent e) {
             if (fDraggingFrame) return false;
 
@@ -927,11 +928,15 @@
             return (w - x) + (h - y) < 12;
         }
 
+        @SuppressWarnings("deprecation")
         void forwardEventToFrame(final MouseEvent e) {
             final Point pt = new Point();
             final Component c = getComponentToForwardTo(e, pt);
             if (c == null) return;
-            c.dispatchEvent(new MouseEvent(c, e.getID(), e.getWhen(), e.getModifiers(), pt.x, pt.y, e.getClickCount(), e.isPopupTrigger(), e.getButton()));
+            c.dispatchEvent(
+                    new MouseEvent(c, e.getID(), e.getWhen(), e.getModifiers(),
+                                   pt.x, pt.y, e.getClickCount(),
+                                   e.isPopupTrigger(), e.getButton()));
         }
 
         Component getComponentToForwardTo(final MouseEvent e, final Point dst) {
@@ -993,6 +998,7 @@
         public void mouseMoved(final MouseEvent e) { }
 
         @Override
+        @SuppressWarnings("deprecation")
         public void mouseWheelMoved(final MouseWheelEvent e) {
             final Point pt = new Point();
             final Component c = getComponentToForwardTo(e, pt);
--- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaMenuPainter.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaMenuPainter.java	Thu Mar 16 20:47:03 2017 +0000
@@ -74,7 +74,10 @@
         kUCapsLockGlyph = 0x21EA;
 
     static final int ALT_GRAPH_MASK = 1 << 5; // New to Java2
-    static final int sUnsupportedModifiersMask = ~(InputEvent.CTRL_MASK | InputEvent.ALT_MASK | InputEvent.SHIFT_MASK | InputEvent.META_MASK | ALT_GRAPH_MASK);
+    @SuppressWarnings("deprecation")
+    static final int sUnsupportedModifiersMask =
+            ~(InputEvent.CTRL_MASK | InputEvent.ALT_MASK | InputEvent.SHIFT_MASK
+                    | InputEvent.META_MASK | ALT_GRAPH_MASK);
 
     interface Client {
         public void paintBackground(Graphics g, JComponent c, int menuWidth, int menuHeight);
@@ -86,6 +89,7 @@
     }
 
     // Return a string with the proper modifier glyphs
+    @SuppressWarnings("deprecation")
     private static String getKeyModifiersUnicode(final int modifiers, final boolean isLeftToRight) {
         final StringBuilder buf = new StringBuilder(2);
         // Order (from StandardMenuDef.c): control, option(alt), shift, cmd
--- a/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaTabbedPaneCopyFromBasicUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/com/apple/laf/AquaTabbedPaneCopyFromBasicUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -515,6 +515,7 @@
     /**
      * Adds the specified mnemonic at the specified index.
      */
+    @SuppressWarnings("deprecation")
     private void addMnemonic(final int index, final int mnemonic) {
         if (mnemonicToIndexMap == null) {
             initMnemonics();
--- a/jdk/src/java.desktop/macosx/classes/sun/font/CFont.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/sun/font/CFont.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, 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
@@ -211,6 +211,10 @@
         ArrayList<String> listOfString = new ArrayList<String>();
         getCascadeList(nativeFontPtr, listOfString);
 
+        // add JRE "Lucida Sans Regular" to the cascade list to enable fallback
+        // to happen to this JRE font in case the intended glyph is missing in
+        // fonts provided in the CoreText provided cascaded list
+        listOfString.add("Lucida Sans Regular");
         FontManager fm = FontManagerFactory.getInstance();
         int numFonts = 1 + listOfString.size();
         PhysicalFont[] fonts = new PhysicalFont[numFonts];
--- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWComponentPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWComponentPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1224,6 +1224,7 @@
      * Changes the target of the AWTEvent from awt component to appropriate
      * swing delegate.
      */
+    @SuppressWarnings("deprecation")
     private AWTEvent createDelegateEvent(final AWTEvent e) {
         // TODO modifiers should be changed to getModifiers()|getModifiersEx()?
         AWTEvent delegateEvent = null;
--- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWListPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/LWListPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -302,6 +302,7 @@
             }
 
             @Override
+            @SuppressWarnings("deprecation")
             protected void processMouseEvent(final MouseEvent e) {
                 super.processMouseEvent(e);
                 if (e.getID() == MouseEvent.MOUSE_CLICKED && e.getClickCount() == 2) {
@@ -314,6 +315,7 @@
             }
 
             @Override
+            @SuppressWarnings("deprecation")
             protected void processKeyEvent(final KeyEvent e) {
                 super.processKeyEvent(e);
                 if (e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_ENTER) {
--- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CDragSourceContextPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -93,6 +93,7 @@
         InputEvent         triggerEvent = trigger.getTriggerEvent();
 
         Point dragOrigin = new Point(trigger.getDragOrigin());
+        @SuppressWarnings("deprecation")
         int extModifiers = (triggerEvent.getModifiers() | triggerEvent.getModifiersEx());
         long timestamp   = triggerEvent.getWhen();
         int clickCount   = ((triggerEvent instanceof MouseEvent) ? (((MouseEvent) triggerEvent).getClickCount()) : 1);
--- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CMenuItem.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CMenuItem.java	Thu Mar 16 20:47:03 2017 +0000
@@ -63,7 +63,7 @@
         CMenuComponent parent = (CMenuComponent)LWToolkit.targetToPeer(getTarget().getParent());
         return parent.executeGet(ptr->nativeCreate(ptr, isSeparator()));
     }
-
+    @SuppressWarnings("deprecation")
     public void setLabel(String label, char keyChar, int keyCode, int modifiers) {
         int keyMask = modifiers;
         if (keyCode == KeyEvent.VK_UNDEFINED) {
--- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java	Thu Mar 16 20:47:03 2017 +0000
@@ -265,9 +265,8 @@
 
     static class DeltaAccumulator {
 
-        static final double MIN_THRESHOLD = 0.1;
-        static final double MAX_THRESHOLD = 0.5;
         double accumulatedDelta;
+        boolean accumulate;
 
         int getRoundedDelta(double delta, int scrollPhase) {
 
@@ -278,25 +277,23 @@
                     roundDelta = delta > 0 ? 1 : -1;
                 }
             } else { // trackpad
-                boolean begin = scrollPhase == NSEvent.SCROLL_PHASE_BEGAN;
-                boolean end = scrollPhase == NSEvent.SCROLL_MASK_PHASE_ENDED
-                        || scrollPhase == NSEvent.SCROLL_MASK_PHASE_CANCELLED;
-
-                if (begin) {
+                if (scrollPhase == NSEvent.SCROLL_PHASE_BEGAN) {
                     accumulatedDelta = 0;
+                    accumulate = true;
                 }
-
-                accumulatedDelta += delta;
+                else if (scrollPhase == NSEvent.SCROLL_PHASE_MOMENTUM_BEGAN) {
+                    accumulate = true;
+                }
+                if (accumulate) {
 
-                double absAccumulatedDelta = Math.abs(accumulatedDelta);
-                if (absAccumulatedDelta > MAX_THRESHOLD) {
+                    accumulatedDelta += delta;
+
                     roundDelta = (int) Math.round(accumulatedDelta);
+
                     accumulatedDelta -= roundDelta;
-                }
 
-                if (end) {
-                    if (roundDelta == 0 && absAccumulatedDelta > MIN_THRESHOLD) {
-                        roundDelta = accumulatedDelta > 0 ? 1 : -1;
+                    if (scrollPhase == NSEvent.SCROLL_PHASE_ENDED) {
+                        accumulate = false;
                     }
                 }
             }
--- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPopupMenu.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPopupMenu.java	Thu Mar 16 20:47:03 2017 +0000
@@ -46,6 +46,7 @@
     private native long nativeShowPopupMenu(long modelPtr, int x, int y);
 
     @Override
+    @SuppressWarnings("deprecation")
     public void show(Event e) {
         Component origin = (Component)e.target;
         if (origin != null) {
--- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterDialogPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/CPrinterDialogPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -68,6 +68,7 @@
     public void setResizable(boolean resizable) {}
     public void setEnabled(boolean enable) {}
     public void setBounds(int x, int y, int width, int height) {}
+    @SuppressWarnings("deprecation")
     public boolean handleEvent(Event e) { return false; }
     public void setForeground(Color c) {}
     public void setBackground(Color c) {}
--- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/LWCToolkit.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/LWCToolkit.java	Thu Mar 16 20:47:03 2017 +0000
@@ -532,6 +532,7 @@
      * @since     1.1
      */
     @Override
+    @SuppressWarnings("deprecation")
     public int getMenuShortcutKeyMask() {
         return Event.META_MASK;
     }
@@ -768,6 +769,7 @@
      * stroke.
      */
     @Override
+    @SuppressWarnings("deprecation")
     public int getFocusAcceleratorKeyMask() {
         return InputEvent.CTRL_MASK | InputEvent.ALT_MASK;
     }
@@ -777,6 +779,7 @@
      * printable character.
      */
     @Override
+    @SuppressWarnings("deprecation")
     public boolean isPrintableCharacterModifiersMask(int mods) {
         return ((mods & (InputEvent.META_MASK | InputEvent.CTRL_MASK)) == 0);
     }
--- a/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/NSEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/classes/sun/lwawt/macosx/NSEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -36,8 +36,8 @@
     static final int SCROLL_PHASE_UNSUPPORTED = 1;
     static final int SCROLL_PHASE_BEGAN = 2;
     static final int SCROLL_PHASE_CONTINUED = 3;
-    static final int SCROLL_MASK_PHASE_CANCELLED = 4;
-    static final int SCROLL_MASK_PHASE_ENDED = 5;
+    static final int SCROLL_PHASE_MOMENTUM_BEGAN = 4;
+    static final int SCROLL_PHASE_ENDED = 5;
 
     private int type;
     private int modifierFlags;
--- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/AWTView.m	Thu Mar 16 20:47:03 2017 +0000
@@ -381,6 +381,13 @@
     } else {
         clickCount = [event clickCount];
     }
+
+    jdouble deltaX = [event deltaX];
+    jdouble deltaY = [event deltaY];
+    if ([AWTToolkit hasPreciseScrollingDeltas: event]) {
+        deltaX = [event scrollingDeltaX] * 0.1;
+        deltaY = [event scrollingDeltaY] * 0.1;
+    }
     
     static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent");
     static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDDI)V");
@@ -391,8 +398,8 @@
                                   [event buttonNumber],
                                   (jint)localPoint.x, (jint)localPoint.y,
                                   (jint)absP.x, (jint)absP.y,
-                                  [event deltaY],
-                                  [event deltaX],
+                                  deltaY,
+                                  deltaX,
                                   [AWTToolkit scrollStateWithEvent: event]);
     CHECK_NULL(jEvent);
     
--- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.m	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/CTrayIcon.m	Thu Mar 16 20:47:03 2017 +0000
@@ -139,7 +139,14 @@
     jint clickCount;
 
     clickCount = [event clickCount];
-        
+
+    jdouble deltaX = [event deltaX];
+    jdouble deltaY = [event deltaY];
+    if ([AWTToolkit hasPreciseScrollingDeltas: event]) {
+        deltaX = [event scrollingDeltaX] * 0.1;
+        deltaY = [event scrollingDeltaY] * 0.1;
+    }
+
     static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent");
     static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDDI)V");
     jobject jEvent = JNFNewObject(env, jctor_NSEvent,
@@ -149,8 +156,8 @@
                                   [event buttonNumber],
                                   (jint)localPoint.x, (jint)localPoint.y,
                                   (jint)absP.x, (jint)absP.y,
-                                  [event deltaY],
-                                  [event deltaX],
+                                  deltaY,
+                                  deltaX,
                                   [AWTToolkit scrollStateWithEvent: event]);
     CHECK_NULL(jEvent);
 
--- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaComponentAccessibility.m	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/JavaComponentAccessibility.m	Thu Mar 16 20:47:03 2017 +0000
@@ -136,7 +136,7 @@
         fJavaRole = [javaRole retain];
 
         fAccessible = (*env)->NewWeakGlobalRef(env, accessible);
-        
+        (*env)->ExceptionClear(env); // in case of OOME
         jobject jcomponent = [(AWTView *)fView awtComponent:env];
         fComponent = (*env)->NewWeakGlobalRef(env, jcomponent);
         (*env)->DeleteLocalRef(env, jcomponent);
--- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/LWCToolkit.h	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/LWCToolkit.h	Thu Mar 16 20:47:03 2017 +0000
@@ -42,6 +42,7 @@
 + (long) getEventCount;
 + (void) eventCountPlusPlus;
 + (jint) scrollStateWithEvent: (NSEvent*) event;
++ (BOOL) hasPreciseScrollingDeltas: (NSEvent*) event;
 @end
 
 /*
--- a/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/LWCToolkit.m	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/macosx/native/libawt_lwawt/awt/LWCToolkit.m	Thu Mar 16 20:47:03 2017 +0000
@@ -47,7 +47,7 @@
 #define SCROLL_PHASE_UNSUPPORTED 1
 #define SCROLL_PHASE_BEGAN 2
 #define SCROLL_PHASE_CONTINUED 3
-#define SCROLL_PHASE_CANCELLED 4
+#define SCROLL_PHASE_MOMENTUM_BEGAN 4
 #define SCROLL_PHASE_ENDED 5
 
 int gNumberOfButtons;
@@ -85,16 +85,33 @@
         return 0;
     }
     
-    NSEventPhase phase = [event phase];
-    NSEventPhase momentumPhase = [event momentumPhase];
-    
-    if (!phase && !momentumPhase) return SCROLL_PHASE_UNSUPPORTED;
-    switch (phase) {
-        case NSEventPhaseBegan: return SCROLL_PHASE_BEGAN;
-        case NSEventPhaseCancelled: return SCROLL_PHASE_CANCELLED;
-        case NSEventPhaseEnded: return SCROLL_PHASE_ENDED;
-        default: return SCROLL_PHASE_CONTINUED;
+    if ([event phase]) {
+        // process a phase of manual scrolling
+        switch ([event phase]) {
+            case NSEventPhaseBegan: return SCROLL_PHASE_BEGAN;
+            case NSEventPhaseCancelled: return SCROLL_PHASE_ENDED;
+            case NSEventPhaseEnded: return SCROLL_PHASE_ENDED;
+            default: return SCROLL_PHASE_CONTINUED;
+        }
     }
+
+    if ([event momentumPhase]) {
+        // process a phase of automatic scrolling
+        switch ([event momentumPhase]) {
+            case NSEventPhaseBegan: return SCROLL_PHASE_MOMENTUM_BEGAN;
+            case NSEventPhaseCancelled: return SCROLL_PHASE_ENDED;
+            case NSEventPhaseEnded: return SCROLL_PHASE_ENDED;
+            default: return SCROLL_PHASE_CONTINUED;
+        }
+    }
+    // phase and momentum phase both are not set
+    return SCROLL_PHASE_UNSUPPORTED;
+}
+
++ (BOOL) hasPreciseScrollingDeltas: (NSEvent*) event {
+    return [event type] == NSScrollWheel
+        && [event respondsToSelector:@selector(hasPreciseScrollingDeltas)]
+        && [event hasPreciseScrollingDeltas];
 }
 @end
 
--- a/jdk/src/java.desktop/share/classes/com/sun/awt/AWTUtilities.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/com/sun/awt/AWTUtilities.java	Thu Mar 16 20:47:03 2017 +0000
@@ -456,8 +456,7 @@
                     "The component argument should not be null.");
         }
 
-        AWTAccessor.getComponentAccessor().setMixingCutoutShape(component,
-                shape);
+        component.setMixingCutoutShape(shape);
     }
 }
 
--- a/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageReader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/com/sun/imageio/plugins/bmp/BMPImageReader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1439,51 +1439,72 @@
         decodeRLE8(imSize, padding, values, bdata);
     }
 
+    private boolean copyRLE8ScanlineToDst(int lineNo,
+                                          byte[] val,
+                                          byte[] bdata) {
+        // Return value
+        boolean isSuccess = false;
+
+        // Reusing the code to copy 1 row of pixels or scanline to required
+        // destination buffer.
+        if (lineNo >= sourceRegion.y &&
+            lineNo < sourceRegion.y + sourceRegion.height) {
+            if (noTransform) {
+                int pos = lineNo * width;
+                for(int i = 0; i < width; i++)
+                    bdata[pos++] = val[i];
+                processImageUpdate(bi, 0, lineNo,
+                                   destinationRegion.width, 1, 1, 1,
+                                   new int[]{0});
+                isSuccess = true;
+            } else if ((lineNo - sourceRegion.y) % scaleY == 0) {
+                int lineStride =
+                    ((ComponentSampleModel)sampleModel).getScanlineStride();
+                int currentLine = (lineNo - sourceRegion.y) / scaleY +
+                    destinationRegion.y;
+                int pos = currentLine * lineStride;
+                pos += destinationRegion.x;
+                for (int i = sourceRegion.x;
+                     i < sourceRegion.x + sourceRegion.width;
+                     i += scaleX)
+                    bdata[pos++] = val[i];
+                processImageUpdate(bi, 0, currentLine,
+                                   destinationRegion.width, 1, 1, 1,
+                                   new int[]{0});
+                isSuccess = true;
+            }
+            // Ensure to reset the scanline buffer once the copy is complete.
+            for(int scIndex = 0; scIndex < width; scIndex++) {
+                val[scIndex] = 0;
+            }
+        }
+
+        return isSuccess;
+    }
+
     private void decodeRLE8(int imSize,
                             int padding,
                             byte[] values,
                             byte[] bdata) throws IOException {
 
-        byte val[] = new byte[width * height];
+        byte val[] = new byte[width];
         int count = 0, l = 0;
         int value;
         boolean flag = false;
         int lineNo = isBottomUp ? height - 1 : 0;
-        int lineStride =
-            ((ComponentSampleModel)sampleModel).getScanlineStride();
         int finished = 0;
 
-        while (count != imSize) {
+        // Ensure image source has sufficient data to decode
+        while ((count + 1) < imSize) {
             value = values[count++] & 0xff;
             if (value == 0) {
                 switch(values[count++] & 0xff) {
 
                 case 0:
                     // End-of-scanline marker
-                    if (lineNo >= sourceRegion.y &&
-                        lineNo < sourceRegion.y + sourceRegion.height) {
-                        if (noTransform) {
-                            int pos = lineNo * width;
-                            for(int i = 0; i < width; i++)
-                                bdata[pos++] = val[i];
-                            processImageUpdate(bi, 0, lineNo,
-                                               destinationRegion.width, 1, 1, 1,
-                                               new int[]{0});
-                            finished++;
-                        } else if ((lineNo - sourceRegion.y) % scaleY == 0) {
-                            int currentLine = (lineNo - sourceRegion.y) / scaleY +
-                                destinationRegion.y;
-                            int pos = currentLine * lineStride;
-                            pos += destinationRegion.x;
-                            for (int i = sourceRegion.x;
-                                 i < sourceRegion.x + sourceRegion.width;
-                                 i += scaleX)
-                                bdata[pos++] = val[i];
-                            processImageUpdate(bi, 0, currentLine,
-                                               destinationRegion.width, 1, 1, 1,
-                                               new int[]{0});
-                            finished++;
-                        }
+                    // Copy the decoded scanline to destination
+                    if (copyRLE8ScanlineToDst(lineNo, val, bdata)) {
+                        finished++;
                     }
                     processImageProgress(100.0F * finished / destinationRegion.height);
                     lineNo += isBottomUp ? -1 : 1;
@@ -1492,26 +1513,62 @@
                     if (abortRequested()) {
                         flag = true;
                     }
-
                     break;
 
                 case 1:
                     // End-of-RLE marker
                     flag = true;
+
+                    // Check if the last decoded scanline was copied to
+                    // destination bitmap
+                    if (l != 0) {
+                        // Copy the decoded scanline to destination
+                        if (copyRLE8ScanlineToDst(lineNo, val, bdata)) {
+                            finished++;
+                        }
+                        processImageProgress(100.0F * finished / destinationRegion.height);
+                        lineNo += isBottomUp ? -1 : 1;
+                        l = 0;
+                    }
                     break;
 
                 case 2:
                     // delta or vector marker
-                    int xoff = values[count++] & 0xff;
-                    int yoff = values[count] & 0xff;
-                    // Move to the position xoff, yoff down
-                    l += xoff + yoff*width;
+                    if ((count+1) < imSize) {
+                        int xoff = values[count++] & 0xff;
+                        int yoff = values[count++] & 0xff;
+
+                        // Check if the yOffset shifts the decoding to another
+                        // row. In such cases, the decoded pixels in scanline
+                        // buffer-val must be copied to the destination image.
+                        if (yoff != 0) {
+                            // Copy the decoded scanline to destination
+                            if (copyRLE8ScanlineToDst(lineNo, val, bdata)) {
+                                finished++;
+                            }
+                            processImageProgress(100.0F * finished
+                                                 / destinationRegion.height);
+                            lineNo += isBottomUp ? -yoff : yoff;
+                        }
+
+                        // Move to the position xoff, yoff down
+                        l += xoff + yoff*width;
+                        l %= width;
+                    }
                     break;
 
                 default:
                     int end = values[count-1] & 0xff;
-                    for (int i=0; i<end; i++) {
-                        val[l++] = (byte)(values[count++] & 0xff);
+                    byte readByte = 0;
+                    // Ensure to check if the source index-count, does not
+                    // exceed the source image size
+                    for (int i=0; (i < end) && (count < imSize); i++) {
+                        readByte = (byte)(values[count++] & 0xff);
+                        // Ensure to check if scanline index-l, does not
+                        // exceed the scanline buffer size (width of image)
+                        if (l < width) {
+                            val[l++] = readByte;
+                        }
                     }
 
                     // Whenever end pixels can fit into odd number of bytes,
@@ -1519,10 +1576,16 @@
                     if ((end & 1) == 1) {
                         count++;
                     }
+                    break;
                 }
             } else {
-                for (int i=0; i<value; i++) {
-                    val[l++] = (byte)(values[count] & 0xff);
+                // Encoded mode
+                // Ensure to check if the source index-count, does not
+                // exceed the source image size
+                if (count < imSize) {
+                    for (int i=0; (i < value) && (l < width); i++) {
+                        val[l++] = (byte)(values[count] & 0xff);
+                    }
                 }
 
                 count++;
--- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifDesktopIconUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifDesktopIconUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -236,7 +236,7 @@
                 }
             });
         }
-
+        @SuppressWarnings("deprecation")
         void forwardEventToParent(MouseEvent e) {
             getParent().dispatchEvent(new MouseEvent(
                 getParent(), e.getID(), e.getWhen(), e.getModifiers(),
@@ -329,7 +329,7 @@
                 }
             });
         }
-
+        @SuppressWarnings("deprecation")
         void forwardEventToParent(MouseEvent e) {
             getParent().dispatchEvent(new MouseEvent(
                 getParent(), e.getID(), e.getWhen(), e.getModifiers(),
--- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifGraphicsUtils.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifGraphicsUtils.java	Thu Mar 16 20:47:03 2017 +0000
@@ -139,10 +139,11 @@
     }
 
   /**
-   * This method is not being used to paint menu item since
+   * @deprecated This method is not being used to paint menu item since
    * 6.0 This code left for compatibility only. Do not use or
    * override it, this will not cause any visible effect.
    */
+  @Deprecated(since = "9")
   public static void paintMenuItem(Graphics g, JComponent c,
                                    Icon checkIcon, Icon arrowIcon,
                                    Color background, Color foreground,
--- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifInternalFrameTitlePane.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifInternalFrameTitlePane.java	Thu Mar 16 20:47:03 2017 +0000
@@ -361,7 +361,7 @@
                 }
             });
         }
-
+        @SuppressWarnings("deprecation")
         void forwardEventToParent(MouseEvent e) {
             getParent().dispatchEvent(new MouseEvent(
                 getParent(), e.getID(), e.getWhen(), e.getModifiers(),
--- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifLookAndFeel.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifLookAndFeel.java	Thu Mar 16 20:47:03 2017 +0000
@@ -523,7 +523,8 @@
 
         Object optionPaneMessageAreaBorder = new BorderUIResource.EmptyBorderUIResource(10,10,12,10);
 
-
+        @SuppressWarnings("deprecation")
+        final int metaMask = KeyEvent.META_MASK;
         Object[] defaults = {
 
             "Desktop.background", table.get("desktop"),
@@ -635,8 +636,7 @@
             "Menu.submenuPopupOffsetX", -2,
             "Menu.submenuPopupOffsetY", 3,
             "Menu.shortcutKeys", new int[]{
-                SwingUtilities2.getSystemMnemonicKeyMask(),
-                KeyEvent.META_MASK
+                SwingUtilities2.getSystemMnemonicKeyMask(), metaMask
             },
             "Menu.cancelMode", "hideMenuTree",
 
--- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifPopupMenuUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifPopupMenuUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -107,6 +107,7 @@
         };
     }
 
+    @SuppressWarnings("deprecation")
     public boolean isPopupTrigger(MouseEvent e) {
         return ((e.getID()==MouseEvent.MOUSE_PRESSED)
                 && ((e.getModifiers() & MouseEvent.BUTTON3_MASK)!=0));
--- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifTextUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/motif/MotifTextUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -155,6 +155,7 @@
     /**
      * Default bindings all keymaps implementing the Motif feel.
      */
+    @SuppressWarnings("deprecation")
     static final JTextComponent.KeyBinding[] defaultBindings = {
         new JTextComponent.KeyBinding(KeyStroke.getKeyStroke(KeyEvent.VK_INSERT,
                                                                     InputEvent.CTRL_MASK),
--- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsRootPaneUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsRootPaneUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -165,8 +165,11 @@
         }
 
         public boolean postProcessKeyEvent(KeyEvent ev) {
-            if(ev.isConsumed()) {
-                // do not manage consumed event
+            if(ev.isConsumed() && ev.getKeyCode() != KeyEvent.VK_ALT) {
+                // mnemonic combination, it's consumed, but we need
+                // set altKeyPressed to false, otherwise after selection
+                // component by mnemonic combination a menu will be open
+                altKeyPressed = false;
                 return false;
             }
             if (ev.getKeyCode() == KeyEvent.VK_ALT) {
--- a/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTabbedPaneUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/com/sun/java/swing/plaf/windows/WindowsTabbedPaneUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -63,6 +63,7 @@
 
     private boolean contentOpaque = true;
 
+    @SuppressWarnings("deprecation")
     protected void installDefaults() {
         super.installDefaults();
         contentOpaque = UIManager.getBoolean("TabbedPane.contentOpaque");
--- a/jdk/src/java.desktop/share/classes/java/awt/AWTEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/AWTEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -292,8 +292,12 @@
 
     /**
      * Constructs an AWTEvent object from the parameters of a 1.0-style event.
+     *
      * @param event the old-style event
+     * @deprecated It is recommended that {@link #AWTEvent(Object, int)} be used
+     *             instead
      */
+    @Deprecated(since = "9")
     public AWTEvent(Event event) {
         this(event.target, event.id);
     }
@@ -436,6 +440,7 @@
      * event class in java.awt.event because we don't want to make
      * it public and it needs to be called from java.awt.
      */
+    @SuppressWarnings("deprecation")
     Event convertToOld() {
         Object src = getSource();
         int newid = id;
--- a/jdk/src/java.desktop/share/classes/java/awt/AWTKeyStroke.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/AWTKeyStroke.java	Thu Mar 16 20:47:03 2017 +0000
@@ -350,6 +350,7 @@
      * @throws NullPointerException if {@code anEvent} is null
      * @return the {@code AWTKeyStroke} that precipitated the event
      */
+    @SuppressWarnings("deprecation")
     public static AWTKeyStroke getAWTKeyStrokeForEvent(KeyEvent anEvent) {
         int id = anEvent.getID();
         switch(id) {
@@ -397,6 +398,7 @@
      * @throws IllegalArgumentException if {@code s} is {@code null},
      *        or is formatted incorrectly
      */
+    @SuppressWarnings("deprecation")
     public static AWTKeyStroke getAWTKeyStroke(String s) {
         if (s == null) {
             throw new IllegalArgumentException("String cannot be null");
@@ -708,6 +710,7 @@
         }
     }
 
+    @SuppressWarnings("deprecation")
     private static int mapOldModifiers(int modifiers) {
         if ((modifiers & InputEvent.SHIFT_MASK) != 0) {
             modifiers |= InputEvent.SHIFT_DOWN_MASK;
@@ -737,6 +740,7 @@
         return modifiers;
     }
 
+    @SuppressWarnings("deprecation")
     private static int mapNewModifiers(int modifiers) {
         if ((modifiers & InputEvent.SHIFT_DOWN_MASK) != 0) {
             modifiers |= InputEvent.SHIFT_MASK;
--- a/jdk/src/java.desktop/share/classes/java/awt/Component.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/Component.java	Thu Mar 16 20:47:03 2017 +0000
@@ -5036,6 +5036,7 @@
      *
      * Returns whether or not event was dispatched to an ancestor
      */
+    @SuppressWarnings("deprecation")
     boolean dispatchMouseWheelToAncestor(MouseWheelEvent e) {
         int newX, newY;
         newX = e.getX() + getX(); // Coordinates take into account at least
@@ -10379,7 +10380,11 @@
     }
 
     /**
-     * Sets a 'mixing-cutout' shape for the given component.
+     * Sets a 'mixing-cutout' shape for this lightweight component.
+     *
+     * This method is used exclusively for the purposes of the
+     * Heavyweight/Lightweight Components Mixing feature and will
+     * have no effect if applied to a heavyweight component.
      *
      * By default a lightweight component is treated as an opaque rectangle for
      * the purposes of the Heavyweight/Lightweight Components Mixing feature.
@@ -10392,7 +10397,7 @@
      * <li>{@code null} - reverts the default cutout shape (the rectangle equal
      * to the component's {@code getBounds()})
      * <li><i>empty-shape</i> - does not cut out anything from heavyweight
-     * components. This makes the given lightweight component effectively
+     * components. This makes this lightweight component effectively
      * transparent. Note that descendants of the lightweight component still
      * affect the shapes of heavyweight components.  An example of an
      * <i>empty-shape</i> is {@code new Rectangle()}.
@@ -10406,16 +10411,11 @@
      * for the given glass pane component.  If a developer needs some other
      * 'mixing-cutout' shape for the glass pane (which is rare), this must be
      * changed manually after installing the glass pane to the root pane.
-     * <p>
-     * Note that the 'mixing-cutout' shape neither affects painting, nor the
-     * mouse events handling for the given component. It is used exclusively
-     * for the purposes of the Heavyweight/Lightweight Components Mixing
-     * feature.
      *
      * @param shape the new 'mixing-cutout' shape
      * @since 9
      */
-    void setMixingCutoutShape(Shape shape) {
+    public void setMixingCutoutShape(Shape shape) {
         Region region = shape == null ? null : Region.getInstance(shape, null);
 
         synchronized (getTreeLock()) {
--- a/jdk/src/java.desktop/share/classes/java/awt/Container.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/Container.java	Thu Mar 16 20:47:03 2017 +0000
@@ -4728,6 +4728,7 @@
      * Listen for drag events posted in other hw components so we can
      * track enter/exit regardless of where a drag originated
      */
+    @SuppressWarnings("deprecation")
     public void eventDispatched(AWTEvent e) {
         boolean isForeignDrag = (e instanceof MouseEvent) &&
                                 !(e instanceof SunDropTargetEvent) &&
@@ -4826,6 +4827,7 @@
      * If the target has been removed, we don't bother to send the
      * message.
      */
+    @SuppressWarnings("deprecation")
     void retargetMouseEvent(Component target, int id, MouseEvent e) {
         if (target == null) {
             return; // mouse is over another hw component or target is disabled
--- a/jdk/src/java.desktop/share/classes/java/awt/Desktop.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/Desktop.java	Thu Mar 16 20:47:03 2017 +0000
@@ -335,7 +335,7 @@
      * most of the platforms support the {@link Desktop.Action#OPEN}
      * action.  But for a specific file, there may not be an
      * application registered to open it.  In this case, {@link
-     * #isSupported} may return {@code true}, but the corresponding
+     * #isSupported(Action)} may return {@code true}, but the corresponding
      * action method will throw an {@link IOException}.
      *
      * @param action the specified {@link Action}
@@ -720,7 +720,7 @@
      * default behavior.
      *
      * @param aboutHandler the handler to respond to the
-     * {@link java.awt.desktop.AboutHandler#handleAbout} )} message
+     * {@link java.awt.desktop.AboutHandler#handleAbout(AboutEvent)} message
      *
      * @throws SecurityException if a security manager exists and it
      * denies the
@@ -828,7 +828,7 @@
      * open a URL.
      *
      * Setting the handler to {@code null} causes all
-     * {@link OpenURIHandler#openURI(AppEvent.OpenURIEvent)} requests to be
+     * {@link OpenURIHandler#openURI(OpenURIEvent)} requests to be
      * enqueued until another handler is set.
      *
      * @implNote Please note that for Mac OS, notifications
--- a/jdk/src/java.desktop/share/classes/java/awt/Event.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/Event.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2013, 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
@@ -24,8 +24,7 @@
  */
 package java.awt;
 
-import java.awt.event.*;
-import java.io.*;
+import java.awt.event.KeyEvent;
 
 /**
  * <b>NOTE:</b> The {@code Event} class is obsolete and is
@@ -56,9 +55,12 @@
  * {@code Event} class ({@code PGUP},
  * {@code PGDN}, {@code F1}, {@code F2}, etc).
  *
+ * @deprecated It is recommended that {@code AWTEvent} and its subclasses be
+ *             used instead
  * @author     Sami Shaio
  * @since      1.0
  */
+@Deprecated(since = "9")
 public class Event implements java.io.Serializable {
     private transient long data;
 
--- a/jdk/src/java.desktop/share/classes/java/awt/KeyboardFocusManager.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/KeyboardFocusManager.java	Thu Mar 16 20:47:03 2017 +0000
@@ -415,6 +415,7 @@
      * Initializes a KeyboardFocusManager.
      */
     public KeyboardFocusManager() {
+        @SuppressWarnings("deprecation")
         AWTKeyStroke[][] defaultFocusTraversalKeyStrokes = {
                 {
                         AWTKeyStroke.getAWTKeyStroke(KeyEvent.VK_TAB, 0, false),
--- a/jdk/src/java.desktop/share/classes/java/awt/MenuBar.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/MenuBar.java	Thu Mar 16 20:47:03 2017 +0000
@@ -375,6 +375,7 @@
      * keydown).  Returns true if there is an associated
      * keyboard event.
      */
+    @SuppressWarnings("deprecation")
     boolean handleShortcut(KeyEvent e) {
         // Is it a key event?
         int id = e.getID();
--- a/jdk/src/java.desktop/share/classes/java/awt/MenuComponent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/MenuComponent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -379,6 +379,7 @@
             }
 
         } else { // backward compatibility
+            @SuppressWarnings("deprecation")
             Event olde = e.convertToOld();
             if (olde != null) {
                 postEvent(olde);
--- a/jdk/src/java.desktop/share/classes/java/awt/MenuItem.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/MenuItem.java	Thu Mar 16 20:47:03 2017 +0000
@@ -435,6 +435,7 @@
      * keydown) and the item is enabled.
      * Returns true if there is an associated shortcut.
      */
+    @SuppressWarnings("deprecation")
     boolean handleShortcut(KeyEvent e) {
         MenuShortcut s = new MenuShortcut(e.getKeyCode(),
                              (e.getModifiers() & InputEvent.SHIFT_MASK) > 0);
--- a/jdk/src/java.desktop/share/classes/java/awt/MenuShortcut.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/MenuShortcut.java	Thu Mar 16 20:47:03 2017 +0000
@@ -180,6 +180,7 @@
      * @return a string representation of this MenuShortcut.
      * @since 1.1
      */
+    @SuppressWarnings("deprecation")
     public String toString() {
         int modifiers = 0;
         if (!GraphicsEnvironment.isHeadless()) {
--- a/jdk/src/java.desktop/share/classes/java/awt/PopupMenu.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/PopupMenu.java	Thu Mar 16 20:47:03 2017 +0000
@@ -154,6 +154,7 @@
      *                parent's hierarchy
      * @exception RuntimeException if the parent is not showing on screen
      */
+    @SuppressWarnings("deprecation")
     public void show(Component origin, int x, int y) {
         // Use localParent for thread safety.
         MenuContainer localParent = parent;
--- a/jdk/src/java.desktop/share/classes/java/awt/Robot.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/Robot.java	Thu Mar 16 20:47:03 2017 +0000
@@ -137,6 +137,7 @@
         initLegalButtonMask();
     }
 
+    @SuppressWarnings("deprecation")
     private static synchronized void initLegalButtonMask() {
         if (LEGAL_BUTTON_MASK != 0) return;
 
--- a/jdk/src/java.desktop/share/classes/java/awt/Toolkit.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/Toolkit.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1067,6 +1067,7 @@
      * @see       java.awt.MenuShortcut
      * @since     1.1
      */
+    @SuppressWarnings("deprecation")
     public int getMenuShortcutKeyMask() throws HeadlessException {
         GraphicsEnvironment.checkHeadless();
 
--- a/jdk/src/java.desktop/share/classes/java/awt/desktop/AppForegroundEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/desktop/AppForegroundEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -30,8 +30,8 @@
  * Event sent when the application has become the foreground app, and when it is
  * no longer the foreground app.
  *
- * @see AppForegroundListener#appRaisedToForeground(AppEvent.AppForegroundEvent)
- * @see AppForegroundListener#appMovedToBackground(AppEvent.AppForegroundEvent)
+ * @see AppForegroundListener#appRaisedToForeground(AppForegroundEvent)
+ * @see AppForegroundListener#appMovedToBackground(AppForegroundEvent)
  *
  * @since 9
  */
--- a/jdk/src/java.desktop/share/classes/java/awt/desktop/AppHiddenEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/desktop/AppHiddenEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -29,8 +29,8 @@
 /**
  * Event sent when the application has been hidden or shown.
  *
- * @see AppHiddenListener#appHidden(AppEvent.AppHiddenEvent)
- * @see AppHiddenListener#appUnhidden(AppEvent.AppHiddenEvent)
+ * @see AppHiddenListener#appHidden(AppHiddenEvent)
+ * @see AppHiddenListener#appUnhidden(AppHiddenEvent)
  *
  * @since 9
  */
--- a/jdk/src/java.desktop/share/classes/java/awt/desktop/AppReopenedEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/desktop/AppReopenedEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -29,7 +29,7 @@
 /**
  * Event sent when the application is asked to re-open itself.
  *
- * @see AppReopenedListener#appReopened(AppEvent.AppReopenedEvent)
+ * @see AppReopenedListener#appReopened(AppReopenedEvent)
  *
  * @since 9
  */
--- a/jdk/src/java.desktop/share/classes/java/awt/desktop/OpenURIEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/desktop/OpenURIEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -31,7 +31,7 @@
 /**
  * Event sent when the app is asked to open a {@code URI}.
  *
- * @see OpenURIHandler#openURI(AppEvent.OpenURIEvent)
+ * @see OpenURIHandler#openURI(OpenURIEvent)
  *
  * @since 9
  */
--- a/jdk/src/java.desktop/share/classes/java/awt/desktop/PrintFilesEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/desktop/PrintFilesEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -33,7 +33,7 @@
 /**
  * Event sent when the app is asked to print a list of files.
  *
- * @see PrintFilesHandler#printFiles(AppEvent.PrintFilesEvent)
+ * @see PrintFilesHandler#printFiles(PrintFilesEvent)
  * @since 9
  */
 public final class PrintFilesEvent extends FilesEvent {
--- a/jdk/src/java.desktop/share/classes/java/awt/desktop/QuitEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/desktop/QuitEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -28,7 +28,7 @@
 /**
  * Event sent when the application is asked to quit.
  *
- * @see QuitHandler#handleQuitRequestWith(AppEvent.QuitEvent, QuitResponse)
+ * @see QuitHandler#handleQuitRequestWith(QuitEvent, QuitResponse)
  *
  * @since 9
  */
--- a/jdk/src/java.desktop/share/classes/java/awt/desktop/ScreenSleepEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/desktop/ScreenSleepEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -28,8 +28,8 @@
  * Event sent when the displays attached to the system enter and exit power save
  * sleep.
  *
- * @see ScreenSleepListener#screenAboutToSleep(AppEvent.ScreenSleepEvent)
- * @see ScreenSleepListener#screenAwoke(AppEvent.ScreenSleepEvent)
+ * @see ScreenSleepListener#screenAboutToSleep(ScreenSleepEvent)
+ * @see ScreenSleepListener#screenAwoke(ScreenSleepEvent)
  *
  * @since 9
  */
--- a/jdk/src/java.desktop/share/classes/java/awt/desktop/SystemSleepEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/desktop/SystemSleepEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -28,8 +28,8 @@
 /**
  * Event sent when the system enters and exits power save sleep.
  *
- * @see SystemSleepListener#systemAboutToSleep(AppEvent.SystemSleepEvent)
- * @see SystemSleepListener#systemAwoke(AppEvent.SystemSleepEvent)
+ * @see SystemSleepListener#systemAboutToSleep(SystemSleepEvent)
+ * @see SystemSleepListener#systemAwoke(SystemSleepEvent)
  *
  * @since 9
  */
--- a/jdk/src/java.desktop/share/classes/java/awt/desktop/UserSessionEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/desktop/UserSessionEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -29,8 +29,8 @@
  *
  * Some systems may provide a reason of a user session change.
  *
- * @see UserSessionListener#userSessionActivated(AppEvent.UserSessionEvent)
- * @see UserSessionListener#userSessionDeactivated(AppEvent.UserSessionEvent)
+ * @see UserSessionListener#userSessionActivated(UserSessionEvent)
+ * @see UserSessionListener#userSessionDeactivated(UserSessionEvent)
  *
  * @since 9
  */
--- a/jdk/src/java.desktop/share/classes/java/awt/dnd/DragSourceDragEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/dnd/DragSourceDragEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -281,6 +281,7 @@
      * The mouse modifiers have higher priority than overlaying key
      * modifiers.
      */
+    @SuppressWarnings("deprecation")
     private void setNewModifiers() {
         if ((gestureModifiers & InputEvent.BUTTON1_MASK) != 0) {
             gestureModifiers |= InputEvent.BUTTON1_DOWN_MASK;
@@ -305,6 +306,7 @@
     /**
      * Sets old modifiers by the new ones.
      */
+    @SuppressWarnings("deprecation")
     private void setOldModifiers() {
         if ((gestureModifiers & InputEvent.BUTTON1_DOWN_MASK) != 0) {
             gestureModifiers |= InputEvent.BUTTON1_MASK;
--- a/jdk/src/java.desktop/share/classes/java/awt/event/ActionEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/event/ActionEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,7 +26,6 @@
 package java.awt.event;
 
 import java.awt.AWTEvent;
-import java.awt.Event;
 import java.lang.annotation.Native;
 
 /**
@@ -63,25 +62,25 @@
      * The shift modifier. An indicator that the shift key was held
      * down during the event.
      */
-    public static final int SHIFT_MASK          = Event.SHIFT_MASK;
+    public static final int SHIFT_MASK = 1 << 0;
 
     /**
      * The control modifier. An indicator that the control key was held
      * down during the event.
      */
-    public static final int CTRL_MASK           = Event.CTRL_MASK;
+    public static final int CTRL_MASK = 1 << 1;
 
     /**
      * The meta modifier. An indicator that the meta key was held
      * down during the event.
      */
-    public static final int META_MASK           = Event.META_MASK;
+    public static final int META_MASK = 1 << 2;
 
     /**
      * The alt modifier. An indicator that the alt key was held
      * down during the event.
      */
-    public static final int ALT_MASK            = Event.ALT_MASK;
+    public static final int ALT_MASK = 1 << 3;
 
 
     /**
@@ -274,6 +273,7 @@
      *
      * @return a string identifying the event and its associated command
      */
+    @SuppressWarnings("deprecation")
     public String paramString() {
         String typeStr;
         switch(id) {
--- a/jdk/src/java.desktop/share/classes/java/awt/event/InputEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/event/InputEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2013, 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
@@ -62,51 +62,76 @@
 
     /**
      * The Shift key modifier constant.
-     * It is recommended that SHIFT_DOWN_MASK be used instead.
+     *
+     * @deprecated It is recommended that SHIFT_DOWN_MASK and
+     *             {@link #getModifiersEx()} be used instead
      */
+    @Deprecated(since = "9")
     public static final int SHIFT_MASK = Event.SHIFT_MASK;
 
     /**
      * The Control key modifier constant.
-     * It is recommended that CTRL_DOWN_MASK be used instead.
+     *
+     * @deprecated It is recommended that CTRL_DOWN_MASK and
+     *             {@link #getModifiersEx()} be used instead
      */
+    @Deprecated(since = "9")
     public static final int CTRL_MASK = Event.CTRL_MASK;
 
     /**
      * The Meta key modifier constant.
-     * It is recommended that META_DOWN_MASK be used instead.
+     *
+     * @deprecated It is recommended that META_DOWN_MASK and
+     *             {@link #getModifiersEx()} be used instead
      */
+    @Deprecated(since = "9")
     public static final int META_MASK = Event.META_MASK;
 
     /**
      * The Alt key modifier constant.
-     * It is recommended that ALT_DOWN_MASK be used instead.
+     *
+     * @deprecated It is recommended that ALT_DOWN_MASK and
+     *             {@link #getModifiersEx()} be used instead
      */
+    @Deprecated(since = "9")
     public static final int ALT_MASK = Event.ALT_MASK;
 
     /**
      * The AltGraph key modifier constant.
+     *
+     * @deprecated It is recommended that ALT_GRAPH_DOWN_MASK and
+     *             {@link #getModifiersEx()} be used instead
      */
+    @Deprecated(since = "9")
     public static final int ALT_GRAPH_MASK = 1 << 5;
 
     /**
      * The Mouse Button1 modifier constant.
-     * It is recommended that BUTTON1_DOWN_MASK be used instead.
+     *
+     * @deprecated It is recommended that BUTTON1_DOWN_MASK and
+     *             {@link #getModifiersEx()} be used instead
      */
+    @Deprecated(since = "9")
     public static final int BUTTON1_MASK = 1 << 4;
 
     /**
      * The Mouse Button2 modifier constant.
-     * It is recommended that BUTTON2_DOWN_MASK be used instead.
-     * Note that BUTTON2_MASK has the same value as ALT_MASK.
+     *
+     * @deprecated It is recommended that BUTTON2_DOWN_MASK and
+     *             {@link #getModifiersEx()} be used instead. Note that
+     *             BUTTON2_MASK has the same value as ALT_MASK.
      */
+    @Deprecated(since = "9")
     public static final int BUTTON2_MASK = Event.ALT_MASK;
 
     /**
      * The Mouse Button3 modifier constant.
-     * It is recommended that BUTTON3_DOWN_MASK be used instead.
-     * Note that BUTTON3_MASK has the same value as META_MASK.
+     *
+     * @deprecated It is recommended that BUTTON3_DOWN_MASK and
+     *             {@link #getModifiersEx()} be used instead. Note that
+     *             BUTTON3_MASK has the same value as META_MASK.
      */
+    @Deprecated(since = "9")
     public static final int BUTTON3_MASK = Event.META_MASK;
 
     /**
@@ -159,7 +184,7 @@
 
     /**
      * An array of extended modifiers for additional buttons.
-     * @see getButtonDownMasks
+     * @see #getButtonDownMasks()
      * There are twenty buttons fit into 4byte space.
      * one more bit is reserved for FIRST_HIGH_BIT.
      * @since 1.7
@@ -382,7 +407,7 @@
      * @return whether or not the Shift modifier is down on this event
      */
     public boolean isShiftDown() {
-        return (modifiers & SHIFT_MASK) != 0;
+        return (modifiers & SHIFT_DOWN_MASK) != 0;
     }
 
     /**
@@ -390,7 +415,7 @@
      * @return whether or not the Control modifier is down on this event
      */
     public boolean isControlDown() {
-        return (modifiers & CTRL_MASK) != 0;
+        return (modifiers & CTRL_DOWN_MASK) != 0;
     }
 
     /**
@@ -398,7 +423,7 @@
      * @return whether or not the Meta modifier is down on this event
      */
     public boolean isMetaDown() {
-        return (modifiers & META_MASK) != 0;
+        return (modifiers & META_DOWN_MASK) != 0;
     }
 
     /**
@@ -406,7 +431,7 @@
      * @return whether or not the Alt modifier is down on this event
      */
     public boolean isAltDown() {
-        return (modifiers & ALT_MASK) != 0;
+        return (modifiers & ALT_DOWN_MASK) != 0;
     }
 
     /**
@@ -414,7 +439,7 @@
      * @return whether or not the AltGraph modifier is down on this event
      */
     public boolean isAltGraphDown() {
-        return (modifiers & ALT_GRAPH_MASK) != 0;
+        return (modifiers & ALT_GRAPH_DOWN_MASK) != 0;
     }
 
     /**
@@ -428,8 +453,12 @@
 
     /**
      * Returns the modifier mask for this event.
+     *
      * @return the modifier mask for this event
+     * @deprecated It is recommended that extended modifier keys and
+     *             {@link #getModifiersEx()} be used instead
      */
+    @Deprecated(since = "9")
     public int getModifiers() {
         return modifiers & (JDK_1_3_MODIFIERS | HIGH_MODIFIERS);
     }
--- a/jdk/src/java.desktop/share/classes/java/awt/event/KeyEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/event/KeyEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1169,6 +1169,7 @@
      * @see #getKeyLocation()
      * @since 1.4
      */
+    @SuppressWarnings("deprecation")
     public KeyEvent(Component source, int id, long when, int modifiers,
                     int keyCode, char keyChar, int keyLocation) {
         super(source, id, when, modifiers);
@@ -1561,7 +1562,10 @@
      * @return string a text description of the combination of modifier
      *                keys that were held down during the event
      * @see InputEvent#getModifiersExText(int)
+     * @deprecated It is recommended that extended modifier keys and
+     *             {@link InputEvent#getModifiersExText(int)} be used instead
      */
+    @Deprecated(since = "9")
     public static String getKeyModifiersText(int modifiers) {
         StringBuilder buf = new StringBuilder();
         if ((modifiers & InputEvent.META_MASK) != 0) {
@@ -1696,6 +1700,7 @@
      *
      * @return a string identifying the event and its attributes
      */
+    @SuppressWarnings("deprecation")
     public String paramString() {
         StringBuilder str = new StringBuilder(100);
 
@@ -1821,6 +1826,7 @@
      * Sets new modifiers by the old ones. The key modifiers
      * override overlapping mouse modifiers.
      */
+    @SuppressWarnings("deprecation")
     private void setNewModifiers() {
         if ((modifiers & SHIFT_MASK) != 0) {
             modifiers |= SHIFT_DOWN_MASK;
@@ -1845,6 +1851,7 @@
     /**
      * Sets old modifiers by the new ones.
      */
+    @SuppressWarnings("deprecation")
     private void setOldModifiers() {
         if ((modifiers & SHIFT_DOWN_MASK) != 0) {
             modifiers |= SHIFT_MASK;
@@ -1871,6 +1878,7 @@
      * override overlapping mouse modifiers.
      * @serial
      */
+    @SuppressWarnings("deprecation")
     private void readObject(ObjectInputStream s)
       throws IOException, ClassNotFoundException {
         s.defaultReadObject();
--- a/jdk/src/java.desktop/share/classes/java/awt/event/MouseEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/event/MouseEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -733,6 +733,7 @@
      * @see InputEvent#getMaskForButton(int)
      * @since 1.6
      */
+    @SuppressWarnings("deprecation")
     public MouseEvent(Component source, int id, long when, int modifiers,
                       int x, int y, int xAbs, int yAbs,
                       int clickCount, boolean popupTrigger, int button)
@@ -943,6 +944,7 @@
      * @see InputEvent#getModifiersExText(int)
      * @since 1.4
      */
+    @SuppressWarnings("deprecation")
     public static String getMouseModifiersText(int modifiers) {
         StringBuilder buf = new StringBuilder();
         if ((modifiers & InputEvent.ALT_MASK) != 0) {
@@ -1007,6 +1009,7 @@
      *
      * @return a string identifying the event and its attributes
      */
+    @SuppressWarnings("deprecation")
     public String paramString() {
         StringBuilder str = new StringBuilder(80);
 
@@ -1066,6 +1069,7 @@
      * Sets new modifiers by the old ones.
      * Also sets button.
      */
+    @SuppressWarnings("deprecation")
     private void setNewModifiers() {
         if ((modifiers & BUTTON1_MASK) != 0) {
             modifiers |= BUTTON1_DOWN_MASK;
@@ -1120,6 +1124,7 @@
     /**
      * Sets old modifiers by the new ones.
      */
+    @SuppressWarnings("deprecation")
     private void setOldModifiers() {
         if (id == MOUSE_PRESSED
             || id == MOUSE_RELEASED
@@ -1168,6 +1173,7 @@
      * Sets new modifiers by the old ones.
      * @serial
      */
+    @SuppressWarnings("deprecation")
     private void readObject(ObjectInputStream s)
       throws IOException, ClassNotFoundException {
         s.defaultReadObject();
--- a/jdk/src/java.desktop/share/classes/java/awt/image/ColorModel.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/image/ColorModel.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2017, 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
@@ -31,10 +31,10 @@
 import sun.java2d.cmm.CMSManager;
 import sun.java2d.cmm.ColorTransform;
 import sun.java2d.cmm.PCMM;
-import java.awt.Toolkit;
 import java.util.Collections;
 import java.util.Map;
 import java.util.WeakHashMap;
+import java.util.Arrays;
 
 /**
  * The {@code ColorModel} abstract class encapsulates the
@@ -362,7 +362,14 @@
             this.transparency         = transparency;
         }
 
-        nBits = bits.clone();
+        /*
+         * We need significant bits value only for the length
+         * of number of components, so we truncate remaining part.
+         * It also helps in hashCode calculation since bits[] can contain
+         * different values after the length of number of components between
+         * two ColorModels.
+         */
+        nBits = Arrays.copyOf(bits, numComponents);
         this.pixel_bits = pixel_bits;
         if (pixel_bits <= 0) {
             throw new IllegalArgumentException("Number of pixel bits must "+
@@ -1441,69 +1448,53 @@
     }
 
     /**
-     * Tests if the specified {@code Object} is an instance of
-     * {@code ColorModel} and if it equals this
-     * {@code ColorModel}.
-     * @param obj the {@code Object} to test for equality
-     * @return {@code true} if the specified {@code Object}
-     * is an instance of {@code ColorModel} and equals this
-     * {@code ColorModel}; {@code false} otherwise.
+     * This method simply delegates to the default implementation in {@code Object}
+     * which is identical to an {@code ==} test since this class cannot enforce the
+     * issues of a proper equality test among multiple independent subclass
+     * branches.
+     * Subclasses are encouraged to override this method and provide equality
+     * testing for their own properties in addition to equality tests for the
+     * following common base properties of {@code ColorModel}:
+     * <ul>
+     * <li>Support for alpha component.</li>
+     * <li>Is alpha premultiplied.</li>
+     * <li>Number of bits per pixel.</li>
+     * <li>Type of transparency like Opaque, Bitmask or Translucent.</li>
+     * <li>Number of components in a pixel.</li>
+     * <li>{@code ColorSpace} type.</li>
+     * <li>Type of the array used to represent pixel values.</li>
+     * <li>Number of significant bits per color and alpha component.</li>
+     * </ul>
+     * @param obj the reference object with which to compare.
+     * @return {@code true} if this object is the same as the obj
+     *         argument; {@code false} otherwise.
      */
+    @Override
     public boolean equals(Object obj) {
-        if (!(obj instanceof ColorModel)) {
-            return false;
-        }
-        ColorModel cm = (ColorModel) obj;
-
-        if (this == cm) {
-            return true;
-        }
-        if (supportsAlpha != cm.hasAlpha() ||
-            isAlphaPremultiplied != cm.isAlphaPremultiplied() ||
-            pixel_bits != cm.getPixelSize() ||
-            transparency != cm.getTransparency() ||
-            numComponents != cm.getNumComponents())
-        {
-            return false;
-        }
-
-        int[] nb = cm.getComponentSize();
-
-        if ((nBits != null) && (nb != null)) {
-            for (int i = 0; i < numComponents; i++) {
-                if (nBits[i] != nb[i]) {
-                    return false;
-                }
-            }
-        } else {
-            return ((nBits == null) && (nb == null));
-        }
-
-        return true;
+        return super.equals(obj);
     }
 
     /**
-     * Returns the hash code for this ColorModel.
-     *
-     * @return    a hash code for this ColorModel.
+     * This method simply delegates to the default implementation in {@code Object}
+     * which returns the system ID for the class.
+     * Subclasses are encouraged to override this method and provide a hash
+     * for their own properties in addition to hashing the values of the
+     * following common base properties of {@code ColorModel}:
+     * <ul>
+     * <li>Support for alpha component.</li>
+     * <li>Is alpha premultiplied.</li>
+     * <li>Number of bits per pixel.</li>
+     * <li>Type of transparency like Opaque, Bitmask or Translucent.</li>
+     * <li>Number of components in a pixel.</li>
+     * <li>{@code ColorSpace} type.</li>
+     * <li>Type of the array used to represent pixel values.</li>
+     * <li>Number of significant bits per color and alpha component.</li>
+     * </ul>
+     * @return a hash code value for this object.
      */
+    @Override
     public int hashCode() {
-
-        int result = 0;
-
-        result = (supportsAlpha ? 2 : 3) +
-                 (isAlphaPremultiplied ? 4 : 5) +
-                 pixel_bits * 6 +
-                 transparency * 7 +
-                 numComponents * 8;
-
-        if (nBits != null) {
-            for (int i = 0; i < numComponents; i++) {
-                result = result + nBits[i] * (i + 9);
-            }
-        }
-
-        return result;
+        return super.hashCode();
     }
 
     /**
@@ -1961,4 +1952,4 @@
         return lg16Toog16LUT;
     }
 
-}
+}
\ No newline at end of file
--- a/jdk/src/java.desktop/share/classes/java/awt/image/ComponentColorModel.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/image/ComponentColorModel.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 
 import java.awt.color.ColorSpace;
 import java.awt.color.ICC_ColorSpace;
+import java.util.Arrays;
 
 /**
  * A {@code ColorModel} class that works with pixel values that
@@ -200,6 +201,7 @@
     private float[] diffMinMax;
     private float[] compOffset;
     private float[] compScale;
+    private volatile int hashCode;
 
     /**
      * Constructs a {@code ComponentColorModel} from the specified
@@ -2927,22 +2929,59 @@
     }
 
     /**
-     * Compares this color model with another for equality.
-     *
-     * @param obj The object to compare with this color model.
-     * @return {@code true} if the color model objects are equal,
-     * {@code false} if they are not.
+     * Tests if the specified {@code Object} is an instance
+     * of {@code ComponentColorModel} and equals this
+     * {@code ComponentColorModel}.
+     * @param obj the {@code Object} to test for equality
+     * @return {@code true} if the specified {@code Object}
+     * is an instance of {@code ComponentColorModel} and equals this
+     * {@code ComponentColorModel}; {@code false} otherwise.
      */
+    @Override
     public boolean equals(Object obj) {
-        if (!super.equals(obj)) {
+        if (!(obj instanceof ComponentColorModel)) {
             return false;
         }
 
-        if (obj.getClass() !=  getClass()) {
+        ComponentColorModel cm = (ComponentColorModel) obj;
+        if (supportsAlpha != cm.hasAlpha() ||
+            isAlphaPremultiplied != cm.isAlphaPremultiplied() ||
+            pixel_bits != cm.getPixelSize() ||
+            transparency != cm.getTransparency() ||
+            numComponents != cm.getNumComponents() ||
+            (!(colorSpace.equals(cm.colorSpace))) ||
+            transferType != cm.transferType)
+        {
+            return false;
+        }
+
+        if (!(Arrays.equals(nBits, cm.getComponentSize()))) {
             return false;
         }
 
         return true;
     }
 
-}
+    /**
+     * Returns the hash code for this ComponentColorModel.
+     *
+     * @return    a hash code for this ComponentColorModel.
+     */
+    @Override
+    public int hashCode() {
+        int result = hashCode;
+        if (result == 0) {
+            result = 7;
+            result = 89 * result + this.pixel_bits;
+            result = 89 * result + Arrays.hashCode(this.nBits);
+            result = 89 * result + this.transparency;
+            result = 89 * result + (this.supportsAlpha ? 1 : 0);
+            result = 89 * result + (this.isAlphaPremultiplied ? 1 : 0);
+            result = 89 * result + this.numComponents;
+            result = 89 * result + this.colorSpace.hashCode();
+            result = 89 * result + this.transferType;
+            hashCode = result;
+        }
+        return result;
+    }
+}
\ No newline at end of file
--- a/jdk/src/java.desktop/share/classes/java/awt/image/IndexColorModel.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/image/IndexColorModel.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1995, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1995, 2017, 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.awt.Transparency;
 import java.awt.color.ColorSpace;
 import java.math.BigInteger;
+import java.util.Arrays;
 
 /**
  * The {@code IndexColorModel} class is a {@code ColorModel}
@@ -129,6 +130,7 @@
     private int transparent_index = -1;
     private boolean allgrayopaque;
     private BigInteger validBits;
+    private volatile int hashCode;
 
     private sun.awt.image.BufImgSurfaceData.ICMColorData colorData = null;
 
@@ -1532,4 +1534,100 @@
                          + " isAlphaPre = "+isAlphaPremultiplied
                          );
     }
-}
+
+    /**
+     * Tests if the specified {@code Object} is an
+     * instance of {@code IndexColorModel}
+     * and if it equals this {@code IndexColorModel}
+     * @param obj the {@code Object} to test for equality
+     * @return {@code true} if the specified {@code Object}
+     * equals this {@code IndexColorModel}; {@code false} otherwise.
+     */
+    @Override
+    public boolean equals(Object obj) {
+
+        if (!(obj instanceof IndexColorModel)) {
+            return false;
+        }
+
+        IndexColorModel cm = (IndexColorModel) obj;
+        if (supportsAlpha != cm.hasAlpha() ||
+            isAlphaPremultiplied != cm.isAlphaPremultiplied() ||
+            pixel_bits != cm.getPixelSize() ||
+            transparency != cm.getTransparency() ||
+            numComponents != cm.getNumComponents() ||
+            (!(colorSpace.equals(cm.colorSpace))) ||
+            transferType != cm.transferType ||
+            map_size != cm.map_size ||
+            transparent_index != cm.transparent_index)
+        {
+            return false;
+        }
+
+        if (!(Arrays.equals(nBits, cm.getComponentSize()))) {
+            return false;
+        }
+
+        // verify whether we have to check equality of all bits in validBits
+        boolean testValidBits;
+        if (validBits == cm.validBits) {
+            testValidBits = false;
+        } else if (validBits == null || cm.validBits == null) {
+            return false;
+        } else if (validBits.equals(cm.validBits)) {
+            testValidBits = false;
+        } else {
+            testValidBits = true;
+        }
+
+        if (testValidBits) {
+            for (int i = 0; i < map_size; i++) {
+                if (rgb[i] != cm.rgb[i] ||
+                    validBits.testBit(i) != cm.validBits.testBit(i))
+                {
+                    return false;
+                }
+            }
+        } else {
+            for (int i = 0; i < map_size; i++) {
+                if (rgb[i] != cm.rgb[i]) {
+                    return false;
+                }
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Returns the hash code for IndexColorModel.
+     *
+     * @return    a hash code for IndexColorModel
+     */
+    @Override
+    public int hashCode() {
+        int result = hashCode;
+        if (result == 0) {
+            /*
+             * We are intentionally not calculating hashCode for validBits,
+             * because it is only used for 8-bit indexed screens and they
+             * are very rare. It is very unlikely for 2 IndexColorModels
+             * to have different valiBits and have same value for all
+             * other properties.
+             */
+            result = 7;
+            result = 89 * result + this.pixel_bits;
+            result = 89 * result + Arrays.hashCode(this.nBits);
+            result = 89 * result + this.transparency;
+            result = 89 * result + (this.supportsAlpha ? 1 : 0);
+            result = 89 * result + (this.isAlphaPremultiplied ? 1 : 0);
+            result = 89 * result + this.numComponents;
+            result = 89 * result + this.colorSpace.hashCode();
+            result = 89 * result + this.transferType;
+            result = 89 * result + Arrays.hashCode(this.rgb);
+            result = 89 * result + this.map_size;
+            result = 89 * result + this.transparent_index;
+            hashCode = result;
+        }
+        return result;
+    }
+}
\ No newline at end of file
--- a/jdk/src/java.desktop/share/classes/java/awt/image/PackedColorModel.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/image/PackedColorModel.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 
 import java.awt.Transparency;
 import java.awt.color.ColorSpace;
+import java.util.Arrays;
 
 /**
  * The {@code PackedColorModel} class is an abstract
@@ -88,6 +89,7 @@
     int[] maskArray;
     int[] maskOffsets;
     float[] scaleFactors;
+    private volatile int hashCode;
 
     /**
      * Constructs a {@code PackedColorModel} from a color mask array,
@@ -393,25 +395,63 @@
      * is an instance of {@code PackedColorModel} and equals this
      * {@code PackedColorModel}; {@code false} otherwise.
      */
+    @Override
     public boolean equals(Object obj) {
         if (!(obj instanceof PackedColorModel)) {
             return false;
         }
 
-        if (!super.equals(obj)) {
+        PackedColorModel cm = (PackedColorModel) obj;
+
+        if (supportsAlpha != cm.hasAlpha() ||
+            isAlphaPremultiplied != cm.isAlphaPremultiplied() ||
+            pixel_bits != cm.getPixelSize() ||
+            transparency != cm.getTransparency() ||
+            numComponents != cm.getNumComponents() ||
+            (!(colorSpace.equals(cm.colorSpace))) ||
+            transferType != cm.transferType)
+        {
             return false;
         }
 
-        PackedColorModel cm = (PackedColorModel) obj;
         int numC = cm.getNumComponents();
         for(int i=0; i < numC; i++) {
             if (maskArray[i] != cm.getMask(i)) {
                 return false;
             }
         }
+
+        if (!(Arrays.equals(nBits, cm.getComponentSize()))) {
+            return false;
+        }
+
         return true;
     }
 
+    /**
+     * Returns the hash code for this PackedColorModel.
+     *
+     * @return    a hash code for this PackedColorModel.
+     */
+    @Override
+    public int hashCode() {
+        int result = hashCode;
+        if (result == 0) {
+            result = 7;
+            result = 89 * result + this.pixel_bits;
+            result = 89 * result + Arrays.hashCode(this.nBits);
+            result = 89 * result + this.transparency;
+            result = 89 * result + (this.supportsAlpha ? 1 : 0);
+            result = 89 * result + (this.isAlphaPremultiplied ? 1 : 0);
+            result = 89 * result + this.numComponents;
+            result = 89 * result + this.colorSpace.hashCode();
+            result = 89 * result + this.transferType;
+            result = 89 * result + Arrays.hashCode(this.maskArray);
+            hashCode = result;
+        }
+        return result;
+    }
+
     private static final int[] createBitsArray(int[]colorMaskArray,
                                                int alphaMask) {
         int numColors = colorMaskArray.length;
@@ -480,4 +520,4 @@
         return count;
     }
 
-}
+}
\ No newline at end of file
--- a/jdk/src/java.desktop/share/classes/java/awt/peer/PopupMenuPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/java/awt/peer/PopupMenuPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -46,5 +46,6 @@
      *
      * @see PopupMenu#show(java.awt.Component, int, int)
      */
+    @SuppressWarnings("deprecation")
     void show(Event e);
 }
--- a/jdk/src/java.desktop/share/classes/javax/swing/Autoscroller.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/Autoscroller.java	Thu Mar 16 20:47:03 2017 +0000
@@ -82,6 +82,7 @@
     /**
      * Starts the timer targeting the passed in component.
      */
+    @SuppressWarnings("deprecation")
     private void start(JComponent c, MouseEvent e) {
         Point screenLocation = c.getLocationOnScreen();
 
@@ -156,6 +157,7 @@
      * ActionListener method. Invoked when the Timer fires. This will scroll
      * if necessary.
      */
+    @SuppressWarnings("deprecation")
     public void actionPerformed(ActionEvent x) {
         JComponent component = Autoscroller.component;
 
--- a/jdk/src/java.desktop/share/classes/javax/swing/DefaultButtonModel.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/DefaultButtonModel.java	Thu Mar 16 20:47:03 2017 +0000
@@ -239,6 +239,7 @@
     /**
      * {@inheritDoc}
      */
+    @SuppressWarnings("deprecation")
     public void setPressed(boolean b) {
         if((isPressed() == b) || !isEnabled()) {
             return;
--- a/jdk/src/java.desktop/share/classes/javax/swing/JComboBox.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JComboBox.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1235,6 +1235,7 @@
      *
      * @see EventListenerList
      */
+    @SuppressWarnings("deprecation")
     protected void fireActionEvent() {
         if (!firingActionEvent) {
             // Set flag to ensure that an infinite loop is not created
--- a/jdk/src/java.desktop/share/classes/javax/swing/JComponent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JComponent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -429,6 +429,7 @@
      * Returns the Set of <code>KeyStroke</code>s to use if the component
      * is managing focus for forward focus traversal.
      */
+    @SuppressWarnings("deprecation")
     static Set<KeyStroke> getManagingFocusForwardTraversalKeys() {
         synchronized(JComponent.class) {
             if (managingFocusForwardTraversalKeys == null) {
@@ -445,6 +446,7 @@
      * Returns the Set of <code>KeyStroke</code>s to use if the component
      * is managing focus for backward focus traversal.
      */
+    @SuppressWarnings("deprecation")
     static Set<KeyStroke> getManagingFocusBackwardTraversalKeys() {
         synchronized(JComponent.class) {
             if (managingFocusBackwardTraversalKeys == null) {
@@ -2886,6 +2888,7 @@
      *
      * @since 1.3
      */
+    @SuppressWarnings("deprecation")
     protected boolean processKeyBinding(KeyStroke ks, KeyEvent e,
                                         int condition, boolean pressed) {
         InputMap map = getInputMap(condition, false);
--- a/jdk/src/java.desktop/share/classes/javax/swing/JFileChooser.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JFileChooser.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1754,6 +1754,7 @@
      *                the event
      * @see EventListenerList
      */
+    @SuppressWarnings("deprecation")
     protected void fireActionPerformed(String command) {
         // Guaranteed to return a non-null array
         Object[] listeners = listenerList.getListenerList();
--- a/jdk/src/java.desktop/share/classes/javax/swing/JLayer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JLayer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -286,8 +286,7 @@
             super.remove(oldGlassPane);
         }
         if (glassPane != null) {
-            AWTAccessor.getComponentAccessor().setMixingCutoutShape(glassPane,
-                    new Rectangle());
+            glassPane.setMixingCutoutShape(new Rectangle());
             glassPane.setVisible(isGlassPaneVisible);
             super.addImpl(glassPane, null, 0);
         }
--- a/jdk/src/java.desktop/share/classes/javax/swing/JList.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JList.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1516,6 +1516,7 @@
      * @see JComponent#setToolTipText
      * @see JComponent#getToolTipText
      */
+    @SuppressWarnings("deprecation")
     public String getToolTipText(MouseEvent event) {
         if(event != null) {
             Point p = event.getPoint();
--- a/jdk/src/java.desktop/share/classes/javax/swing/JMenuItem.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JMenuItem.java	Thu Mar 16 20:47:03 2017 +0000
@@ -412,6 +412,7 @@
      * @param path  the <code>MenuElement</code> path array
      * @param manager   the <code>MenuSelectionManager</code>
      */
+    @SuppressWarnings("deprecation")
     public void processMouseEvent(MouseEvent e,MenuElement path[],MenuSelectionManager manager) {
         processMenuDragMouseEvent(
                  new MenuDragMouseEvent(e.getComponent(), e.getID(),
@@ -435,6 +436,7 @@
      * @param path the <code>MenuElement</code> path array
      * @param manager   the <code>MenuSelectionManager</code>
      */
+    @SuppressWarnings("deprecation")
     public void processKeyEvent(KeyEvent e,MenuElement path[],MenuSelectionManager manager) {
         if (DEBUG) {
             System.out.println("in JMenuItem.processKeyEvent/3 for " + getText() +
--- a/jdk/src/java.desktop/share/classes/javax/swing/JPopupMenu.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JPopupMenu.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1385,6 +1385,7 @@
      * @param path the <code>MenuElement</code> path array
      * @param manager   the <code>MenuSelectionManager</code>
      */
+    @SuppressWarnings("deprecation")
     public void processKeyEvent(KeyEvent e, MenuElement path[],
                                 MenuSelectionManager manager) {
         MenuKeyEvent mke = new MenuKeyEvent(e.getComponent(), e.getID(),
--- a/jdk/src/java.desktop/share/classes/javax/swing/JRootPane.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JRootPane.java	Thu Mar 16 20:47:03 2017 +0000
@@ -663,8 +663,7 @@
             throw new NullPointerException("glassPane cannot be set to null.");
         }
 
-        AWTAccessor.getComponentAccessor().setMixingCutoutShape(glass,
-                new Rectangle());
+        glass.setMixingCutoutShape(new Rectangle());
 
         boolean visible = false;
         if (glassPane != null && glassPane.getParent() == this) {
--- a/jdk/src/java.desktop/share/classes/javax/swing/JTable.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JTable.java	Thu Mar 16 20:47:03 2017 +0000
@@ -3410,8 +3410,10 @@
                 // Convert the event to the renderer's coordinate system
                 Rectangle cellRect = getCellRect(hitRowIndex, hitColumnIndex, false);
                 p.translate(-cellRect.x, -cellRect.y);
+                @SuppressWarnings("deprecation")
+                final int modifiers = event.getModifiers();
                 MouseEvent newEvent = new MouseEvent(component, event.getID(),
-                                          event.getWhen(), event.getModifiers(),
+                                          event.getWhen(), modifiers,
                                           p.x, p.y,
                                           event.getXOnScreen(),
                                           event.getYOnScreen(),
--- a/jdk/src/java.desktop/share/classes/javax/swing/JTextField.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JTextField.java	Thu Mar 16 20:47:03 2017 +0000
@@ -485,6 +485,7 @@
      * first order.
      * @see EventListenerList
      */
+    @SuppressWarnings("deprecation")
     protected void fireActionPerformed() {
         // Guaranteed to return a non-null array
         Object[] listeners = listenerList.getListenerList();
--- a/jdk/src/java.desktop/share/classes/javax/swing/JToggleButton.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JToggleButton.java	Thu Mar 16 20:47:03 2017 +0000
@@ -372,6 +372,7 @@
         /**
          * Sets the pressed state of the toggle button.
          */
+        @SuppressWarnings("deprecation")
         public void setPressed(boolean b) {
             if ((isPressed() == b) || !isEnabled()) {
                 return;
--- a/jdk/src/java.desktop/share/classes/javax/swing/JTree.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/JTree.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1568,9 +1568,10 @@
                     Rectangle       pathBounds = getPathBounds(path);
 
                     p.translate(-pathBounds.x, -pathBounds.y);
+                    @SuppressWarnings("deprecation")
+                    final int modifiers = event.getModifiers();
                     newEvent = new MouseEvent(rComponent, event.getID(),
-                                          event.getWhen(),
-                                              event.getModifiers(),
+                                          event.getWhen(), modifiers,
                                               p.x, p.y,
                                               event.getXOnScreen(),
                                               event.getYOnScreen(),
--- a/jdk/src/java.desktop/share/classes/javax/swing/KeyboardManager.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/KeyboardManager.java	Thu Mar 16 20:47:03 2017 +0000
@@ -207,6 +207,7 @@
       * want a crack at the event.
       * If one of them wants it, then it will "DO-THE-RIGHT-THING"
       */
+    @SuppressWarnings("deprecation")
     public boolean fireKeyboardAction(KeyEvent e, boolean pressed, Container topAncestor) {
 
          if (e.isConsumed()) {
--- a/jdk/src/java.desktop/share/classes/javax/swing/MenuSelectionManager.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/MenuSelectionManager.java	Thu Mar 16 20:47:03 2017 +0000
@@ -212,6 +212,7 @@
      *
      * @param event  a MouseEvent object
      */
+    @SuppressWarnings("deprecation")
     public void processMouseEvent(MouseEvent event) {
         int screenX,screenY;
         Point p;
--- a/jdk/src/java.desktop/share/classes/javax/swing/SwingUtilities.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/SwingUtilities.java	Thu Mar 16 20:47:03 2017 +0000
@@ -346,6 +346,7 @@
      *
      * @return the new mouse event
      */
+    @SuppressWarnings("deprecation")
     public static MouseEvent convertMouseEvent(Component source,
                                                MouseEvent sourceEvent,
                                                Component destination) {
--- a/jdk/src/java.desktop/share/classes/javax/swing/SwingWorker.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/SwingWorker.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -575,7 +575,7 @@
      * For example:
      *
      * <pre>
-     * class SwingWorkerCompletionWaiter extends PropertyChangeListener {
+     * class SwingWorkerCompletionWaiter implements PropertyChangeListener {
      *     private JDialog dialog;
      *
      *     public SwingWorkerCompletionWaiter(JDialog dialog) {
--- a/jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/ToolTipManager.java	Thu Mar 16 20:47:03 2017 +0000
@@ -89,6 +89,7 @@
      */
     protected boolean heavyWeightPopupEnabled = false;
 
+    @SuppressWarnings("deprecation")
     ToolTipManager() {
         enterTimer = new Timer(750, new insideTimerAction());
         enterTimer.setRepeats(false);
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1839,6 +1839,7 @@
         // key.  If it finds a key event that wasn't a navigation key it
         // dispatches it to JComboBox.selectWithKeyChar() so that it can do
         // type-ahead.
+        @SuppressWarnings("deprecation")
         public void keyPressed( KeyEvent e ) {
             if ( isNavigationKey(e.getKeyCode(), e.getModifiers()) ) {
                 lastTime = 0L;
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboPopup.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicComboPopup.java	Thu Mar 16 20:47:03 2017 +0000
@@ -528,6 +528,7 @@
      */
     protected JList<Object> createList() {
         return new JList<Object>( comboBox.getModel() ) {
+            @SuppressWarnings("deprecation")
             public void processMouseEvent(MouseEvent e)  {
                 if (BasicGraphicsUtils.isMenuShortcutKeyDown(e))  {
                     // Fix for 4234053. Filter out the Control Key from the list.
@@ -1238,6 +1239,7 @@
     protected MouseEvent convertMouseEvent( MouseEvent e ) {
         Point convertedPoint = SwingUtilities.convertPoint( (Component)e.getSource(),
                                                             e.getPoint(), list );
+        @SuppressWarnings("deprecation")
         MouseEvent newEvent = new MouseEvent( (Component)e.getSource(),
                                               e.getID(),
                                               e.getWhen(),
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicGraphicsUtils.java	Thu Mar 16 20:47:03 2017 +0000
@@ -382,6 +382,7 @@
         return c.getComponentOrientation().isLeftToRight();
     }
 
+    @SuppressWarnings("deprecation")
     static boolean isMenuShortcutKeyDown(InputEvent event) {
         return (event.getModifiers() &
                 Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0;
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicInternalFrameUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1024,7 +1024,7 @@
                 return;
             }
         }
-
+        @SuppressWarnings("deprecation")
         public void mouseDragged(MouseEvent e) {
 
             if ( startingBounds == null ) {
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicMenuItemUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1026,6 +1026,7 @@
                 manager.processMouseEvent(e);
             }
         }
+        @SuppressWarnings("deprecation")
         public void mouseEntered(MouseEvent e) {
             MenuSelectionManager manager = MenuSelectionManager.defaultManager();
             int modifiers = e.getModifiers();
@@ -1037,6 +1038,7 @@
             manager.setSelectedPath(getPath());
              }
         }
+        @SuppressWarnings("deprecation")
         public void mouseExited(MouseEvent e) {
             MenuSelectionManager manager = MenuSelectionManager.defaultManager();
 
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicMenuUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicMenuUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -123,6 +123,7 @@
                                            getPropertyPrefix() + ".actionMap");
     }
 
+    @SuppressWarnings("deprecation")
     void updateMnemonicBinding() {
         int mnemonic = menuItem.getModel().getMnemonic();
         int[] shortcutKeys = (int[])DefaultLookup.get(menuItem, this,
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicPopupMenuUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -268,6 +268,7 @@
         return list;
     }
 
+    @SuppressWarnings("deprecation")
     public boolean isPopupTrigger(MouseEvent e) {
         return ((e.getID()==MouseEvent.MOUSE_RELEASED)
                 && ((e.getModifiers() & MouseEvent.BUTTON3_MASK)!=0));
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicSplitPaneUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -328,6 +328,7 @@
     /**
      * Installs the UI defaults.
      */
+    @SuppressWarnings("deprecation")
     protected void installDefaults(){
         LookAndFeel.installBorder(splitPane, "SplitPane.border");
         LookAndFeel.installColors(splitPane, "SplitPane.background",
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTableUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTableUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -868,6 +868,7 @@
 
         public void keyReleased(KeyEvent e) { }
 
+        @SuppressWarnings("deprecation")
         public void keyTyped(KeyEvent e) {
             KeyStroke keyStroke = KeyStroke.getKeyStroke(e.getKeyChar(),
                     e.getModifiers());
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/basic/BasicTextUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -525,7 +525,7 @@
      * adding 'TAB' and 'SHIFT-TAB' to traversalKeysSet in case
      * editor is non editable
      */
-
+    @SuppressWarnings("deprecation")
     void updateFocusTraversalKeys() {
         /*
          * Fix for 4514331 Non-editable JTextArea and similar
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalRootPaneUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalRootPaneUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -898,6 +898,7 @@
             w.setCursor(lastCursor);
         }
 
+        @SuppressWarnings("deprecation")
         public void mouseClicked(MouseEvent ev) {
             Window w = (Window)ev.getSource();
             Frame f = null;
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalToolTipUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/metal/MetalToolTipUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -192,6 +192,7 @@
     // that subclasses that randomly invoke this method will see varying
     // results. If this becomes an issue, MetalToolTipUI should no longer be
     // shared.
+    @SuppressWarnings("deprecation")
     public String getAcceleratorString() {
         if (tip == null || isAcceleratorHidden()) {
             return "";
--- a/jdk/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/plaf/synth/SynthSplitPaneUI.java	Thu Mar 16 20:47:03 2017 +0000
@@ -80,6 +80,7 @@
      * Installs the UI defaults.
      */
     @Override
+    @SuppressWarnings("deprecation")
     protected void installDefaults() {
         updateStyle(splitPane);
 
--- a/jdk/src/java.desktop/share/classes/javax/swing/table/JTableHeader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/table/JTableHeader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -384,6 +384,7 @@
      *                          renderer and, therefore, the proper tip
      * @return the tool tip for this component
      */
+    @SuppressWarnings("deprecation")
     public String getToolTipText(MouseEvent event) {
         String tip = null;
         Point p = event.getPoint();
--- a/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/text/DefaultCaret.java	Thu Mar 16 20:47:03 2017 +0000
@@ -372,6 +372,7 @@
     /**
      * Selects word based on the MouseEvent
      */
+    @SuppressWarnings("deprecation")
     private void selectWord(MouseEvent e) {
         if (selectedWordEvent != null
             && selectedWordEvent.getX() == e.getX()
@@ -405,6 +406,7 @@
      * @param e the mouse event
      * @see MouseListener#mouseClicked
      */
+    @SuppressWarnings("deprecation")
     public void mouseClicked(MouseEvent e) {
         if (getComponent() == null) {
             return;
@@ -513,6 +515,7 @@
     /**
      * Adjusts the caret location based on the MouseEvent.
      */
+    @SuppressWarnings("deprecation")
     private void adjustCaret(MouseEvent e) {
         if ((e.getModifiers() & ActionEvent.SHIFT_MASK) != 0 &&
             getDot() != -1) {
--- a/jdk/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/javax/swing/text/JTextComponent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -4103,6 +4103,7 @@
             get(FOCUSED_COMPONENT);
     }
 
+    @SuppressWarnings("deprecation")
     private int getCurrentEventModifiers() {
         int modifiers = 0;
         AWTEvent currentEvent = EventQueue.getCurrentEvent();
--- a/jdk/src/java.desktop/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,6 +26,8 @@
 /**
  * Defines the AWT and Swing user interface toolkits, plus APIs for
  * accessibility, audio, imaging, printing, and JavaBeans.
+ *
+ * @since 9
  */
 module java.desktop {
     requires transitive java.datatransfer;
@@ -88,9 +90,6 @@
     exports sun.awt to
         jdk.accessibility;
 
-    exports com.sun.awt to
-        jdk.desktop;
-
     opens javax.swing.plaf.basic to
         jdk.jconsole;
     opens com.sun.java.swing.plaf.windows to
--- a/jdk/src/java.desktop/share/classes/sun/awt/AWTAccessor.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/sun/awt/AWTAccessor.java	Thu Mar 16 20:47:03 2017 +0000
@@ -93,12 +93,6 @@
          * its parent.
          */
         Rectangle getBounds(Component comp);
-        /*
-         * Sets the shape of a lw component to cut out from hw components.
-         *
-         * See 6797587, 6776743, 6768307, and 6768332 for details
-         */
-        void setMixingCutoutShape(Component comp, Shape shape);
 
         /**
          * Sets GraphicsConfiguration value for the component.
--- a/jdk/src/java.desktop/share/classes/sun/awt/NullComponentPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/sun/awt/NullComponentPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -126,6 +126,7 @@
     public void coalescePaintEvent(PaintEvent e) {
     }
 
+    @SuppressWarnings("deprecation")
     public boolean handleEvent(Event e) {
         return false;
     }
--- a/jdk/src/java.desktop/share/classes/sun/awt/SunToolkit.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/sun/awt/SunToolkit.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1049,6 +1049,7 @@
     /**
      * Returns key modifiers used by Swing to set up a focus accelerator key stroke.
      */
+    @SuppressWarnings("deprecation")
     public int getFocusAcceleratorKeyMask() {
         return InputEvent.ALT_MASK;
     }
@@ -1059,6 +1060,7 @@
      * the way things work on Windows: here, pressing ctrl + alt allows user to enter
      * characters from the extended character set (like euro sign or math symbols)
      */
+    @SuppressWarnings("deprecation")
     public boolean isPrintableCharacterModifiersMask(int mods) {
         return ((mods & InputEvent.ALT_MASK) == (mods & InputEvent.CTRL_MASK));
     }
--- a/jdk/src/java.desktop/share/classes/sun/font/CompositeFont.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/sun/font/CompositeFont.java	Thu Mar 16 20:47:03 2017 +0000
@@ -93,20 +93,25 @@
          * better that it is handled internally to the CompositeFont class.
          */
         if (fm.getEUDCFont() != null) {
+            int msCnt = numMetricsSlots;
+            int fbCnt = numSlots - msCnt;
             numSlots++;
             if (componentNames != null) {
                 componentNames = new String[numSlots];
-                System.arraycopy(compNames, 0, componentNames, 0, numSlots-1);
-                componentNames[numSlots-1] =
-                    fm.getEUDCFont().getFontName(null);
+                System.arraycopy(compNames, 0, componentNames, 0, msCnt);
+                componentNames[msCnt] = fm.getEUDCFont().getFontName(null);
+                System.arraycopy(compNames, msCnt,
+                                 componentNames, msCnt+1, fbCnt);
             }
             if (componentFileNames != null) {
                 componentFileNames = new String[numSlots];
                 System.arraycopy(compFileNames, 0,
-                                  componentFileNames, 0, numSlots-1);
+                                  componentFileNames, 0, msCnt);
+                System.arraycopy(compFileNames, msCnt,
+                                  componentFileNames, msCnt+1, fbCnt);
             }
             components = new PhysicalFont[numSlots];
-            components[numSlots-1] = fm.getEUDCFont();
+            components[msCnt] = fm.getEUDCFont();
             deferredInitialisation = new boolean[numSlots];
             if (defer) {
                 for (int i=0; i<numSlots-1; i++) {
--- a/jdk/src/java.desktop/share/classes/sun/font/CompositeStrike.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/sun/font/CompositeStrike.java	Thu Mar 16 20:47:03 2017 +0000
@@ -71,7 +71,9 @@
     }
 
     PhysicalStrike getStrikeForSlot(int slot) {
-
+        if (slot >= strikes.length) {
+            slot = 0;
+        }
         PhysicalStrike strike = strikes[slot];
         if (strike == null) {
             strike =
--- a/jdk/src/java.desktop/share/classes/sun/font/ExtendedTextSourceLabel.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/sun/font/ExtendedTextSourceLabel.java	Thu Mar 16 20:47:03 2017 +0000
@@ -626,7 +626,11 @@
         glyphinfo = gv.getGlyphInfo();
     }
     catch (Exception e) {
-        System.out.println(source);
+        if (DEBUG) {
+            System.err.println(source);
+            e.printStackTrace();
+        }
+        glyphinfo = new float[gv.getNumGlyphs() * numvals];
     }
 
     int numGlyphs = gv.getNumGlyphs();
@@ -775,7 +779,7 @@
         if (gx == gxlimit) {
            tgt = charInfo.length / numvals;
         } else {
-           tgt = indices[gx]-1;
+           tgt = indices[gx];
         }
         if (DEBUG) {
            System.err.println("gx=" + gx + " gxlimit=" + gxlimit +
--- a/jdk/src/java.desktop/share/classes/sun/font/FontFamily.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/sun/font/FontFamily.java	Thu Mar 16 20:47:03 2017 +0000
@@ -27,6 +27,7 @@
 
 import java.io.File;
 import java.awt.Font;
+import java.io.IOException;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.concurrent.ConcurrentHashMap;
@@ -132,6 +133,16 @@
 
         FileFont newFont = (FileFont)font;
         File newDir = (new File(newFont.platName)).getParentFile();
+        if (existDir != null) {
+            try {
+                existDir = existDir.getCanonicalFile();
+            } catch (IOException ignored) {}
+        }
+        if (newDir != null) {
+            try {
+                newDir = newDir.getCanonicalFile();
+            } catch (IOException ignored) {}
+        }
         return java.util.Objects.equals(newDir, existDir);
     }
 
--- a/jdk/src/java.desktop/share/classes/sun/swing/FilePane.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/sun/swing/FilePane.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1831,6 +1831,7 @@
     private class Handler implements MouseListener {
         private MouseListener doubleClickListener;
 
+        @SuppressWarnings("deprecation")
         public void mouseClicked(MouseEvent evt) {
             JComponent source = (JComponent)evt.getSource();
 
--- a/jdk/src/java.desktop/share/classes/sun/swing/MenuItemLayoutHelper.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/sun/swing/MenuItemLayoutHelper.java	Thu Mar 16 20:47:03 2017 +0000
@@ -175,6 +175,7 @@
         arrowSize.origWidth = arrowSize.width;
     }
 
+    @SuppressWarnings("deprecation")
     private String getAccText(String acceleratorDelimiter) {
         String accText = "";
         KeyStroke accelerator = mi.getAccelerator();
--- a/jdk/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/classes/sun/swing/SwingUtilities2.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1460,7 +1460,7 @@
      *
      * @param ie InputEvent to check
      */
-
+    @SuppressWarnings("deprecation")
     private static boolean isAccessClipboardGesture(InputEvent ie) {
         boolean allowedGesture = false;
         if (ie instanceof KeyEvent) { //we can validate only keyboard gestures
@@ -2129,6 +2129,7 @@
         return -1;
     }
 
+    @SuppressWarnings("deprecation")
     public static int getSystemMnemonicKeyMask() {
         Toolkit toolkit = Toolkit.getDefaultToolkit();
         if (toolkit instanceof SunToolkit) {
--- a/jdk/src/java.desktop/share/native/libfontmanager/hb-jdk-font.cc	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/share/native/libfontmanager/hb-jdk-font.cc	Thu Mar 16 20:47:03 2017 +0000
@@ -52,6 +52,9 @@
 
     *glyph = (hb_codepoint_t)
           env->CallIntMethod(font2D, sunFontIDs.f2dCharToGlyphMID, u);
+    if ((int)*glyph < 0) {
+        *glyph = 0;
+    }
     return (*glyph != 0);
 }
 
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/InfoWindow.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/InfoWindow.java	Thu Mar 16 20:47:03 2017 +0000
@@ -429,7 +429,7 @@
                 gtkImagesLoaded = true;
             }
         }
-
+        @SuppressWarnings("deprecation")
         private class ActionPerformer extends MouseAdapter {
             public void mouseClicked(MouseEvent e) {
                 // hide the balloon by any click
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/ListHelper.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/ListHelper.java	Thu Mar 16 20:47:03 2017 +0000
@@ -385,7 +385,7 @@
         }
         return false;
     }
-
+    @SuppressWarnings("deprecation")
     void handleVSBEvent(MouseEvent e, Rectangle bounds, int x, int y) {
         int sbHeight = hsbVis ? bounds.height - SCROLLBAR_WIDTH : bounds.height;
 
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XBaseMenuWindow.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XBaseMenuWindow.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1087,7 +1087,9 @@
                       }
                   } else {
                       //Invoke action event
-                      item.action(mouseEvent.getWhen(), mouseEvent.getModifiers());
+                      @SuppressWarnings("deprecation")
+                      final int modifiers = mouseEvent.getModifiers();
+                      item.action(mouseEvent.getWhen(), modifiers);
                       ungrabInput();
                   }
               } else {
@@ -1200,7 +1202,9 @@
               if (citem instanceof XMenuPeer) {
                   cwnd.selectItem(citem, true);
               } else if (citem != null) {
-                  citem.action(event.getWhen(), event.getModifiers());
+                  @SuppressWarnings("deprecation")
+                  final int modifiers = event.getModifiers();
+                  citem.action(event.getWhen(), modifiers);
                   ungrabInput();
               }
               break;
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XButtonPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XButtonPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -120,7 +120,9 @@
               if (XToolkit.isLeftMouseButton(e)) {
                   if (armed)
                   {
-                      action(e.getWhen(),e.getModifiers());
+                      @SuppressWarnings("deprecation")
+                      final int modifiers = e.getModifiers();
+                      action(e.getWhen(), modifiers);
                   }
                   pressed = false;
                   armed = false;
@@ -168,7 +170,9 @@
                   pressed=true;
                   armed=true;
                   repaint();
-                  action(e.getWhen(),e.getModifiers());
+                  @SuppressWarnings("deprecation")
+                  final int modifiers = e.getModifiers();
+                  action(e.getWhen(), modifiers);
               }
 
               break;
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XChoicePeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XChoicePeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -482,7 +482,7 @@
         firstPress = false;
         dragStartIdx = -1;
     }
-
+    @SuppressWarnings("deprecation")
     public void mouseDragged(MouseEvent e) {
         /*
          * fix for 5003166. On Motif user are unable to drag
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XEmbedServerTester.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XEmbedServerTester.java	Thu Mar 16 20:47:03 2017 +0000
@@ -452,6 +452,7 @@
         waitWindowActivated(res);
         return res;
     }
+    @SuppressWarnings("deprecation")
     private int activateServerNoWait(int prev) {
         xembedLog.fine("Activating server");
         int res = getEventPos();
@@ -467,6 +468,7 @@
         robot.mouseRelease(InputEvent.BUTTON1_MASK);
         return res;
     }
+    @SuppressWarnings("deprecation")
     private int deactivateServer() {
         xembedLog.fine("Deactivating server");
         int res = getEventPos();
@@ -480,6 +482,7 @@
         waitWindowDeactivated(res);
         return res;
     }
+    @SuppressWarnings("deprecation")
     private int focusServer() {
         xembedLog.fine("Focusing server");
         boolean weFocused = focused;
@@ -740,6 +743,7 @@
     private void ungrabKey() {
         sendMessage(XEmbedHelper.NON_STANDARD_XEMBED_GTK_UNGRAB_KEY, 0, accel_keysym, accel_mods);
     }
+    @SuppressWarnings("deprecation")
     private int showModalDialog() {
         xembedLog.fine("Showing modal dialog");
         int res = getEventPos();
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XListPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XListPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -573,7 +573,7 @@
             repaint();
         }
     }
-
+    @SuppressWarnings("deprecation")
     void mousePressed(MouseEvent mouseEvent) {
         if (log.isLoggable(PlatformLogger.Level.FINER)) {
             log.finer(mouseEvent.toString() + ", hsb " + hsbVis + ", vsb " + vsbVis);
@@ -641,6 +641,7 @@
             isMousePressed = true;
         }
     }
+    @SuppressWarnings("deprecation")
     void mouseReleased(MouseEvent mouseEvent) {
         if (isEnabled() && mouseEvent.getButton() == MouseEvent.BUTTON1) {
             //winReleaseCursorFocus();
@@ -685,6 +686,7 @@
         }
     }
 
+    @SuppressWarnings("deprecation")
     void mouseDragged(MouseEvent mouseEvent) {
         // TODO: can you drag w/ any other buttons?  what about multiple buttons?
         if (isEnabled() &&
@@ -810,7 +812,7 @@
               break;
         }
     }
-
+    @SuppressWarnings("deprecation")
     void keyPressed(KeyEvent e) {
         int keyCode = e.getKeyCode();
         if (log.isLoggable(PlatformLogger.Level.FINE)) {
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XMenuBarPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XMenuBarPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -503,6 +503,7 @@
      * This function is called from XWindow
      * @see XWindow.handleF10onEDT()
      */
+    @SuppressWarnings("deprecation")
     void handleF10KeyPress(KeyEvent event) {
         int keyState = event.getModifiers();
         if (((keyState & InputEvent.ALT_MASK) != 0) ||
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XPopupMenuPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XPopupMenuPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -131,6 +131,7 @@
     /*
      * From PopupMenuPeer
      */
+    @SuppressWarnings("deprecation")
     public void show(Event e) {
         target = (Component)e.target;
         // Get menus from the target.
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XScrollPanePeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XScrollPanePeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -468,6 +468,7 @@
      * MouseEvent.MOUSE_EXITED
      * MouseEvent.MOUSE_DRAGGED
      */
+    @SuppressWarnings("deprecation")
     public void handleJavaMouseEvent( MouseEvent mouseEvent ) {
         super.handleJavaMouseEvent(mouseEvent);
         int modifiers = mouseEvent.getModifiers();
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XScrollbar.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XScrollbar.java	Thu Mar 16 20:47:03 2017 +0000
@@ -457,6 +457,7 @@
      * MouseEvent.MOUSE_EXITED
      * MouseEvent.MOUSE_DRAGGED
      */
+    @SuppressWarnings("deprecation")
     public void handleMouseEvent(int id, int modifiers, int x, int y) {
         if ((modifiers & InputEvent.BUTTON1_MASK) == 0) {
             return;
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XScrollbarPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XScrollbarPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -126,6 +126,7 @@
      * MouseEvent.MOUSE_EXITED
      * MouseEvent.MOUSE_DRAGGED
      */
+    @SuppressWarnings("deprecation")
     public void handleJavaMouseEvent( MouseEvent mouseEvent ) {
         super.handleJavaMouseEvent(mouseEvent);
 
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XTextAreaPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XTextAreaPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1344,6 +1344,7 @@
             }
         }
 
+        @SuppressWarnings("deprecation")
         private static MouseEvent newMouseEvent(
             Component source, Point point, MouseEvent template )
         {
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XTrayIconPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XTrayIconPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -477,6 +477,7 @@
             e.setSource(xtiPeer.target);
             XToolkit.postEvent(XToolkit.targetToAppContext(e.getSource()), e);
         }
+        @SuppressWarnings("deprecation")
         public void mouseClicked(MouseEvent e) {
             if ((e.getClickCount() == 1 || xtiPeer.balloon.isVisible()) &&
                 e.getButton() == MouseEvent.BUTTON1)
--- a/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindow.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/awt/X11/XWindow.java	Thu Mar 16 20:47:03 2017 +0000
@@ -621,7 +621,7 @@
         // 4 and 5 buttons are usually considered assigned to a first wheel
         return button == XConstants.buttons[3] || button == XConstants.buttons[4];
     }
-
+    @SuppressWarnings("deprecation")
     static int getXModifiers(AWTKeyStroke stroke) {
         int mods = stroke.getModifiers();
         int res = 0;
--- a/jdk/src/java.desktop/unix/classes/sun/print/IPPPrintService.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/unix/classes/sun/print/IPPPrintService.java	Thu Mar 16 20:47:03 2017 +0000
@@ -59,6 +59,7 @@
 
 import java.util.Iterator;
 import java.util.HashSet;
+import java.util.Map;
 
 
 public class IPPPrintService implements PrintService, SunPrinterJobService {
@@ -1758,6 +1759,19 @@
 
                     if (responseMap != null && responseMap.length > 0) {
                         getAttMap = responseMap[0];
+                        // If there is extra hashmap created due to duplicate
+                        // key/attribute present in IPPresponse, then use that
+                        // map too by appending to getAttMap after removing the
+                        // duplicate key/value
+                        if (responseMap.length > 1) {
+                            for (int i = 1; i < responseMap.length; i++) {
+                                for (Map.Entry<String, AttributeClass> entry : responseMap[i].entrySet()) {
+                                    if (!getAttMap.containsKey(entry.getValue())) {
+                                        getAttMap.put(entry.getKey(), entry.getValue());
+                                    }
+                                }
+                            }
+                        }
                     }
                 } else {
                     debug_println(debugPrefix+"opGetAttributes - null input stream");
--- a/jdk/src/java.desktop/windows/classes/sun/awt/Win32GraphicsDevice.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/windows/classes/sun/awt/Win32GraphicsDevice.java	Thu Mar 16 20:47:03 2017 +0000
@@ -523,9 +523,9 @@
         dynamicColorModel = null;
         defaultConfig = null;
         configs = null;
+        initScaleFactors();
         // pass on to all top-level windows on this display
         topLevels.notifyListeners();
-        initScaleFactors();
     }
 
     /**
--- a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WButtonPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WButtonPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -95,6 +95,7 @@
     private static native void initIDs();
 
     @Override
+    @SuppressWarnings("deprecation")
     public boolean handleJavaKeyEvent(KeyEvent e) {
          switch (e.getID()) {
             case KeyEvent.KEY_RELEASED:
--- a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WFileDialogPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WFileDialogPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -263,6 +263,7 @@
     void disable() {}
     @Override
     public void reshape(int x, int y, int width, int height) {}
+    @SuppressWarnings("deprecation")
     public boolean handleEvent(Event e) { return false; }
     @Override
     public void setForeground(Color c) {}
--- a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WPopupMenuPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WPopupMenuPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -70,6 +70,7 @@
 
     private native void createMenu(WComponentPeer parent);
 
+    @SuppressWarnings("deprecation")
     public void show(Event e) {
         Component origin = (Component)e.target;
         WComponentPeer peer = (WComponentPeer) WToolkit.targetToPeer(origin);
@@ -97,6 +98,7 @@
      */
     void show(Component origin, Point p) {
         WComponentPeer peer = (WComponentPeer) WToolkit.targetToPeer(origin);
+        @SuppressWarnings("deprecation")
         Event e = new Event(origin, 0, Event.MOUSE_DOWN, p.x, p.y, 0, 0);
         if (peer == null) {
             Component nativeOrigin = WToolkit.getNativeContainer(origin);
@@ -107,5 +109,6 @@
         _show(e);
     }
 
+    @SuppressWarnings("deprecation")
     private native void _show(Event e);
 }
--- a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WPrintDialogPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WPrintDialogPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -135,6 +135,7 @@
     void disable() {}
     @Override
     public void reshape(int x, int y, int width, int height) {}
+    @SuppressWarnings("deprecation")
     public boolean handleEvent(Event e) { return false; }
     @Override
     public void setForeground(Color c) {}
--- a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WTextFieldPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WTextFieldPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -43,6 +43,7 @@
     }
 
     @Override
+    @SuppressWarnings("deprecation")
     public boolean handleJavaKeyEvent(KeyEvent e) {
         switch (e.getID()) {
            case KeyEvent.KEY_TYPED:
--- a/jdk/src/java.desktop/windows/classes/sun/awt/windows/WWindowPeer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/windows/classes/sun/awt/windows/WWindowPeer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -80,6 +80,8 @@
      * WindowStateEvent is posted to the EventQueue.
      */
     private WindowListener windowListener;
+    private float scaleX;
+    private float scaleY;
 
     /**
      * Initialize JNI field IDs
@@ -190,7 +192,10 @@
 
         // Express our interest in display changes
         GraphicsConfiguration gc = getGraphicsConfiguration();
-        ((Win32GraphicsDevice)gc.getDevice()).addDisplayChangedListener(this);
+        Win32GraphicsDevice gd = (Win32GraphicsDevice) gc.getDevice();
+        gd.addDisplayChangedListener(this);
+        scaleX = gd.getDefaultScaleX();
+        scaleY = gd.getDefaultScaleY();
 
         initActiveWindowsTracking((Window)target);
 
@@ -539,6 +544,22 @@
 
         AWTAccessor.getComponentAccessor().
             setGraphicsConfiguration((Component)target, winGraphicsConfig);
+
+        checkDPIChange(oldDev, newDev);
+    }
+
+    private void checkDPIChange(Win32GraphicsDevice oldDev,
+                                Win32GraphicsDevice newDev) {
+        float newScaleX = newDev.getDefaultScaleX();
+        float newScaleY = newDev.getDefaultScaleY();
+
+        if (scaleX != newScaleX || scaleY != newScaleY) {
+            if (oldDev.getScreen() == newDev.getScreen()) {
+                windowDPIChange(scaleX, scaleY, newScaleX, newScaleY);
+            }
+            scaleX = newScaleX;
+            scaleY = newScaleY;
+        }
     }
 
     /**
@@ -781,6 +802,9 @@
         }
     }
 
+    native void windowDPIChange(float prevScaleX, float prevScaleY,
+                                float newScaleX, float newScaleY);
+
     /*
      * The method maps the list of the active windows to the window's AppContext,
      * then the method registers ActiveWindowListener, GuiDisposedListener listeners;
--- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_Component.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -950,8 +950,11 @@
     return 1;
 }
 
-
-void AwtComponent::Reshape(int x, int y, int w, int h)
+void AwtComponent::Reshape(int x, int y, int w, int h) {
+    ReshapeNoScale(ScaleUpX(x), ScaleUpY(y), ScaleUpX(w), ScaleUpY(h));
+}
+
+void AwtComponent::ReshapeNoScale(int x, int y, int w, int h)
 {
 #if defined(DEBUG)
     RECT        rc;
@@ -960,11 +963,6 @@
     DTRACE_PRINTLN4("AwtComponent::Reshape from %d, %d, %d, %d", rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top);
 #endif
 
-    x = ScaleUpX(x);
-    y = ScaleUpY(y);
-    w = ScaleUpX(w);
-    h = ScaleUpY(h);
-
     AwtWindow* container = GetContainer();
     AwtComponent* parent = GetParent();
     if (container != NULL && container == parent) {
--- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_Component.h	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_Component.h	Thu Mar 16 20:47:03 2017 +0000
@@ -275,6 +275,7 @@
     virtual void Show();
     virtual void Hide();
     virtual void Reshape(int x, int y, int w, int h);
+    void ReshapeNoScale(int x, int y, int w, int h);
 
     /*
      * Fix for 4046446.
--- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_Window.cpp	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_Window.cpp	Thu Mar 16 20:47:03 2017 +0000
@@ -153,6 +153,14 @@
     jboolean isFSEMState;
 };
 
+// struct for _WindowDPIChange() method
+struct ScaleStruct {
+    jobject window;
+    jfloat prevScaleX;
+    jfloat prevScaleY;
+    jfloat scaleX;
+    jfloat scaleY;
+};
 
 /************************************************************************
  * AwtWindow fields
@@ -1753,6 +1761,9 @@
     (env)->SetIntField(peer, AwtWindow::sysYID, ScaleDownY(rect.top));
     SendComponentEvent(java_awt_event_ComponentEvent_COMPONENT_MOVED);
 
+    prevX = rect.left;
+    prevY = rect.top;
+
     env->DeleteLocalRef(target);
     return AwtComponent::WmMove(x, y);
 }
@@ -2053,6 +2064,8 @@
     int curScrn = GetScreenImOn();
 
     if (curScrn != m_screenNum) {  // we've been moved
+        int prevScrn = m_screenNum;
+
         JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
 
         jclass peerCls = env->GetObjectClass(m_peerObject);
@@ -2068,12 +2081,81 @@
         }
 
         env->CallVoidMethod(m_peerObject, draggedID);
+
         m_screenNum = curScrn;
+        WindowDPIChange(prevScrn, curScrn);
 
         env->DeleteLocalRef(peerCls);
     }
 }
 
+int Disposition(int x1, int x2, int x) {
+    return x < x1 ? -1 : (x > x2 ? 1 : 0);
+}
+
+void AwtWindow::WindowDPIChange(int prevScreen, int screen) {
+    Devices::InstanceAccess devices;
+    AwtWin32GraphicsDevice* prevDevice = devices->GetDevice(prevScreen);
+    AwtWin32GraphicsDevice* device = devices->GetDevice(screen);
+
+    if (prevDevice && device) {
+        RECT prevBounds;
+        RECT bounds;
+
+        if (MonitorBounds(prevDevice->GetMonitor(), &prevBounds)
+            && MonitorBounds(device->GetMonitor(), &bounds)) {
+            int x;
+            int y;
+            int dx;
+            int dy;
+            RECT rect;
+
+            ::GetWindowRect(GetHWnd(), &rect);
+            x = rect.left;
+            y = rect.top;
+            dx = x - prevX;
+            dy = y - prevY;
+
+            if (dx != 0 || dy != 0) {
+                int w = rect.right - rect.left;
+                int h = rect.bottom - rect.top;
+                int dispX = Disposition(prevBounds.left, prevBounds.right,
+                    (bounds.left + bounds.right) / 2);
+                int dispY = Disposition(prevBounds.top, prevBounds.bottom,
+                    (bounds.top + bounds.bottom) / 2);
+
+                w = w * device->GetScaleX() / prevDevice->GetScaleX();
+                h = h * device->GetScaleY() / prevDevice->GetScaleY();
+
+                prevX = x;
+                prevY = y;
+
+                if (dx != 0 && dispX != 0) {
+                    x = dispX > 0 ? bounds.left : bounds.right - w;
+                    y = min(y, bounds.top);
+                    ReshapeNoScale(x, y, w, h);
+                } else if (dy != 0 && dispY != 0) {
+                    x = max(x, bounds.left);
+                    y = dispY > 0 ? bounds.top : bounds.bottom - h;
+                    ReshapeNoScale(x, y, w, h);
+                }
+            }
+        }
+    }
+}
+
+void AwtWindow::WindowDPIChange(float prevScaleX, float prevScaleY, float scaleX, float scaleY) {
+    int w;
+    int h;
+    RECT rect;
+
+    ::GetWindowRect(GetHWnd(), &rect);
+
+    w = (rect.right - rect.left) * scaleX / prevScaleX;
+    h = (rect.bottom - rect.top) * scaleY / prevScaleY;
+    ReshapeNoScale(rect.left, rect.top, w, h);
+}
+
 BOOL AwtWindow::IsFocusableWindow() {
     /*
      * For Window/Frame/Dialog to accept focus it should:
@@ -3102,6 +3184,29 @@
 
     env->DeleteGlobalRef(self);
 }
+
+void AwtWindow::_WindowDPIChange(void* param)
+{
+    JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
+
+    ScaleStruct *ss = (ScaleStruct *)param;
+    jobject self = ss->window;
+    jfloat prevScaleX = ss->prevScaleX;
+    jfloat prevScaleY = ss->prevScaleY;
+    jfloat scaleX = ss->scaleX;
+    jfloat scaleY = ss->scaleY;
+
+    PDATA pData;
+    JNI_CHECK_PEER_GOTO(self, ret);
+    AwtWindow *window = (AwtWindow *)pData;
+
+    window->WindowDPIChange(prevScaleX, prevScaleY, scaleX, scaleY);
+
+ret:
+    env->DeleteGlobalRef(self);
+    delete ss;
+}
+
 extern "C" int getSystemMetricValue(int msgType);
 extern "C" {
 
@@ -3800,4 +3905,27 @@
     CATCH_BAD_ALLOC;
 }
 
+/*
+* Class:     sun_awt_windows_WWindowPeer
+* Method:    windowDPIChange
+* Signature: (FFFF)V
+*/
+JNIEXPORT void JNICALL
+Java_sun_awt_windows_WWindowPeer_windowDPIChange(JNIEnv *env, jobject self,
+    jfloat prevScaleX, jfloat prevScaleY, jfloat scaleX, jfloat scaleY)
+{
+    TRY;
+
+    ScaleStruct *ss = new ScaleStruct;
+    ss->window = env->NewGlobalRef(self);
+    ss->prevScaleX = prevScaleX;
+    ss->prevScaleY = prevScaleY;
+    ss->scaleX = scaleX;
+    ss->scaleY = scaleY;
+
+    AwtToolkit::GetInstance().InvokeFunction(AwtWindow::_WindowDPIChange, ss);
+    // global refs and ss are deleted in _WindowDPIChange
+
+    CATCH_BAD_ALLOC;
+}
 } /* extern "C" */
--- a/jdk/src/java.desktop/windows/native/libawt/windows/awt_Window.h	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.desktop/windows/native/libawt/windows/awt_Window.h	Thu Mar 16 20:47:03 2017 +0000
@@ -242,6 +242,7 @@
     static void _RepositionSecurityWarning(void* param);
     static void _SetFullScreenExclusiveModeState(void* param);
     static void _GetNativeWindowSize(void* param);
+    static void _WindowDPIChange(void* param);
 
     inline static BOOL IsResizing() {
         return sm_resizing;
@@ -383,8 +384,12 @@
 
 private:
     int m_screenNum;
+    int prevX;
+    int prevY;
 
     void InitOwner(AwtWindow *owner);
+    void WindowDPIChange(int prevScreen, int newScreen);
+    void WindowDPIChange(float prevScaleX, float prevScaleY, float scaleX, float scaleY);
 
     Type m_windowType;
     void InitType(JNIEnv *env, jobject peer);
--- a/jdk/src/java.instrument/share/classes/java/lang/instrument/ClassFileTransformer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.instrument/share/classes/java/lang/instrument/ClassFileTransformer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -229,6 +229,7 @@
      *         or {@code null} if no transform is performed
      *
      * @since  9
+     * @spec JPMS
      */
     default byte[]
     transform(  Module              module,
--- a/jdk/src/java.instrument/share/classes/java/lang/instrument/Instrumentation.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.instrument/share/classes/java/lang/instrument/Instrumentation.java	Thu Mar 16 20:47:03 2017 +0000
@@ -714,6 +714,7 @@
      * @throws NullPointerException if any of the arguments are {@code null} or
      *         any of the Sets or Maps contains a {@code null} key or value
      * @since 9
+     * @spec JPMS
      */
     void redefineModule(Module module,
                         Set<Module> extraReads,
--- a/jdk/src/java.instrument/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.instrument/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,6 +26,8 @@
 /**
  * Defines services that allow agents to
  * instrument programs running on the JVM.
+ *
+ * @since 9
  */
 module java.instrument {
     exports java.lang.instrument;
--- a/jdk/src/java.logging/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.logging/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines the Java Logging API.
+ *
+ * @since 9
  */
 module java.logging {
     exports java.util.logging;
--- a/jdk/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.management.rmi/share/classes/javax/management/remote/rmi/RMIConnector.java	Thu Mar 16 20:47:03 2017 +0000
@@ -38,6 +38,7 @@
 import java.io.ObjectInputStream;
 import java.io.ObjectStreamClass;
 import java.io.Serializable;
+import java.lang.module.ModuleDescriptor;
 import java.lang.ref.WeakReference;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationHandler;
@@ -107,6 +108,8 @@
 import sun.rmi.transport.LiveRef;
 import java.io.NotSerializableException;
 
+import static java.lang.module.ModuleDescriptor.Modifier.SYNTHETIC;
+
 /**
  * <p>A connection to a remote RMI connector.  Usually, such
  * connections are made using {@link
@@ -2020,8 +2023,14 @@
                 Module rmiModule = RemoteRef.class.getModule();
 
                 String pkg = packageOf(pRefClassName);
-                assert pkg != null && pkg.length() > 0 && !pkg.equals(packageOf(proxyRefCName));
-                Module m = Modules.defineModule(cl, "jdk.remoteref", Collections.singleton(pkg));
+                assert pkg != null && pkg.length() > 0 &&
+                        !pkg.equals(packageOf(proxyRefCName));
+
+                ModuleDescriptor descriptor =
+                    ModuleDescriptor.newModule("jdk.remoteref", Set.of(SYNTHETIC))
+                        .packages(Set.of(pkg))
+                        .build();
+                Module m = Modules.defineModule(cl, descriptor, null);
 
                 // jdk.remoteref needs to read to java.base and jmxModule
                 Modules.addReads(m, Object.class.getModule());
--- a/jdk/src/java.management.rmi/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.management.rmi/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -46,6 +46,7 @@
  *           and load the appropriate {@code JMXConnectorServerProvider} service
  *           implementation for the given protocol.
  *
+ * @since 9
  */
 module java.management.rmi {
 
--- a/jdk/src/java.management/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.management/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -28,6 +28,8 @@
  * <P>
  * The JMX API consists of interfaces for monitoring and management of the
  * JVM and other components in the Java runtime.
+ *
+ * @since 9
  */
 module java.management {
 
--- a/jdk/src/java.naming/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.naming/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines the Java Naming and Directory Interface (JNDI) API.
+ *
+ * @since 9
  */
 module java.naming {
     requires java.security.sasl;
--- a/jdk/src/java.prefs/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.prefs/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines the Preferences API.
+ *
+ * @since 9
  */
 module java.prefs {
     requires java.xml;
--- a/jdk/src/java.rmi/share/classes/java/rmi/activation/ActivationInstantiator.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.rmi/share/classes/java/rmi/activation/ActivationInstantiator.java	Thu Mar 16 20:47:03 2017 +0000
@@ -60,7 +60,20 @@
     * initialization data, and
     *
     * <li> returning a MarshalledObject containing the stub for the
-    * remote object it created </ul>
+    * remote object it created.</ul>
+    *
+    * <p>In order for activation to be successful, one of the following requirements
+    * must be met, otherwise {@link ActivationException} is thrown:
+    *
+    * <ul><li>The class to be activated and the special activation constructor are both public,
+    * and the class resides in a package that is
+    * {@linkplain java.lang.reflect.Module#isExported(String,java.lang.reflect.Module) exported}
+    * to at least the {@code java.rmi} module; or
+    *
+    * <li>The class to be activated resides in a package that is
+    * {@linkplain java.lang.reflect.Module#isOpen(String,java.lang.reflect.Module) open}
+    * to at least the {@code java.rmi} module.
+    * </ul>
     *
     * @param id the object's activation identifier
     * @param desc the object's descriptor
--- a/jdk/src/java.rmi/share/classes/java/rmi/activation/Activator.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.rmi/share/classes/java/rmi/activation/Activator.java	Thu Mar 16 20:47:03 2017 +0000
@@ -48,7 +48,7 @@
  * The <code>Activator</code> works closely with
  * <code>ActivationSystem</code>, which provides a means for registering
  * groups and objects within those groups, and <code>ActivationMonitor</code>,
- * which recives information about active and inactive objects and inactive
+ * which receives information about active and inactive objects and inactive
  * groups. <p>
  *
  * The activator is responsible for monitoring and detecting when
--- a/jdk/src/java.rmi/share/classes/java/rmi/server/UnicastRemoteObject.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.rmi/share/classes/java/rmi/server/UnicastRemoteObject.java	Thu Mar 16 20:47:03 2017 +0000
@@ -107,8 +107,9 @@
  * the binary name of the root class with the suffix {@code _Stub}.
  *
  * <li>The stub class is loaded by name using the class loader of the root
- * class. The stub class must extend {@link RemoteStub} and must have a
- * public constructor that has one parameter of type {@link RemoteRef}.
+ * class. The stub class must be public, it must extend {@link RemoteStub}, it must
+ * reside in a package that is exported to at least the {@code java.rmi} module, and it
+ * must have a public constructor that has one parameter of type {@link RemoteRef}.
  *
  * <li>Finally, an instance of the stub class is constructed with a
  * {@link RemoteRef}.
@@ -124,12 +125,21 @@
  *
  * <ul>
  *
- * <li>The proxy's class is defined by the class loader of the remote
- * object's class.
+ * <li>The proxy's class is defined according to the specifications for the
+ * <a href="{@docRoot}/java/lang/reflect/Proxy.html#membership">
+ * {@code Proxy}
+ * </a>
+ * class, using the class loader of the remote object's class.
  *
  * <li>The proxy implements all the remote interfaces implemented by the
  * remote object's class.
  *
+ * <li>Each remote interface must either be public and reside in a package that is
+ * {@linkplain java.lang.reflect.Module#isExported(String,java.lang.reflect.Module) exported}
+ * to at least the {@code java.rmi} module, or it must reside in a package that is
+ * {@linkplain java.lang.reflect.Module#isOpen(String,java.lang.reflect.Module) open}
+ * to at least the {@code java.rmi} module.
+ *
  * <li>The proxy's invocation handler is a {@link
  * RemoteObjectInvocationHandler} instance constructed with a
  * {@link RemoteRef}.
--- a/jdk/src/java.rmi/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.rmi/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines the Remote Method Invocation (RMI) API.
+ *
+ * @since 9
  */
 module java.rmi {
     requires java.logging;
--- a/jdk/src/java.scripting/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.scripting/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines the Scripting API.
+ *
+ * @since 9
  */
 module java.scripting {
     exports javax.script;
--- a/jdk/src/java.se.ee/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.se.ee/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -28,6 +28,8 @@
  * <P>
  * This module requires {@code java.se} and supplements it with modules
  * that define CORBA and Java EE APIs. These modules are upgradeable.
+ *
+ * @since 9
  */
 @SuppressWarnings("deprecation")
 module java.se.ee {
--- a/jdk/src/java.se/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.se/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -28,6 +28,8 @@
  * <P>
  * The modules defining CORBA and Java EE APIs are not required by
  * this module, but they are required by {@code java.se.ee}.
+ *
+ * @since 9
  */
 module java.se {
     requires transitive java.compiler;
--- a/jdk/src/java.security.jgss/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.security.jgss/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -27,6 +27,8 @@
  * Defines the Java binding of the IETF Generic Security Services API (GSS-API).
  * <P>
  * This module also contains GSS-API mechanisms including Kerberos v5 and SPNEGO.
+ *
+ * @since 9
  */
 module java.security.jgss {
     requires java.naming;
--- a/jdk/src/java.security.sasl/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.security.sasl/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -29,6 +29,8 @@
  * <P>
  * This module also contains SASL mechanisms including DIGEST-MD5,
  * CRAM-MD5, and NTLM.
+ *
+ * @since 9
  */
 module java.security.sasl {
     requires java.logging;
--- a/jdk/src/java.smartcardio/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.smartcardio/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines the Java Smart Card I/O API.
+ *
+ * @since 9
  */
 module java.smartcardio {
     exports javax.smartcardio;
--- a/jdk/src/java.sql.rowset/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.sql.rowset/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines the JDBC RowSet API.
+ *
+ * @since 9
  */
 module java.sql.rowset {
     requires transitive java.logging;
--- a/jdk/src/java.sql/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.sql/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines the JDBC API.
+ *
+ * @since 9
  */
 module java.sql {
     requires transitive java.logging;
--- a/jdk/src/java.transaction/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.transaction/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -28,6 +28,8 @@
  * <P>
  * The subset consists of RMI exception types which are mapped to CORBA system
  * exceptions by the 'Java Language to IDL Mapping Specification'.
+ *
+ * @since 9
  */
 module java.transaction {
     requires transitive java.rmi;
--- a/jdk/src/java.xml.crypto/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/java.xml.crypto/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines an API for XML cryptography.
+ *
+ * @since 9
  */
 module java.xml.crypto {
     requires transitive java.xml;
--- a/jdk/src/jdk.attach/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.attach/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines the attach API.
+ *
+ * @since 9
  */
 module jdk.attach {
     requires jdk.internal.jvmstat;
--- a/jdk/src/jdk.crypto.ucrypto/solaris/conf/security/ucrypto-solaris.cfg	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.crypto.ucrypto/solaris/conf/security/ucrypto-solaris.cfg	Thu Mar 16 20:47:03 2017 +0000
@@ -2,8 +2,5 @@
 # Configuration file for the OracleUcrypto provider
 #
 disabledServices = {
-  # disabled due to Solaris bug 7121679
-  Cipher.AES/CFB128/PKCS5Padding
-  Cipher.AES/CFB128/NoPadding
 }
 
--- a/jdk/src/jdk.desktop/share/classes/jdk/awt/AWTUtils.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,95 +0,0 @@
-/*
- * 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.
- */
-
-package jdk.awt;
-
-import java.awt.Component;
-import java.awt.Shape;
-
-import com.sun.awt.AWTUtilities;
-
-/**
- * A class to allow access to JDK-specific utility methods.
- * Methods in this class are always deprecated since a caller
- * should be aware they may be removed and replaced in the future.
- * Access using reflection is highly recommended.
- * @since 9
- */
-public final class AWTUtils {
-
-    /**
-     * No-one should be creating instances of this class.
-     */
-    private AWTUtils() {
-    }
-
-    /**
-     * Sets a 'mixing-cutout' shape for the given component.
-     *
-     * By default a lightweight component is treated as an opaque rectangle for
-     * the purposes of the Heavyweight/Lightweight Components Mixing feature.
-     * This method enables developers to set an arbitrary shape to be cut out
-     * from heavyweight components positioned underneath the lightweight
-     * component in the z-order.
-     * <p>
-     * The {@code shape} argument may have the following values:
-     * <ul>
-     * <li>{@code null} - reverts the default cutout shape (the rectangle equal
-     * to the component's {@code getBounds()})
-     * <li><i>empty-shape</i> - does not cut out anything from heavyweight
-     * components. This makes the given lightweight component effectively
-     * transparent. Note that descendants of the lightweight component still
-     * affect the shapes of heavyweight components.  An example of an
-     * <i>empty-shape</i> is {@code new Rectangle()}.
-     * <li><i>non-empty-shape</i> - the given shape will be cut out from
-     * heavyweight components.
-     * </ul>
-     * <p>
-     * The most common example when the 'mixing-cutout' shape is needed is a
-     * glass pane component. The {@link JRootPane#setGlassPane()} method
-     * automatically sets the <i>empty-shape</i> as the 'mixing-cutout' shape
-     * for the given glass pane component.  If a developer needs some other
-     * 'mixing-cutout' shape for the glass pane (which is rare), this must be
-     * changed manually after installing the glass pane to the root pane.
-     * <p>
-     * Note that the 'mixing-cutout' shape neither affects painting, nor the
-     * mouse events handling for the given component. It is used exclusively
-     * for the purposes of the Heavyweight/Lightweight Components Mixing
-     * feature.
-     *
-     * @param component the component that needs non-default
-     * 'mixing-cutout' shape
-     * @param shape the new 'mixing-cutout' shape
-     * @throws NullPointerException if the component argument is {@code null}
-     * @deprecated This API may be removed or replaced.
-     */
-    @Deprecated
-    @SuppressWarnings("deprecation")
-    public static void setComponentMixingCutoutShape(Component component,
-                                                     Shape shape) {
-
-        AWTUtilities.setComponentMixingCutoutShape(component, shape);
-    }
-}
--- a/jdk/src/jdk.desktop/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,34 +0,0 @@
-/*
- * 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.
- */
-
-/*
- * Provides non-SE desktop APIs.
- */
-
-module jdk.desktop {
-    requires transitive java.desktop;
-
-    exports jdk.awt;
-}
--- a/jdk/src/jdk.editpad/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.editpad/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Implementation of the edit pad service.
+ *
+ * @since 9
  */
 module jdk.editpad {
     requires jdk.internal.ed;
--- a/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/AsyncSSLDelegate.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/AsyncSSLDelegate.java	Thu Mar 16 20:47:03 2017 +0000
@@ -609,11 +609,13 @@
         }
 
         // SSLParameters.getApplicationProtocols() can't return null
+        // JDK 8 EXCL START
         for (String approto : p.getApplicationProtocols()) {
             sb.append("\n    application protocol: {")
               .append(params.size()).append("}");
             params.add(approto);
         }
+        // JDK 8 EXCL END
 
         if (p.getProtocols() != null) {
             for (String protocol : p.getProtocols()) {
--- a/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/DefaultPublisher.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/DefaultPublisher.java	Thu Mar 16 20:47:03 2017 +0000
@@ -91,11 +91,13 @@
                         for (long i = 0; i < nbItemsDemanded && !done.get(); i++) {
                             try {
                                 Optional<T> item = Objects.requireNonNull(supplier.get());
-                                item.ifPresentOrElse(subscriber::onNext, () -> {
+                                if (item.isPresent()) {
+                                    subscriber.onNext(item.get());
+                                } else {
                                     if (done.compareAndSet(false, true)) {
                                         subscriber.onComplete();
                                     }
-                                });
+                                }
                             } catch (RuntimeException e) {
                                 if (done.compareAndSet(false, true)) {
                                     subscriber.onError(e);
--- a/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/HttpResponse.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/HttpResponse.java	Thu Mar 16 20:47:03 2017 +0000
@@ -30,6 +30,8 @@
 import java.net.URI;
 import jdk.incubator.http.ResponseProcessors.MultiFile;
 import jdk.incubator.http.ResponseProcessors.MultiProcessorImpl;
+import static jdk.incubator.http.internal.common.Utils.unchecked;
+import static jdk.incubator.http.internal.common.Utils.charsetFrom;
 import java.nio.ByteBuffer;
 import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
@@ -269,19 +271,6 @@
             };
         }
 
-        /**
-         * Get the Charset from the Content-encoding header. Defaults to
-         * UTF_8
-         */
-        private static Charset charsetFrom(HttpHeaders headers) {
-            String encoding = headers.firstValue("Content-encoding")
-                    .orElse("UTF_8");
-            try {
-                return Charset.forName(encoding);
-            } catch (IllegalArgumentException e) {
-                return StandardCharsets.UTF_8;
-            }
-        }
 
         /**
          * Returns a {@code BodyHandler<Path>} that returns a
@@ -342,10 +331,6 @@
             };
         }
 
-        private static UncheckedIOException unchecked(IOException e) {
-            return new UncheckedIOException(e);
-        }
-
         /**
          * Returns a {@code BodyHandler<Path>} that returns a
          * {@link BodyProcessor BodyProcessor}{@code <Path>} obtained from
@@ -743,48 +728,5 @@
             return asMap(pushHandler, true);
         }
 
-        /**
-         * Returns a {@code MultiProcessor} which writes the response bodies to
-         * files under a given root directory and which returns an aggregate
-         * response map that is a {@code Map<HttpRequest, HttpResponse<Path>>}.
-         * The keyset of the {@code Map} represents the original request and any
-         * additional requests generated by the server. The values are the
-         * responses containing the paths of the destination files. Each file
-         * uses the URI path of the request relative to the destination parent
-         * directorycprovided.
-         *
-         * <p>
-         * All incoming additional requests (push promises) are accepted by this
-         * multi response processor. Errors are effectively ignored and any
-         * failed responses are simply omitted from the result {@code Map}.
-         * Other implementations of {@code MultiProcessor} may handle these
-         * situations.
-         *
-         * <p>
-         * <b>Example usage</b>
-         * <pre>
-         * {@code
-         *    HttpClient client = ..
-         *    HttpRequest request = HttpRequest
-         *               .create(new URI("https://www.foo.com/"))
-         *               .version(Version.HTTP2)
-         *               .GET();
-         *
-         *    Map<HttpRequest, HttpResponse<Path>>> map = client
-         *               .sendAsync(HttpResponse.MultiProcessor.multiFile("/usr/destination"))
-         *               .join();
-         *
-         * }
-         * </pre>
-         * TEMPORARILY REMOVING THIS FROM API. MIGHT NOT BE NEEDED.
-         *
-         * @param destination the destination parent directory of all response
-         * bodies
-         * @return a MultiProcessor
-         */
-        private static MultiProcessor<MultiMapResult<Path>,Path> multiFile(Path destination) {
-            MultiFile mf = new MultiFile(destination);
-            return new MultiProcessorImpl<Path>(mf::handlePush, true);
-        }
     }
 }
--- a/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/ResponseProcessors.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/ResponseProcessors.java	Thu Mar 16 20:47:03 2017 +0000
@@ -252,7 +252,7 @@
 
         @Override
         public void onError(HttpRequest request, Throwable t) {
-            results.put(request, CompletableFuture.failedFuture(t));
+            results.put(request, MinimalFuture.failedFuture(t));
         }
 
         @Override
--- a/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/SSLDelegate.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/SSLDelegate.java	Thu Mar 16 20:47:03 2017 +0000
@@ -449,9 +449,11 @@
         for (String cipher : p.getCipherSuites()) {
                 System.out.printf("cipher: %s\n", cipher);
         }
+        // JDK 8 EXCL START
         for (String approto : p.getApplicationProtocols()) {
                 System.out.printf("application protocol: %s\n", approto);
         }
+        // JDK 8 EXCL END
         for (String protocol : p.getProtocols()) {
                 System.out.printf("protocol: %s\n", protocol);
         }
--- a/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/common/MinimalFuture.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/common/MinimalFuture.java	Thu Mar 16 20:47:03 2017 +0000
@@ -110,7 +110,6 @@
         }
     }
 
-    @Override
     public <U> MinimalFuture<U> newIncompleteFuture() {
         return new MinimalFuture<>();
     }
--- a/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/common/Queue.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/common/Queue.java	Thu Mar 16 20:47:03 2017 +0000
@@ -118,11 +118,13 @@
     public synchronized void closeExceptionally(Throwable t) {
         if (exception == null) exception = t;
         else if (t != null && t != exception) {
-            Stream.of(exception.getSuppressed())
+            if (!Stream.of(exception.getSuppressed())
                 .filter(x -> x == t)
                 .findFirst()
-                .ifPresentOrElse((x) -> {},
-                                 () -> exception.addSuppressed(t));
+                .isPresent())
+            {
+                exception.addSuppressed(t);
+            }
         }
         close();
     }
--- a/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/common/Utils.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/common/Utils.java	Thu Mar 16 20:47:03 2017 +0000
@@ -32,12 +32,14 @@
 import java.io.ByteArrayOutputStream;
 import java.io.Closeable;
 import java.io.IOException;
+import java.io.UncheckedIOException;
 import java.io.PrintStream;
 import java.io.UnsupportedEncodingException;
 import java.net.NetPermission;
 import java.net.URI;
 import java.net.URLPermission;
 import java.nio.ByteBuffer;
+import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
@@ -54,6 +56,7 @@
 import java.util.concurrent.Executors;
 import java.util.concurrent.LinkedBlockingQueue;
 import java.util.function.Predicate;
+import jdk.incubator.http.HttpHeaders;
 
 /**
  * Miscellaneous utilities
@@ -259,9 +262,11 @@
         SSLParameters p1 = new SSLParameters();
         p1.setAlgorithmConstraints(p.getAlgorithmConstraints());
         p1.setCipherSuites(p.getCipherSuites());
+        // JDK 8 EXCL START
         p1.setEnableRetransmissions(p.getEnableRetransmissions());
+        p1.setMaximumPacketSize(p.getMaximumPacketSize());
+        // JDK 8 EXCL END
         p1.setEndpointIdentificationAlgorithm(p.getEndpointIdentificationAlgorithm());
-        p1.setMaximumPacketSize(p.getMaximumPacketSize());
         p1.setNeedClientAuth(p.getNeedClientAuth());
         String[] protocols = p.getProtocols();
         if (protocols != null) {
@@ -475,4 +480,21 @@
         return newb;
     }
 
+    /**
+     * Get the Charset from the Content-encoding header. Defaults to
+     * UTF_8
+     */
+    public static Charset charsetFrom(HttpHeaders headers) {
+        String encoding = headers.firstValue("Content-encoding")
+                .orElse("UTF_8");
+        try {
+            return Charset.forName(encoding);
+        } catch (IllegalArgumentException e) {
+            return StandardCharsets.UTF_8;
+        }
+    }
+
+    public static UncheckedIOException unchecked(IOException e) {
+        return new UncheckedIOException(e);
+    }
 }
--- a/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/websocket/FrameConsumer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/websocket/FrameConsumer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,6 +26,7 @@
 package jdk.incubator.http.internal.websocket;
 
 import jdk.incubator.http.WebSocket.MessagePart;
+import jdk.incubator.http.internal.common.Log;
 import jdk.incubator.http.internal.websocket.Frame.Opcode;
 
 import java.nio.ByteBuffer;
@@ -33,13 +34,11 @@
 import java.nio.charset.CharacterCodingException;
 
 import static java.lang.String.format;
-import static java.lang.System.Logger.Level.TRACE;
 import static java.nio.charset.StandardCharsets.UTF_8;
 import static java.util.Objects.requireNonNull;
 import static jdk.incubator.http.internal.common.Utils.dump;
 import static jdk.incubator.http.internal.websocket.StatusCodes.NO_STATUS_CODE;
 import static jdk.incubator.http.internal.websocket.StatusCodes.checkIncomingCode;
-import static jdk.incubator.http.internal.websocket.WebSocketImpl.logger;
 
 /*
  * Consumes frame parts and notifies a message consumer, when there is
@@ -71,17 +70,13 @@
 
     @Override
     public void fin(boolean value) {
-        if (logger.isLoggable(TRACE)) {
-            logger.log(TRACE, "Reading fin: {0}", value);
-        }
+        Log.logTrace("Reading fin: {0}", value);
         fin = value;
     }
 
     @Override
     public void rsv1(boolean value) {
-        if (logger.isLoggable(TRACE)) {
-            logger.log(TRACE, "Reading rsv1: {0}", value);
-        }
+        Log.logTrace("Reading rsv1: {0}", value);
         if (value) {
             throw new FailWebSocketException("Unexpected rsv1 bit");
         }
@@ -89,9 +84,7 @@
 
     @Override
     public void rsv2(boolean value) {
-        if (logger.isLoggable(TRACE)) {
-            logger.log(TRACE, "Reading rsv2: {0}", value);
-        }
+        Log.logTrace("Reading rsv2: {0}", value);
         if (value) {
             throw new FailWebSocketException("Unexpected rsv2 bit");
         }
@@ -99,9 +92,7 @@
 
     @Override
     public void rsv3(boolean value) {
-        if (logger.isLoggable(TRACE)) {
-            logger.log(TRACE, "Reading rsv3: {0}", value);
-        }
+        Log.logTrace("Reading rsv3: {0}", value);
         if (value) {
             throw new FailWebSocketException("Unexpected rsv3 bit");
         }
@@ -109,7 +100,7 @@
 
     @Override
     public void opcode(Opcode v) {
-        logger.log(TRACE, "Reading opcode: {0}", v);
+        Log.logTrace("Reading opcode: {0}", v);
         if (v == Opcode.PING || v == Opcode.PONG || v == Opcode.CLOSE) {
             if (!fin) {
                 throw new FailWebSocketException("Fragmented control frame  " + v);
@@ -137,9 +128,7 @@
 
     @Override
     public void mask(boolean value) {
-        if (logger.isLoggable(TRACE)) {
-            logger.log(TRACE, "Reading mask: {0}", value);
-        }
+        Log.logTrace("Reading mask: {0}", value);
         if (value) {
             throw new FailWebSocketException("Masked frame received");
         }
@@ -147,10 +136,7 @@
 
     @Override
     public void payloadLen(long value) {
-        if (logger.isLoggable(TRACE)) {
-            // Checked for being loggable because of autoboxing of 'value'
-            logger.log(TRACE, "Reading payloadLen: {0}", value);
-        }
+        Log.logTrace("Reading payloadLen: {0}", value);
         if (opcode.isControl()) {
             if (value > 125) {
                 throw new FailWebSocketException(
@@ -178,9 +164,7 @@
 
     @Override
     public void payloadData(ByteBuffer data) {
-        if (logger.isLoggable(TRACE)) {
-            logger.log(TRACE, "Reading payloadData: data={0}", data);
-        }
+        Log.logTrace("Reading payloadData: data={0}", data);
         unconsumedPayloadLen -= data.remaining();
         boolean isLast = unconsumedPayloadLen == 0;
         if (opcode.isControl()) {
--- a/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/websocket/UTF8AccumulatingDecoder.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/websocket/UTF8AccumulatingDecoder.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 package jdk.incubator.http.internal.websocket;
 
+import jdk.incubator.http.internal.common.Log;
+
 import java.nio.ByteBuffer;
 import java.nio.CharBuffer;
 import java.nio.charset.CharacterCodingException;
@@ -32,10 +34,8 @@
 import java.nio.charset.CoderResult;
 import java.nio.charset.CodingErrorAction;
 
-import static java.lang.System.Logger.Level.WARNING;
 import static java.nio.charset.StandardCharsets.UTF_8;
 import static jdk.incubator.http.internal.common.Utils.EMPTY_BYTEBUFFER;
-import static jdk.incubator.http.internal.websocket.WebSocketImpl.logger;
 
 final class UTF8AccumulatingDecoder {
 
@@ -74,9 +74,8 @@
         // Since it's UTF-8, the assumption is leftovers.remaining() < 4
         // (i.e. small). Otherwise a shared buffer should be used
         if (!(leftovers.remaining() < 4)) {
-            logger.log(WARNING,
-                       "The size of decoding leftovers is greater than expected: {0}",
-                       leftovers.remaining());
+            Log.logError("The size of decoding leftovers is greater than expected: {0}",
+                         leftovers.remaining());
         }
         b.position(b.limit()); // As if we always read to the end
         // Decoder promises that in the case of endOfInput == true:
--- a/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/websocket/WebSocketImpl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.incubator.httpclient/share/classes/jdk/incubator/http/internal/websocket/WebSocketImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,6 +26,7 @@
 package jdk.incubator.http.internal.websocket;
 
 import jdk.incubator.http.WebSocket;
+import jdk.incubator.http.internal.common.Log;
 import jdk.incubator.http.internal.common.Pair;
 import jdk.incubator.http.internal.websocket.OpeningHandshake.Result;
 import jdk.incubator.http.internal.websocket.OutgoingMessage.Binary;
@@ -47,8 +48,6 @@
 import java.util.function.Consumer;
 import java.util.function.Function;
 
-import static java.lang.System.Logger.Level.ERROR;
-import static java.lang.System.Logger.Level.TRACE;
 import static java.util.Objects.requireNonNull;
 import static java.util.concurrent.CompletableFuture.failedFuture;
 import static jdk.incubator.http.internal.common.Pair.pair;
@@ -61,8 +60,6 @@
  */
 final class WebSocketImpl implements WebSocket {
 
-    static final System.Logger logger = System.getLogger("jdk.httpclient.WebSocket");
-
     private final URI uri;
     private final String subprotocol;
     private final RawChannel channel;
@@ -142,7 +139,7 @@
                     try {
                         channel.close();
                     } catch (IOException e) {
-                        logger.log(ERROR, e);
+                        Log.logError(e);
                     } finally {
                         closed.set(true);
                     }
@@ -168,14 +165,14 @@
     private void signalError(Throwable error) {
         synchronized (lock) {
             if (lastMethodInvoked) {
-                logger.log(ERROR, error);
+                Log.logError(error);
             } else {
                 lastMethodInvoked = true;
                 receiver.close();
                 try {
                     listener.onError(this, error);
                 } catch (Exception e) {
-                    logger.log(ERROR, e);
+                    Log.logError(e);
                 }
             }
         }
@@ -190,7 +187,7 @@
         try {
             channel.shutdownInput();
         } catch (IOException e) {
-            logger.log(ERROR, e);
+            Log.logError(e);
         }
         boolean wasComplete = !closeReceived.complete(null);
         if (wasComplete) {
@@ -210,7 +207,7 @@
             enqueueClose(new Close(code, ""))
                     .whenComplete((r1, error1) -> {
                         if (error1 != null) {
-                            logger.log(ERROR, error1);
+                            Log.logError(error1);
                         }
                     });
         });
@@ -223,14 +220,14 @@
     private CompletionStage<?> signalClose(int statusCode, String reason) {
         synchronized (lock) {
             if (lastMethodInvoked) {
-                logger.log(TRACE, "Close: {0}, ''{1}''", statusCode, reason);
+                Log.logTrace("Close: {0}, ''{1}''", statusCode, reason);
             } else {
                 lastMethodInvoked = true;
                 receiver.close();
                 try {
                     return listener.onClose(this, statusCode, reason);
                 } catch (Exception e) {
-                    logger.log(ERROR, e);
+                    Log.logError(e);
                 }
             }
         }
@@ -289,7 +286,7 @@
             try {
                 channel.shutdownOutput();
             } catch (IOException e) {
-                logger.log(ERROR, e);
+                Log.logError(e);
             }
             boolean wasComplete = !closeSent.complete(null);
             if (wasComplete) {
--- a/jdk/src/jdk.incubator.httpclient/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.incubator.httpclient/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,6 +26,8 @@
 /**
  * Defines the high-level HTTP and WebSocket API.
  * {@Incubating}
+ *
+ * @since 9
  */
 module jdk.incubator.httpclient {
     requires java.base;
--- a/jdk/src/jdk.internal.ed/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.internal.ed/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,6 +26,8 @@
 /**
  * Internal editor support for JDK tools.  Includes the Service Provider
  * Interface to built-in editors.
+ *
+ * @since 9
  */
 module jdk.internal.ed {
 
--- a/jdk/src/jdk.internal.le/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.internal.le/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Internal API for line editing
+ *
+ * @since 9
  */
 module jdk.internal.le {
     exports jdk.internal.jline to
--- a/jdk/src/jdk.internal.opt/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.internal.opt/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Internal option processing API
+ *
+ * @since 9
  */
 module jdk.internal.opt {
     exports jdk.internal.joptsimple to jdk.jlink, jdk.jshell;
--- a/jdk/src/jdk.jartool/share/classes/com/sun/jarsigner/ContentSigner.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jartool/share/classes/com/sun/jarsigner/ContentSigner.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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,7 +38,7 @@
  * @deprecated This class has been deprecated.
  */
 
-@Deprecated
+@Deprecated(since="9")
 public abstract class ContentSigner {
 
     /**
--- a/jdk/src/jdk.jartool/share/classes/com/sun/jarsigner/ContentSignerParameters.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jartool/share/classes/com/sun/jarsigner/ContentSignerParameters.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -36,7 +36,7 @@
  * @author Vincent Ryan
  * @deprecated This class has been deprecated.
  */
-@Deprecated
+@Deprecated(since="9")
 public interface ContentSignerParameters {
 
     /**
--- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/GNUStyleOptions.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/GNUStyleOptions.java	Thu Mar 16 20:47:03 2017 +0000
@@ -118,7 +118,7 @@
                 void process(Main jartool, String opt, String arg) {
                     jartool.nflag = true;
                 }
-                boolean isHidden() { return true; }
+                boolean isExtra() { return true; }
             },
             new Option(true, OptionType.CREATE_UPDATE, "--main-class", "-e") {
                 void process(Main jartool, String opt, String arg) {
@@ -157,8 +157,7 @@
                     for (String dir : dirs) {
                         paths[i++] = Paths.get(dir);
                     }
-                    jartool.moduleFinder =
-                        new ModulePath(Runtime.version(), true, paths);
+                    jartool.moduleFinder = ModulePath.of(Runtime.version(), true, paths);
                 }
             },
             new Option(false, OptionType.CREATE_UPDATE, "--do-not-resolve-by-default") {
--- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Main.java	Thu Mar 16 20:47:03 2017 +0000
@@ -158,7 +158,7 @@
     static final String MANIFEST_DIR = "META-INF/";
     static final String VERSIONS_DIR = MANIFEST_DIR + "versions/";
     static final String VERSION = "1.0";
-
+    static final int VERSIONS_DIR_LENGTH = VERSIONS_DIR.length();
     private static ResourceBundle rsrc;
 
     /**
@@ -681,7 +681,7 @@
     void addPackageIfNamed(Set<String> packages, String name) {
         if (name.startsWith(VERSIONS_DIR)) {
             // trim the version dir prefix
-            int i0 = VERSIONS_DIR.length();
+            int i0 = VERSIONS_DIR_LENGTH;
             int i = name.indexOf('/', i0);
             if (i <= 0) {
                 warn(formatMsg("warn.release.unexpected.versioned.entry", name));
@@ -699,7 +699,7 @@
         }
         String pn = toPackageName(name);
         // add if this is a class or resource in a package
-        if (Checks.isJavaIdentifier(pn)) {
+        if (Checks.isPackageName(pn)) {
             packages.add(pn);
         }
     }
@@ -1727,12 +1727,16 @@
     private boolean printModuleDescriptor(ZipFile zipFile)
         throws IOException
     {
-        ZipEntry entry = zipFile.getEntry(MODULE_INFO);
-        if (entry ==  null)
+        ZipEntry[] zes = zipFile.stream()
+            .filter(e -> isModuleInfoEntry(e.getName()))
+            .sorted(Validator.ENTRY_COMPARATOR)
+            .toArray(ZipEntry[]::new);
+        if (zes.length == 0)
             return false;
-
-        try (InputStream is = zipFile.getInputStream(entry)) {
-            printModuleDescriptor(is);
+        for (ZipEntry ze : zes) {
+            try (InputStream is = zipFile.getInputStream(ze)) {
+                printModuleDescriptor(is, ze.getName());
+            }
         }
         return true;
     }
@@ -1742,16 +1746,23 @@
     {
         try (BufferedInputStream bis = new BufferedInputStream(fis);
              ZipInputStream zis = new ZipInputStream(bis)) {
-
             ZipEntry e;
             while ((e = zis.getNextEntry()) != null) {
-                if (e.getName().equals(MODULE_INFO)) {
-                    printModuleDescriptor(zis);
-                    return true;
+                String ename = e.getName();
+                if (isModuleInfoEntry(ename)){
+                    moduleInfos.put(ename, zis.readAllBytes());
                 }
             }
         }
-        return false;
+        if (moduleInfos.size() == 0)
+            return false;
+        String[] names = moduleInfos.keySet().stream()
+            .sorted(Validator.ENTRYNAME_COMPARATOR)
+            .toArray(String[]::new);
+        for (String name : names) {
+            printModuleDescriptor(new ByteArrayInputStream(moduleInfos.get(name)), name);
+        }
+        return true;
     }
 
     static <T> String toString(Collection<T> set) {
@@ -1760,7 +1771,7 @@
                   .collect(joining(" "));
     }
 
-    private void printModuleDescriptor(InputStream entryInputStream)
+    private void printModuleDescriptor(InputStream entryInputStream, String ename)
         throws IOException
     {
         ModuleInfo.Attributes attrs = ModuleInfo.read(entryInputStream, null);
@@ -1768,10 +1779,12 @@
         ModuleHashes hashes = attrs.recordedHashes();
 
         StringBuilder sb = new StringBuilder();
-        sb.append("\n");
+        sb.append("\nmodule ")
+          .append(md.toNameAndVersion())
+          .append(" (").append(ename).append(")");
+
         if (md.isOpen())
-            sb.append("open ");
-        sb.append(md.toNameAndVersion());
+            sb.append("\n  open ");
 
         md.requires().stream()
             .sorted(Comparator.comparing(Requires::name))
@@ -1879,7 +1892,7 @@
             if (end == 0)
                 return true;
             if (name.startsWith(VERSIONS_DIR)) {
-                int off = VERSIONS_DIR.length();
+                int off = VERSIONS_DIR_LENGTH;
                 if (off == end)      // meta-inf/versions/module-info.class
                     return false;
                 while (off < end - 1) {
@@ -1995,7 +2008,7 @@
             }
             // get a resolved module graph
             Configuration config =
-                Configuration.empty().resolveRequires(system, finder, roots);
+                Configuration.empty().resolve(system, finder, roots);
 
             // filter modules resolved from the system module finder
             this.modules = config.modules().stream()
--- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Validator.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/Validator.java	Thu Mar 16 20:47:03 2017 +0000
@@ -49,6 +49,7 @@
 
 import static java.util.jar.JarFile.MANIFEST_NAME;
 import static sun.tools.jar.Main.VERSIONS_DIR;
+import static sun.tools.jar.Main.VERSIONS_DIR_LENGTH;
 import static sun.tools.jar.Main.MODULE_INFO;
 import static sun.tools.jar.Main.getMsg;
 import static sun.tools.jar.Main.formatMsg;
@@ -59,19 +60,19 @@
 final class Validator {
     private final static boolean DEBUG = Boolean.getBoolean("jar.debug");
     private final  Map<String,FingerPrint> fps = new HashMap<>();
-    private static final int vdlen = VERSIONS_DIR.length();
     private final Main main;
     private final JarFile jf;
     private int oldVersion = -1;
     private String currentTopLevelName;
     private boolean isValid = true;
-    private Set<String> concealedPkgs;
+    private Set<String> concealedPkgs = Collections.emptySet();
     private ModuleDescriptor md;
+    private String mdName;
 
     private Validator(Main main, JarFile jf) {
         this.main = main;
         this.jf = jf;
-        loadModuleDescriptor();
+        checkModuleDescriptor(MODULE_INFO);
     }
 
     static boolean validate(Main main, JarFile jf) throws IOException {
@@ -83,7 +84,7 @@
             jf.stream()
               .filter(e -> !e.isDirectory() &&
                       !e.getName().equals(MANIFEST_NAME))
-              .sorted(entryComparator)
+              .sorted(ENTRY_COMPARATOR)
               .forEachOrdered(e -> validate(e));
             return isValid;
         } catch (InvalidJarException e) {
@@ -102,9 +103,8 @@
     // sort base entries before versioned entries, and sort entry classes with
     // nested classes so that the top level class appears before the associated
     // nested class
-    private static Comparator<JarEntry> entryComparator = (je1, je2) ->  {
-        String s1 = je1.getName();
-        String s2 = je2.getName();
+    static Comparator<String> ENTRYNAME_COMPARATOR = (s1, s2) ->  {
+
         if (s1.equals(s2)) return 0;
         boolean b1 = s1.startsWith(VERSIONS_DIR);
         boolean b2 = s2.startsWith(VERSIONS_DIR);
@@ -140,6 +140,9 @@
         return l1 - l2;
     };
 
+    static Comparator<ZipEntry> ENTRY_COMPARATOR =
+        Comparator.comparing(ZipEntry::getName, ENTRYNAME_COMPARATOR);
+
     /*
      *  Validator has state and assumes entries provided to accept are ordered
      *  from base entries first and then through the versioned entries in
@@ -158,24 +161,25 @@
 
         // validate the versioned module-info
         if (isModuleInfoEntry(entryName)) {
-            if (entryName.length() != MODULE_INFO.length())
-                checkModuleDescriptor(je);
+            if (!entryName.equals(mdName))
+                checkModuleDescriptor(entryName);
             return;
         }
 
         // figure out the version and basename from the JarEntry
         int version;
         String basename;
+        String versionStr = null;;
         if (entryName.startsWith(VERSIONS_DIR)) {
-            int n = entryName.indexOf("/", vdlen);
+            int n = entryName.indexOf("/", VERSIONS_DIR_LENGTH);
             if (n == -1) {
                 error(formatMsg("error.validator.version.notnumber", entryName));
                 isValid = false;
                 return;
             }
-            String v = entryName.substring(vdlen, n);
+            versionStr = entryName.substring(VERSIONS_DIR_LENGTH, n);
             try {
-                version = Integer.parseInt(v);
+                version = Integer.parseInt(versionStr);
             } catch (NumberFormatException x) {
                 error(formatMsg("error.validator.version.notnumber", entryName));
                 isValid = false;
@@ -196,6 +200,11 @@
         if (oldVersion != version) {
             oldVersion = version;
             currentTopLevelName = null;
+            if (md == null && versionStr != null) {
+                // don't have a base module-info.class yet, try to see if
+                // a versioned one exists
+                checkModuleDescriptor(VERSIONS_DIR + versionStr + "/" + MODULE_INFO);
+            }
         }
 
         // analyze the entry, keeping key attributes
@@ -308,61 +317,52 @@
         return;
     }
 
-    private void loadModuleDescriptor() {
-        ZipEntry je = jf.getEntry(MODULE_INFO);
-        if (je != null) {
-            try (InputStream jis = jf.getInputStream(je)) {
-                md = ModuleDescriptor.read(jis);
-                concealedPkgs = new HashSet<>(md.packages());
-                md.exports().stream().map(Exports::source).forEach(concealedPkgs::remove);
-                md.opens().stream().map(Opens::source).forEach(concealedPkgs::remove);
-                return;
-            } catch (Exception x) {
-                error(x.getMessage() + " : " + je.getName());
-                this.isValid = false;
-            }
-        }
-        md = null;
-        concealedPkgs = Collections.emptySet();
-    }
-
-    private static boolean isPlatformModule(String name) {
-        return name.startsWith("java.") || name.startsWith("jdk.");
-    }
-
     /**
      * Checks whether or not the given versioned module descriptor's attributes
-     * are valid when compared against the root module descriptor.
+     * are valid when compared against the root/base module descriptor.
      *
-     * A versioned module descriptor must be identical to the root module
+     * A versioned module descriptor must be identical to the root/base module
      * descriptor, with two exceptions:
      *  - A versioned descriptor can have different non-public `requires`
      *    clauses of platform ( `java.*` and `jdk.*` ) modules, and
      *  - A versioned descriptor can have different `uses` clauses, even of
      *    service types defined outside of the platform modules.
      */
-    private void checkModuleDescriptor(JarEntry je) {
-        try (InputStream is = jf.getInputStream(je)) {
-            ModuleDescriptor root = this.md;
-            ModuleDescriptor md = null;
-            try {
-                md = ModuleDescriptor.read(is);
-            } catch (InvalidModuleDescriptorException x) {
-                error(x.getMessage());
-                isValid = false;
-                return;
-            }
-            if (root == null) {
-                this.md = md;
-            } else {
-                if (!root.name().equals(md.name())) {
+    private void checkModuleDescriptor(String miName) {
+        ZipEntry je = jf.getEntry(miName);
+        if (je != null) {
+            try (InputStream jis = jf.getInputStream(je)) {
+                ModuleDescriptor md = ModuleDescriptor.read(jis);
+                // Initialize the base md if it's not yet. A "base" md can be either the
+                // root module-info.class or the first versioned module-info.class
+                ModuleDescriptor base = this.md;
+
+                if (base == null) {
+                    concealedPkgs = new HashSet<>(md.packages());
+                    md.exports().stream().map(Exports::source).forEach(concealedPkgs::remove);
+                    md.opens().stream().map(Opens::source).forEach(concealedPkgs::remove);
+                    // must have the implementation class of the services it 'provides'.
+                    if (md.provides().stream().map(Provides::providers)
+                          .flatMap(List::stream)
+                          .filter(p -> jf.getEntry(toBinaryName(p)) == null)
+                          .peek(p -> error(formatMsg("error.missing.provider", p)))
+                          .count() != 0) {
+                        isValid = false;
+                        return;
+                    }
+                    this.md = md;
+                    this.mdName = miName;
+                    return;
+                }
+
+                if (!base.name().equals(md.name())) {
                     error(getMsg("error.validator.info.name.notequal"));
                     isValid = false;
                 }
-                if (!root.requires().equals(md.requires())) {
-                    Set<Requires> rootRequires = root.requires();
+                if (!base.requires().equals(md.requires())) {
+                    Set<Requires> baseRequires = base.requires();
                     for (Requires r : md.requires()) {
-                        if (rootRequires.contains(r))
+                        if (baseRequires.contains(r))
                             continue;
                         if (r.modifiers().contains(Requires.Modifier.TRANSITIVE)) {
                             error(getMsg("error.validator.info.requires.transitive"));
@@ -372,7 +372,7 @@
                             isValid = false;
                         }
                     }
-                    for (Requires r : rootRequires) {
+                    for (Requires r : baseRequires) {
                         Set<Requires> mdRequires = md.requires();
                         if (mdRequires.contains(r))
                             continue;
@@ -382,33 +382,37 @@
                         }
                     }
                 }
-                if (!root.exports().equals(md.exports())) {
+                if (!base.exports().equals(md.exports())) {
                     error(getMsg("error.validator.info.exports.notequal"));
                     isValid = false;
                 }
-                if (!root.opens().equals(md.opens())) {
+                if (!base.opens().equals(md.opens())) {
                     error(getMsg("error.validator.info.opens.notequal"));
                     isValid = false;
                 }
-                if (!root.provides().equals(md.provides())) {
+                if (!base.provides().equals(md.provides())) {
                     error(getMsg("error.validator.info.provides.notequal"));
                     isValid = false;
                 }
-                if (!root.mainClass().equals(md.mainClass())) {
+                if (!base.mainClass().equals(md.mainClass())) {
                     error(formatMsg("error.validator.info.manclass.notequal", je.getName()));
                     isValid = false;
                 }
-                if (!root.version().equals(md.version())) {
+                if (!base.version().equals(md.version())) {
                     error(formatMsg("error.validator.info.version.notequal", je.getName()));
                     isValid = false;
                 }
+            } catch (Exception x) {
+                error(x.getMessage() + " : " + miName);
+                this.isValid = false;
             }
-        } catch (IOException x) {
-            error(x.getMessage());
-            isValid = false;
         }
     }
 
+    private static boolean isPlatformModule(String name) {
+        return name.startsWith("java.") || name.startsWith("jdk.");
+    }
+
     private boolean checkInternalName(String entryName, String basename, String internalName) {
         String className = className(basename);
         if (internalName.equals(className)) {
--- a/jdk/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jartool/share/classes/sun/tools/jar/resources/jar.properties	Thu Mar 16 20:47:03 2017 +0000
@@ -238,6 +238,11 @@
 \                             of the jar (i.e. META-INF/versions/VERSION/)
 main.help.opt.any.verbose=\
 \  -v, --verbose              Generate verbose output on standard output
+main.help.opt.create=\
+\ Operation modifiers valid only in create mode:\n
+main.help.opt.create.normalize=\
+\  -n, --normalize            Normalize information in the new jar archive\n\
+\                             after creation
 main.help.opt.create.update=\
 \ Operation modifiers valid only in create and update mode:\n
 main.help.opt.create.update.main-class=\
--- a/jdk/src/jdk.jconsole/share/classes/sun/tools/jconsole/JConsole.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jconsole/share/classes/sun/tools/jconsole/JConsole.java	Thu Mar 16 20:47:03 2017 +0000
@@ -128,7 +128,7 @@
             hotspotMI.setMnemonic(Resources.getMnemonicInt(Messages.HOTSPOT_MBEANS_ELLIPSIS));
             hotspotMI.setAccelerator(KeyStroke.
                                      getKeyStroke(KeyEvent.VK_H,
-                                                  InputEvent.CTRL_MASK));
+                                                  InputEvent.CTRL_DOWN_MASK));
             hotspotMI.addActionListener(this);
             connectionMenu.add(hotspotMI);
 
@@ -138,7 +138,7 @@
         connectMI = new JMenuItem(Messages.NEW_CONNECTION_ELLIPSIS);
         connectMI.setMnemonic(Resources.getMnemonicInt(Messages.NEW_CONNECTION_ELLIPSIS));
         connectMI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_N,
-                                                        InputEvent.CTRL_MASK));
+                                                        InputEvent.CTRL_DOWN_MASK));
         connectMI.addActionListener(this);
         connectionMenu.add(connectMI);
 
@@ -147,7 +147,7 @@
         exitMI = new JMenuItem(Messages.EXIT);
         exitMI.setMnemonic(Resources.getMnemonicInt(Messages.EXIT));
         exitMI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_F4,
-                                                     InputEvent.ALT_MASK));
+                                                     InputEvent.ALT_DOWN_MASK));
         exitMI.addActionListener(this);
         connectionMenu.add(exitMI);
 
@@ -223,7 +223,7 @@
             tileMI = new JMenuItem(Messages.TILE);
             tileMI.setMnemonic(Resources.getMnemonicInt(Messages.TILE));
             tileMI.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_T,
-                                                         InputEvent.CTRL_MASK));
+                                                         InputEvent.CTRL_DOWN_MASK));
             tileMI.addActionListener(JConsole.this);
             add(tileMI);
 
--- a/jdk/src/jdk.jconsole/share/classes/sun/tools/jconsole/VMPanel.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jconsole/share/classes/sun/tools/jconsole/VMPanel.java	Thu Mar 16 20:47:03 2017 +0000
@@ -124,7 +124,9 @@
         addMouseListener(new MouseAdapter() {
 
             public void mouseClicked(MouseEvent e) {
-                if (connectedIconBounds != null && (e.getModifiers() & MouseEvent.BUTTON1_MASK) != 0 && connectedIconBounds.contains(e.getPoint())) {
+                if (connectedIconBounds != null
+                        && (e.getModifiersEx() & MouseEvent.BUTTON1_DOWN_MASK) != 0
+                        && connectedIconBounds.contains(e.getPoint())) {
 
                     if (isConnected()) {
                         userDisconnected = true;
--- a/jdk/src/jdk.jconsole/share/classes/sun/tools/jconsole/inspector/Utils.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jconsole/share/classes/sun/tools/jconsole/inspector/Utils.java	Thu Mar 16 20:47:03 2017 +0000
@@ -438,7 +438,7 @@
         public void keyPressed(KeyEvent e) {
             // Accept "copy" key strokes
             KeyStroke ks = KeyStroke.getKeyStroke(
-                    e.getKeyCode(), e.getModifiers());
+                    e.getKeyCode(), e.getModifiersEx());
             JComponent comp = (JComponent) e.getSource();
             for (int i = 0; i < 3; i++) {
                 InputMap im = comp.getInputMap(i);
--- a/jdk/src/jdk.jdi/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jdi/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Defines the Java Debugger Interface.
+ *
+ * @since 9
  */
 module jdk.jdi {
     requires jdk.attach;
--- a/jdk/src/jdk.jdwp.agent/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jdwp.agent/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Java Debug Wire Protocol.
+ *
+ * @since 9
  */
 module jdk.jdwp.agent {
 }
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jimage/resources/jimage.properties	Thu Mar 16 20:47:03 2017 +0000
@@ -98,3 +98,4 @@
 err.no.jimage=no jimage provided
 err.option.unsupported={0} not supported: {1}
 err.unknown.option=unknown option: {0}
+err.cannot.create.dir=cannot create directory {0}
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/builder/DefaultImageBuilder.java	Thu Mar 16 20:47:03 2017 +0000
@@ -362,7 +362,7 @@
         String module = "/" + entry.moduleName() + "/";
         String filename = entry.path().substring(module.length());
 
-        // Remove radical native|config|...
+        // Remove radical lib|config|...
         return filename.substring(filename.indexOf('/') + 1);
     }
 
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/AbstractResourcePoolEntry.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/AbstractResourcePoolEntry.java	Thu Mar 16 20:47:03 2017 +0000
@@ -38,7 +38,7 @@
  * <li>For jimage content: /{module name}/{package1}/.../{packageN}/{file
  * name}</li>
  * <li>For other files (shared lib, launchers, config, ...):/{module name}/
- * {@literal bin|conf|native}/{dir1}>/.../{dirN}/{file name}</li>
+ * {@literal bin|conf|lib}/{dir1}>/.../{dirN}/{file name}</li>
  * </ul>
  */
 abstract class AbstractResourcePoolEntry implements ResourcePoolEntry {
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/JlinkTask.java	Thu Mar 16 20:47:03 2017 +0000
@@ -29,6 +29,7 @@
 import java.io.PrintWriter;
 import java.io.UncheckedIOException;
 import java.lang.module.Configuration;
+import java.lang.module.FindException;
 import java.lang.module.ModuleDescriptor;
 import java.lang.module.ModuleFinder;
 import java.lang.module.ModuleReference;
@@ -232,7 +233,7 @@
 
             return EXIT_OK;
         } catch (PluginException | IllegalArgumentException |
-                 UncheckedIOException |IOException | ResolutionException e) {
+                 UncheckedIOException |IOException | FindException | ResolutionException e) {
             log.println(taskHelper.getMessage("error.prefix") + " " + e.getMessage());
             if (DEBUG) {
                 e.printStackTrace(log);
@@ -370,7 +371,7 @@
      */
     private ModuleFinder modulePathFinder() {
         Path[] entries = options.modulePath.toArray(new Path[0]);
-        ModuleFinder finder = new ModulePath(Runtime.version(), true, entries);
+        ModuleFinder finder = ModulePath.of(Runtime.version(), true, entries);
         if (!options.limitMods.isEmpty()) {
             finder = limitFinder(finder, options.limitMods, Collections.emptySet());
         }
@@ -388,7 +389,7 @@
                                                Set<String> roots)
     {
         Path[] entries = paths.toArray(new Path[0]);
-        ModuleFinder finder = new ModulePath(Runtime.version(), true, entries);
+        ModuleFinder finder = ModulePath.of(Runtime.version(), true, entries);
 
         // if limitmods is specified then limit the universe
         if (!limitMods.isEmpty()) {
@@ -418,9 +419,9 @@
         }
 
         Configuration cf = Configuration.empty()
-                .resolveRequires(finder,
-                                 ModuleFinder.of(),
-                                 roots);
+                .resolve(finder,
+                         ModuleFinder.of(),
+                         roots);
 
         // emit warning for modules that end with a digit
         cf.modules().stream()
@@ -458,9 +459,9 @@
 
         // resolve all root modules
         Configuration cf = Configuration.empty()
-                .resolveRequires(finder,
-                                 ModuleFinder.of(),
-                                 roots);
+                .resolve(finder,
+                         ModuleFinder.of(),
+                         roots);
 
         // module name -> reference
         Map<String, ModuleReference> map = new HashMap<>();
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ResourcePoolConfiguration.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/ResourcePoolConfiguration.java	Thu Mar 16 20:47:03 2017 +0000
@@ -51,7 +51,7 @@
         ModuleDescriptor md = mod.descriptor();
 
         // drop hashes
-        ModuleDescriptor.Builder builder = ModuleDescriptor.module(md.name());
+        ModuleDescriptor.Builder builder = ModuleDescriptor.newModule(md.name());
         md.requires().stream()
           .forEach(builder::requires);
         md.exports().stream()
@@ -62,12 +62,7 @@
           .forEach(builder::uses);
         md.provides().stream()
           .forEach(builder::provides);
-
-        // build the proper concealed packages
-        Set<String> concealed = new HashSet<>(mod.packages());
-        md.exports().stream().map(ModuleDescriptor.Exports::source).forEach(concealed::remove);
-        md.opens().stream().map(ModuleDescriptor.Opens::source).forEach(concealed::remove);
-        concealed.stream().forEach(builder::contains);
+        builder.packages(md.packages());
 
         md.version().ifPresent(builder::version);
         md.mainClass().ifPresent(builder::mainClass);
@@ -102,7 +97,9 @@
             ModuleDescriptor desc = m.descriptor();
             if (!desc.packages().equals(m.packages())) {
                 throw new RuntimeException("Module " + m.name() +
-                   "'s descriptor returns inconsistent package set");
+                   "'s descriptor indicates the set of packages is : " +
+                   desc.packages() + ", but module contains packages: " +
+                   m.packages());
             }
         });
     }
@@ -124,7 +121,7 @@
             }
         };
 
-        return Configuration.empty().resolveRequires(
+        return Configuration.empty().resolve(
             finder, ModuleFinder.of(), nameToModRef.keySet());
     }
 }
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/TaskHelper.java	Thu Mar 16 20:47:03 2017 +0000
@@ -718,13 +718,13 @@
     static Layer createPluginsLayer(List<Path> paths) {
 
         Path[] dirs = paths.toArray(new Path[0]);
-        ModuleFinder finder = new ModulePath(Runtime.version(), true, dirs);
+        ModuleFinder finder = ModulePath.of(Runtime.version(), true, dirs);
         Configuration bootConfiguration = Layer.boot().configuration();
         try {
             Configuration cf = bootConfiguration
-                .resolveRequiresAndUses(ModuleFinder.of(),
-                                        finder,
-                                        Collections.emptySet());
+                .resolveAndBind(ModuleFinder.of(),
+                                finder,
+                                Collections.emptySet());
             ClassLoader scl = ClassLoader.getSystemClassLoader();
             return Layer.boot().defineModulesWithOneLoader(cf, scl);
         } catch (Exception ex) {
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/DefaultCompressPlugin.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/DefaultCompressPlugin.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,7 @@
 package jdk.tools.jlink.internal.plugins;
 
 import java.util.Map;
+import java.util.function.Function;
 
 import jdk.tools.jlink.internal.ResourcePoolManager.ResourcePoolImpl;
 import jdk.tools.jlink.plugin.ResourcePool;
@@ -64,9 +65,10 @@
             return ss.transform(in, out);
         } else if (zip != null) {
             return zip.transform(in, out);
+        } else {
+            in.transformAndCopy(Function.identity(), out);
+            return out.build();
         }
-
-        return out.build();
     }
 
     @Override
@@ -103,21 +105,20 @@
         if (level != null) {
             switch (level) {
                 case LEVEL_0:
-                    ss = new StringSharingPlugin(resFilter);
+                    ss = null;
+                    zip = null;
                     break;
                 case LEVEL_1:
-                    zip = new ZipPlugin(resFilter);
+                    ss = new StringSharingPlugin(resFilter);
                     break;
                 case LEVEL_2:
-                    ss = new StringSharingPlugin(resFilter);
                     zip = new ZipPlugin(resFilter);
                     break;
                 default:
                     throw new IllegalArgumentException("Invalid compression level " + level);
             }
         } else {
-            ss = new StringSharingPlugin(resFilter);
-            zip = new ZipPlugin(resFilter);
+            throw new IllegalArgumentException("Invalid compression level " + level);
         }
     }
 }
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/ExcludeVMPlugin.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/ExcludeVMPlugin.java	Thu Mar 16 20:47:03 2017 +0000
@@ -95,9 +95,9 @@
 
     /**
      * VM paths:
-     * /java.base/native/{architecture}/{server|client|minimal}/{shared lib}
-     * e.g.: /java.base/native/amd64/server/libjvm.so
-     * /java.base/native/server/libjvm.dylib
+     * /java.base/lib/{architecture}/{server|client|minimal}/{shared lib}
+     * e.g.: /java.base/lib/server/libjvm.so
+     * /java.base/lib/server/libjvm.dylib
      */
     private List<ResourcePoolEntry> getVMs(ResourcePoolModule javaBase, String[] jvmlibs) {
         List<ResourcePoolEntry> ret = javaBase.entries().filter((t) -> {
@@ -198,17 +198,17 @@
             }
             case CLIENT: {
                 target = Jvm.CLIENT;
-                exclude = "/java.base/native**server/**,/java.base/native**minimal/**";
+                exclude = "/java.base/lib**server/**,/java.base/lib**minimal/**";
                 break;
             }
             case SERVER: {
                 target = Jvm.SERVER;
-                exclude = "/java.base/native**client/**,/java.base/native**minimal/**";
+                exclude = "/java.base/lib**client/**,/java.base/lib**minimal/**";
                 break;
             }
             case MINIMAL: {
                 target = Jvm.MINIMAL;
-                exclude = "/java.base/native**server/**,/java.base/native**client/**";
+                exclude = "/java.base/lib**server/**,/java.base/lib**client/**";
                 break;
             }
             default: {
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/GenerateJLIClassesPlugin.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/GenerateJLIClassesPlugin.java	Thu Mar 16 20:47:03 2017 +0000
@@ -24,14 +24,17 @@
  */
 package jdk.tools.jlink.internal.plugins;
 
+import java.io.BufferedReader;
 import java.io.File;
 import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
 import java.lang.invoke.MethodType;
+import java.lang.module.ModuleDescriptor;
 import java.nio.file.Files;
-import java.util.ArrayList;
 import java.util.EnumSet;
-import java.util.List;
 import java.util.Map;
+import java.util.Optional;
 import java.util.Set;
 import java.util.TreeMap;
 import java.util.TreeSet;
@@ -51,8 +54,13 @@
 public final class GenerateJLIClassesPlugin implements Plugin {
 
     private static final String NAME = "generate-jli-classes";
+    private static final String IGNORE_VERSION = "ignore-version";
 
     private static final String DESCRIPTION = PluginsResourceBundle.getDescription(NAME);
+    private static final String IGNORE_VERSION_WARNING = NAME + ".ignore.version.warn";
+    private static final String VERSION_MISMATCH_WARNING = NAME + ".version.mismatch.warn";
+
+    private static final String DEFAULT_TRACE_FILE = "default_jli_trace.txt";
 
     private static final String DIRECT_HOLDER = "java/lang/invoke/DirectMethodHandle$Holder";
     private static final String DMH_INVOKE_VIRTUAL = "invokeVirtual";
@@ -69,11 +77,15 @@
     private static final JavaLangInvokeAccess JLIA
             = SharedSecrets.getJavaLangInvokeAccess();
 
-    Set<String> speciesTypes;
+    Set<String> speciesTypes = Set.of();
+
+    Set<String> invokerTypes = Set.of();
 
-    Set<String> invokerTypes;
+    Map<String, Set<String>> dmhMethods = Map.of();
 
-    Map<String, Set<String>> dmhMethods;
+    String mainArgument;
+
+    boolean ignoreVersion;
 
     public GenerateJLIClassesPlugin() {
     }
@@ -157,69 +169,101 @@
 
     @Override
     public void configure(Map<String, String> config) {
-        String mainArgument = config.get(NAME);
+        mainArgument = config.get(NAME);
+        ignoreVersion = Boolean.parseBoolean(config.get(IGNORE_VERSION));
+    }
 
+    public void initialize(ResourcePool in) {
         // Start with the default configuration
-        Set<String> defaultBMHSpecies = defaultSpecies();
-        // Expand BMH species signatures
-        defaultBMHSpecies = defaultBMHSpecies.stream()
+        speciesTypes = defaultSpecies().stream()
                 .map(type -> expandSignature(type))
                 .collect(Collectors.toSet());
 
-        Set<String> defaultInvokerTypes = defaultInvokers();
-        validateMethodTypes(defaultInvokerTypes);
+        invokerTypes = defaultInvokers();
+        validateMethodTypes(invokerTypes);
 
-        Map<String, Set<String>> defaultDmhMethods = defaultDMHMethods();
-        for (Set<String> dmhMethodTypes : defaultDmhMethods.values()) {
+        dmhMethods = defaultDMHMethods();
+        for (Set<String> dmhMethodTypes : dmhMethods.values()) {
             validateMethodTypes(dmhMethodTypes);
         }
 
         // Extend the default configuration with the contents in the supplied
-        // input file
+        // input file - if none was supplied we look for the default file
         if (mainArgument == null || !mainArgument.startsWith("@")) {
-            speciesTypes = defaultBMHSpecies;
-            invokerTypes = defaultInvokerTypes;
-            dmhMethods = defaultDmhMethods;
+            try (InputStream traceFile =
+                    this.getClass().getResourceAsStream(DEFAULT_TRACE_FILE)) {
+                if (traceFile != null) {
+                    readTraceConfig(
+                        new BufferedReader(
+                            new InputStreamReader(traceFile)).lines());
+                }
+            } catch (Exception e) {
+                throw new PluginException("Couldn't read " + DEFAULT_TRACE_FILE, e);
+            }
         } else {
             File file = new File(mainArgument.substring(1));
             if (file.exists()) {
-                // Use TreeSet/TreeMap to keep things sorted in a deterministic
-                // order to avoid scrambling the layout on small changes and to
-                // ease finding methods in the generated code
-                speciesTypes = new TreeSet<>(defaultBMHSpecies);
-                invokerTypes = new TreeSet<>(defaultInvokerTypes);
-                dmhMethods = new TreeMap<>();
-                for (Map.Entry<String, Set<String>> entry : defaultDmhMethods.entrySet()) {
-                    dmhMethods.put(entry.getKey(), new TreeSet<>(entry.getValue()));
-                }
-                fileLines(file)
-                    .map(line -> line.split(" "))
-                    .forEach(parts -> {
-                        switch (parts[0]) {
-                            case "[BMH_RESOLVE]":
-                                speciesTypes.add(expandSignature(parts[1]));
-                                break;
-                            case "[LF_RESOLVE]":
-                                String methodType = parts[3];
-                                validateMethodType(methodType);
-                                if (parts[1].contains("Invokers")) {
-                                    invokerTypes.add(methodType);
-                                } else if (parts[1].contains("DirectMethodHandle")) {
-                                    String dmh = parts[2];
-                                    // ignore getObject etc for now (generated
-                                    // by default)
-                                    if (DMH_METHOD_TYPE_MAP.containsKey(dmh)) {
-                                        addDMHMethodType(dmh, methodType);
-                                    }
-                                }
-                                break;
-                            default: break; // ignore
-                        }
-                });
+                readTraceConfig(fileLines(file));
             }
         }
     }
 
+    private boolean checkVersion(Runtime.Version linkedVersion) {
+        Runtime.Version baseVersion = Runtime.version();
+        if (baseVersion.major() != linkedVersion.major() ||
+                baseVersion.minor() != linkedVersion.minor()) {
+            return false;
+        }
+        return true;
+    }
+
+    private Runtime.Version getLinkedVersion(ResourcePool in) {
+        ModuleDescriptor.Version version = in.moduleView()
+                .findModule("java.base")
+                .get()
+                .descriptor()
+                .version()
+                .orElseThrow(() -> new PluginException("No version defined in "
+                        + "the java.base being linked"));
+         return Runtime.Version.parse(version.toString());
+    }
+
+    private void readTraceConfig(Stream<String> lines) {
+        // Use TreeSet/TreeMap to keep things sorted in a deterministic
+        // order to avoid scrambling the layout on small changes and to
+        // ease finding methods in the generated code
+        speciesTypes = new TreeSet<>(speciesTypes);
+        invokerTypes = new TreeSet<>(invokerTypes);
+        TreeMap<String, Set<String>> newDMHMethods = new TreeMap<>();
+        for (Map.Entry<String, Set<String>> entry : dmhMethods.entrySet()) {
+            newDMHMethods.put(entry.getKey(), new TreeSet<>(entry.getValue()));
+        }
+        dmhMethods = newDMHMethods;
+        lines.map(line -> line.split(" "))
+             .forEach(parts -> {
+                switch (parts[0]) {
+                    case "[BMH_RESOLVE]":
+                        speciesTypes.add(expandSignature(parts[1]));
+                        break;
+                    case "[LF_RESOLVE]":
+                        String methodType = parts[3];
+                        validateMethodType(methodType);
+                        if (parts[1].contains("Invokers")) {
+                            invokerTypes.add(methodType);
+                        } else if (parts[1].contains("DirectMethodHandle")) {
+                            String dmh = parts[2];
+                            // ignore getObject etc for now (generated
+                            // by default)
+                            if (DMH_METHOD_TYPE_MAP.containsKey(dmh)) {
+                                addDMHMethodType(dmh, methodType);
+                            }
+                        }
+                        break;
+                    default: break; // ignore
+                }
+            });
+    }
+
     private void addDMHMethodType(String dmh, String methodType) {
         validateMethodType(methodType);
         Set<String> methodTypes = dmhMethods.get(dmh);
@@ -265,6 +309,25 @@
 
     @Override
     public ResourcePool transform(ResourcePool in, ResourcePoolBuilder out) {
+        if (ignoreVersion) {
+            System.out.println(
+                    PluginsResourceBundle
+                            .getMessage(IGNORE_VERSION_WARNING));
+        } else if (!checkVersion(getLinkedVersion(in))) {
+            // The linked images are not version compatible
+            if (mainArgument != null) {
+                // Log a mismatch warning if an argument was specified
+                System.out.println(
+                        PluginsResourceBundle
+                                .getMessage(VERSION_MISMATCH_WARNING,
+                                            getLinkedVersion(in),
+                                            Runtime.version()));
+            }
+            in.transformAndCopy(entry -> entry, out);
+            return out.build();
+        }
+
+        initialize(in);
         // Copy all but DMH_ENTRY to out
         in.transformAndCopy(entry -> {
                 // filter out placeholder entries
@@ -277,8 +340,18 @@
                     return entry;
                 }
             }, out);
+
+        // Generate BMH Species classes
         speciesTypes.forEach(types -> generateBMHClass(types, out));
+
+        // Generate LambdaForm Holder classes
         generateHolderClasses(out);
+
+        // Let it go
+        speciesTypes = null;
+        invokerTypes = null;
+        dmhMethods = null;
+
         return out.build();
     }
 
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/SystemModulesPlugin.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/internal/plugins/SystemModulesPlugin.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -46,11 +46,16 @@
 import java.util.function.IntSupplier;
 
 import jdk.internal.module.Checks;
+import jdk.internal.module.ClassFileAttributes;
+import jdk.internal.module.ClassFileConstants;
 import jdk.internal.module.ModuleHashes;
 import jdk.internal.module.ModuleInfo.Attributes;
 import jdk.internal.module.ModuleInfoExtender;
 import jdk.internal.module.ModuleResolution;
 import jdk.internal.module.SystemModules;
+import jdk.internal.org.objectweb.asm.Attribute;
+import jdk.internal.org.objectweb.asm.ClassReader;
+import jdk.internal.org.objectweb.asm.ClassVisitor;
 import jdk.internal.org.objectweb.asm.ClassWriter;
 import jdk.internal.org.objectweb.asm.MethodVisitor;
 import jdk.internal.org.objectweb.asm.Opcodes;
@@ -109,6 +114,11 @@
     }
 
     @Override
+    public String getArgumentsDescription() {
+        return PluginsResourceBundle.getArgument(NAME);
+    }
+
+    @Override
     public void configure(Map<String, String> config) {
         String arg = config.get(NAME);
         if (arg != null) {
@@ -171,10 +181,11 @@
     }
 
     static class ModuleInfo {
+        private final ByteArrayInputStream bain;
         private final Attributes attrs;
         private final Set<String> packages;
-        private final ByteArrayInputStream bain;
         private final boolean dropModuleTarget;
+        private final boolean addModulePackages;
         private ModuleDescriptor descriptor;  // may be different that the original one
 
         ModuleInfo(byte[] bytes, Set<String> packages, boolean dropModuleTarget)
@@ -182,15 +193,21 @@
         {
             this.bain = new ByteArrayInputStream(bytes);
             this.packages = packages;
-
             this.attrs = jdk.internal.module.ModuleInfo.read(bain, null);
+            // If ModulePackages attribute is present, the packages from this
+            // module descriptor returns the packages in that attribute.
+            // If it's not present, ModuleDescriptor::packages only contains
+            // the exported and open packages from module-info.class
             this.descriptor = attrs.descriptor();
             if (descriptor.isAutomatic()) {
                 throw new InternalError("linking automatic module is not supported");
             }
 
+            // add ModulePackages attribute if this module contains some packages
+            // and ModulePackages is not present
+            this.addModulePackages = packages.size() > 0 && !hasModulePackages();
+            // drop target attribute only if any OS property is present
             if (dropModuleTarget) {
-                // drop target attribute only if any OS property is present
                 this.dropModuleTarget =
                     descriptor.osName().isPresent() ||
                     descriptor.osArch().isPresent() ||
@@ -276,53 +293,71 @@
             }
         }
 
+        boolean hasModulePackages() throws IOException {
+            Set<String> attrTypes = new HashSet<>();
+            ClassVisitor cv = new ClassVisitor(Opcodes.ASM5) {
+                @Override
+                public void visitAttribute(Attribute attr) {
+                    attrTypes.add(attr.type);
+                }
+            };
+
+            // prototype of attributes that should be parsed
+            Attribute[] attrs = new Attribute[] {
+                new ClassFileAttributes.ModulePackagesAttribute()
+            };
+
+            try (InputStream in = getInputStream()) {
+                // parse module-info.class
+                ClassReader cr = new ClassReader(in);
+                cr.accept(cv, attrs, 0);
+                return attrTypes.contains(ClassFileConstants.MODULE_PACKAGES);
+            }
+        }
+
         /**
          * Returns true if module-info.class should be written
          * 1. add ModulePackages attribute if not present; or
          * 2. drop ModuleTarget attribute except java.base
          */
         boolean shouldRewrite() {
-            return shouldAddModulePackages() || shouldDropModuleTarget();
-        }
-
-        boolean shouldAddModulePackages() {
-            return (descriptor.packages().isEmpty() && packages.size() > 0);
-        }
-
-        boolean shouldDropModuleTarget() {
-            return dropModuleTarget &&
-                        (descriptor.osName().isPresent() ||
-                         descriptor.osArch().isPresent() ||
-                         descriptor.osVersion().isPresent());
+            return addModulePackages || dropModuleTarget;
         }
 
         /**
          * Returns the bytes for the module-info.class with ModulePackages
-         * if it contains at least one package
+         * attribute added and/or with ModuleTarget attribute dropped.
          */
         byte[] getBytes() throws IOException {
-            bain.reset();
-
-            // add ModulePackages attribute if not exist
-            if (shouldRewrite()) {
-                ModuleInfoRewriter rewriter = new ModuleInfoRewriter(bain);
-                if (shouldAddModulePackages()) {
-                    rewriter.addModulePackages(packages);
+            try (InputStream in = getInputStream()) {
+                if (shouldRewrite()) {
+                    ModuleInfoRewriter rewriter = new ModuleInfoRewriter(in);
+                    if (addModulePackages) {
+                        rewriter.addModulePackages(packages);
+                    }
+                    if (dropModuleTarget) {
+                        rewriter.dropModuleTarget();
+                    }
+                    // rewritten module descriptor
+                    byte[] bytes = rewriter.getBytes();
+                    try (ByteArrayInputStream bain = new ByteArrayInputStream(bytes)) {
+                        this.descriptor = ModuleDescriptor.read(bain);
+                    }
+                    return bytes;
+                } else {
+                    return in.readAllBytes();
                 }
-                if (shouldDropModuleTarget()) {
-                    rewriter.dropModuleTarget();
-                }
-                // rewritten module descriptor
-                byte[] bytes = rewriter.getBytes();
-                try (ByteArrayInputStream bain = new ByteArrayInputStream(bytes)) {
-                     this.descriptor = ModuleDescriptor.read(bain);
-                }
-                return bytes;
-            } else {
-                return bain.readAllBytes();
             }
         }
 
+        /*
+         * Returns the input stream of the module-info.class
+         */
+        InputStream getInputStream() {
+            bain.reset();
+            return bain;
+        }
+
         class ModuleInfoRewriter extends ByteArrayOutputStream {
             final ModuleInfoExtender extender;
             ModuleInfoRewriter(InputStream in) {
@@ -771,9 +806,12 @@
                 if (md.isOpen()) {
                     setModuleBit("open", true);
                 }
-                if (md.isSynthetic()) {
+                if (md.modifiers().contains(ModuleDescriptor.Modifier.SYNTHETIC)) {
                     setModuleBit("synthetic", true);
                 }
+                if (md.modifiers().contains(ModuleDescriptor.Modifier.MANDATED)) {
+                    setModuleBit("mandated", true);
+                }
             }
 
             /*
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jlink/resources/plugins.properties	Thu Mar 16 20:47:03 2017 +0000
@@ -40,9 +40,9 @@
 
 compress.description=\
 Compress all resources in the output image.\n\
-Level 0: constant string sharing\n\
-Level 1: ZIP\n\
-Level 2: both.\n\
+Level 0: No compression\n\
+Level 1: Constant string sharing\n\
+Level 2: ZIP.\n\
 An optional <pattern-list> filter can be specified to list the pattern of\n\
 files to be included.
 
@@ -62,7 +62,7 @@
 exclude-files.argument=<pattern-list> of files to exclude
 
 exclude-files.description=\
-Specify files to exclude. e.g.: **.java,glob:/java.base/native/client/**
+Specify files to exclude. e.g.: **.java,glob:/java.base/lib/client/**
 
 exclude-resources.argument=<pattern-list> resources to exclude
 
@@ -75,11 +75,23 @@
 exclude-jmod-section.description=\
 Specify a JMOD section to exclude
 
-generate-jli-classes.argument=@filename
+generate-jli-classes.argument=@filename[:ignore-version=<true|false>]
 
 generate-jli-classes.description=\
-Takes a file hinting to jlink what java.lang.invoke classes to pre-generate. If\n\
-this flag is not specified a default set of classes will be generated.
+Specify a file listing the java.lang.invoke classes to pre-generate. \n\
+By default, this plugin may use a builtin list of classes to pre-generate. \n\
+If this plugin runs on a different runtime version than the image being \n\
+created then code generation will be disabled by default to guarantee \n\
+correctness - add ignore-version=true to override this.
+
+generate-jli-classes.ignore.version.warn=\
+WARNING: --generate-jli-classes set to ignore version mismatch between \n\
+JDK running jlink and target image.
+
+generate-jli-classes.version.mismatch.warn=\
+WARNING: Pre-generation of JLI classes is only supported when linking \n\
+the same version of java.base ({0}) as the JDK running jlink ({1}), \n\
+class generation skipped - specify ignore-version to override.
 
 system-modules.argument=retainModuleTarget
 
@@ -148,8 +160,10 @@
 \      --disable-plugin <pluginname>     Disable the plugin mentioned
 
 plugin.opt.compress=\
-\  -c, --compress=<0|1|2>                Enable compression of resources\n\
-\                                        More details in --list-plugins option
+\  -c, --compress=<0|1|2>                Enable compression of resources:\n\
+\                                          Level 0: No compression\n\
+\                                          Level 1: Constant string sharing\n\
+\                                          Level 2: ZIP
 
 plugin.opt.strip-debug=\
 \  -G, --strip-debug                     Strip debug information
--- a/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/JmodTask.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.jlink/share/classes/jdk/tools/jmod/JmodTask.java	Thu Mar 16 20:47:03 2017 +0000
@@ -34,6 +34,7 @@
 import java.io.PrintWriter;
 import java.io.UncheckedIOException;
 import java.lang.module.Configuration;
+import java.lang.module.FindException;
 import java.lang.module.ModuleReader;
 import java.lang.module.ModuleReference;
 import java.lang.module.ModuleFinder;
@@ -851,8 +852,8 @@
             // get a resolved module graph
             Configuration config = null;
             try {
-                config = Configuration.empty().resolveRequires(system, finder, roots);
-            } catch (ResolutionException e) {
+                config = Configuration.empty().resolve(system, finder, roots);
+            } catch (FindException | ResolutionException e) {
                 throw new CommandException("err.module.resolution.fail", e.getMessage());
             }
 
@@ -1392,7 +1393,7 @@
                 options.legalNotices = getLastElement(opts.valuesOf(legalNotices));
             if (opts.has(modulePath)) {
                 Path[] dirs = getLastElement(opts.valuesOf(modulePath)).toArray(new Path[0]);
-                options.moduleFinder = new ModulePath(Runtime.version(), true, dirs);
+                options.moduleFinder = ModulePath.of(Runtime.version(), true, dirs);
             }
             if (opts.has(moduleVersion))
                 options.moduleVersion = getLastElement(opts.valuesOf(moduleVersion));
--- a/jdk/src/jdk.rmic/share/classes/sun/rmi/rmic/Main.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.rmic/share/classes/sun/rmi/rmic/Main.java	Thu Mar 16 20:47:03 2017 +0000
@@ -145,12 +145,14 @@
          * in parseArgs, so that none of the arguments will be nulled
          * before delegating to the new implementation.
          */
-        for (int i = 0; i < argv.length; i++) {
-            if (argv[i].equals("-Xnew")) {
-                return (new sun.rmi.rmic.newrmic.Main(out,
-                                                      program)).compile(argv);
-            }
-        }
+        // disable the -Xnew option as per JDK-8146299 and JDK-8145980
+        // to allow further discussion how to progress with this feature
+        //for (int i = 0; i < argv.length; i++) {
+        //    if (argv[i].equals("-Xnew")) {
+        //        return (new sun.rmi.rmic.newrmic.Main(out,
+        //                                              program)).compile(argv);
+        //    }
+        //}
 
         if (!parseArgs(argv)) {
             return false;
--- a/jdk/src/jdk.security.auth/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.security.auth/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,6 +26,8 @@
 /**
  * Contains the implementation of the javax.security.auth.* interfaces and
  * various authentication modules.
+ *
+ * @since 9
  */
 module jdk.security.auth {
     requires transitive java.naming;
--- a/jdk/src/jdk.security.jgss/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/src/jdk.security.jgss/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,6 +26,8 @@
 /**
  * Defines Java extensions to the GSS-API and an implementation of the SASL
  * GSSAPI mechanism.
+ *
+ * @since 9
  */
 module jdk.security.jgss {
     requires transitive java.security.jgss;
--- a/jdk/test/ProblemList.txt	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/ProblemList.txt	Thu Mar 16 20:47:03 2017 +0000
@@ -199,8 +199,6 @@
 
 java/rmi/activation/ActivationGroup/downloadActivationGroup/DownloadActivationGroup.java 8169569 windows-all
 
-sun/rmi/rmic/newrmic/equivalence/run.sh                         8145980 generic-all
-
 java/rmi/registry/readTest/CodebaseTest.java                    8173324 windows-all
 
 ############################################################################
@@ -214,6 +212,7 @@
 sun/security/tools/jarsigner/warnings/BadKeyUsageTest.java      8026393 generic-all
 
 javax/net/ssl/DTLS/PacketLossRetransmission.java                8169086 macosx-x64
+javax/net/ssl/DTLS/RespondToRetransmit.java                     8169086 macosx-x64
 
 ############################################################################
 
@@ -251,23 +250,27 @@
 
 tools/pack200/CommandLineTests.java                             8059906 generic-all
 
-tools/launcher/ArgsEnvVar.java					8173712 generic-all
 tools/launcher/FXLauncherTest.java                              8068049 linux-all,macosx-all
 
-tools/jimage/JImageExtractTest.java                             8169713 generic-all
-tools/jimage/JImageListTest.java                                8169713 generic-all
-tools/jimage/JImageVerifyTest.java                              8169713 generic-all
+tools/jimage/JImageExtractTest.java                             8170120 generic-all
+tools/jimage/JImageListTest.java                                8170120 generic-all
+tools/jimage/JImageVerifyTest.java                              8170120 generic-all
 
 
 tools/jlink/multireleasejar/JLinkMultiReleaseJarTest.java       8169971 windows-x64
 
+tools/jar/multiRelease/RuntimeTest.java                         8173905 generic-all
+
+tools/schemagen/MultiReleaseJarTest.java                        8174692 generic-all
+tools/wsgen/MultiReleaseJarTest.java                            8174692 generic-all
+
 ############################################################################
 
 # jdk_jdi
 
 com/sun/jdi/RedefineImplementor.sh                              8004127 generic-all
 
-com/sun/jdi/JdbMethodExitTest.sh                                6902121 generic-all
+com/sun/jdi/JdbMethodExitTest.sh                                8171483 generic-all
 
 com/sun/jdi/RepStep.java                                        8043571 generic-all
 
@@ -296,6 +299,8 @@
 
 sun/tools/jcmd/TestJcmdSanity.java                              8031482 windows-all
 
+sun/tools/jstat/jstatClassloadOutput1.sh                        8173942 generic-all
+
 sun/jvmstat/monitor/MonitoredVm/MonitorVmStartTerminate.java    8057732 generic-all
 
 demo/jvmti/compiledMethodLoad/CompiledMethodLoadTest.java       8151899 generic-all
@@ -308,6 +313,6 @@
 
 javax/rmi/PortableRemoteObject/8146975/RmiIiopReturnValueTest.java 8169737 linux-all
 
-javax/xml/ws/clientjar/TestWsImport.java			8170370 generic-all
+javax/xml/ws/clientjar/TestWsImport.java			8173317 generic-all
 
 ############################################################################
--- a/jdk/test/TEST.groups	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/TEST.groups	Thu Mar 16 20:47:03 2017 +0000
@@ -273,6 +273,7 @@
     jdk/internal/jline \
     com/sun/jndi \
     com/sun/corba \
+    org/omg/CORBA \
     lib/testlibrary \
     sample
 
--- a/jdk/test/com/oracle/security/ucrypto/TestAES.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/com/oracle/security/ucrypto/TestAES.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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 7088989 8014374 8167512
+ * @bug 7088989 8014374 8167512 8173708
  * @summary Ensure the AES ciphers of OracleUcrypto provider works correctly
  * @key randomness
  * @run main TestAES
@@ -177,6 +177,12 @@
                     k += c.doFinal(eout, firstPartLen+1, eout.length - firstPartLen - 1, dout, k);
                     if (!checkArrays(in, in.length, dout, k)) testPassed = false;
                 } catch(Exception ex) {
+                    if (ex instanceof BadPaddingException &&
+                            algos[i].indexOf("CFB128") != -1 &&
+                            p.getName().equals("OracleUcrypto")) {
+                        System.out.println("Ignore due to a pre-S11.3 bug: " + ex);
+                        continue;
+                    }
                     System.out.println("Unexpected Exception: " + algos[i]);
                     ex.printStackTrace();
                     testPassed = false;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/com/sun/java/swing/plaf/windows/Test8173145.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,123 @@
+/*
+ * Copyright (c) 2017, 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 8173145
+   @summary Menu is activated after using mnemonic Alt/Key combination
+   @modules java.desktop/com.sun.java.swing.plaf.windows
+   @run main Test8173145
+*/
+
+import java.awt.*;
+import java.awt.event.KeyEvent;
+import java.lang.reflect.InvocationTargetException;
+
+import javax.swing.*;
+
+public class Test8173145 {
+
+    private volatile static JButton btn;
+    private volatile static boolean uiCreated;
+
+    public static void main(String[] args) throws InvocationTargetException, InterruptedException, AWTException {
+        SwingUtilities.invokeAndWait(new Runnable() {
+            @Override
+            public void run() {
+                try {
+                    uiCreated = createGUI();
+                } catch (Exception e) {
+                    e.printStackTrace();
+                }
+            }
+        });
+
+        if (uiCreated) {
+            test();
+        } else {
+            //no windows l&f, skip the test
+        }
+    }
+
+    private static void test() {
+        final Robot robot;
+        try {
+            robot = new Robot();
+        } catch (AWTException e) {
+            throw new RuntimeException(e);
+        }
+        robot.setAutoDelay(100);
+        robot.waitForIdle();
+
+        robot.keyPress(KeyEvent.VK_ALT);
+        robot.keyPress(KeyEvent.VK_M);
+        robot.keyRelease(KeyEvent.VK_M);
+        robot.keyRelease(KeyEvent.VK_ALT);
+
+        Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
+
+        if (focusOwner != btn) {
+            throw new RuntimeException("Wrong focus owner");
+        }
+    }
+
+    private static boolean createGUI() {
+        try {
+            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
+        } catch (Exception e) {
+            return false;
+        }
+        JFrame f = new JFrame();
+
+        JPanel panel = new JPanel();
+        btn = new JButton("Mmmmm");
+        btn.setMnemonic(KeyEvent.VK_M);
+        btn.setDisplayedMnemonicIndex(0);
+        panel.add(btn);
+
+        JTextField tf = new JTextField();
+        tf.setColumns(10);
+        panel.add(tf);
+
+        f.setJMenuBar(getMenuBar());
+        f.add(panel);
+        f.pack();
+        f.setVisible(true);
+        tf.requestFocus();
+        return true;
+    }
+
+    static JMenuBar getMenuBar() {
+        JMenuBar menuBar;
+        JMenu menu;
+
+        menuBar = new JMenuBar();
+
+        menu = new JMenu("Menu");
+        menuBar.add(menu);
+
+        JMenuItem mi = new JMenuItem("test");
+        menu.add(mi);
+
+        return menuBar;
+    }
+}
--- a/jdk/test/com/sun/java/swing/plaf/windows/WindowsRadioButtonUI/7089914/bug7089914.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/com/sun/java/swing/plaf/windows/WindowsRadioButtonUI/7089914/bug7089914.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,9 +26,9 @@
  */
 
 /* @test
- * @bug 7089914
+ * @bug 7089914 8174720
  * @requires (os.family == "windows")
- * @modules java.desktop/com.sun.java.swing.plaf.windows
+ * @modules java.desktop/com.sun.java.swing.plaf.windows:open
  * @summary Focus on image icons are not visible in javaws cache with high contrast mode
  * @author Sean Chou
  */
--- a/jdk/test/com/sun/management/HotSpotDiagnosticMXBean/CheckOrigin.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/com/sun/management/HotSpotDiagnosticMXBean/CheckOrigin.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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
@@ -62,7 +62,7 @@
             ProcessBuilder pb = ProcessTools.
                 createJavaProcessBuilder(
                     "--add-exports", "jdk.attach/sun.tools.attach=ALL-UNNAMED",
-                    "-XX:+UseConcMarkSweepGC",  // this will cause UseParNewGC to be FLAG_SET_ERGO
+                    "-XX:+UseConcMarkSweepGC",  // this will cause MaxNewSize to be FLAG_SET_ERGO
                     "-XX:+UseCodeAging",
                     "-XX:+UseCerealGC",         // Should be ignored.
                     "-XX:Flags=" + flagsFile.getAbsolutePath(),
@@ -109,7 +109,7 @@
             // Set through j.l.m
             checkOrigin("HeapDumpOnOutOfMemoryError", Origin.MANAGEMENT);
             // Should be set by the VM, when we set UseConcMarkSweepGC
-            checkOrigin("UseParNewGC", Origin.ERGONOMIC);
+            checkOrigin("MaxNewSize", Origin.ERGONOMIC);
             // Set using attach
             checkOrigin("HeapDumpPath", Origin.ATTACH_ON_DEMAND);
         }
--- a/jdk/test/java/awt/Mixing/AWT_Mixing/OpaqueOverlapping.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/awt/Mixing/AWT_Mixing/OpaqueOverlapping.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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,7 +22,6 @@
  */
 
 
-import com.sun.awt.AWTUtilities;
 import java.awt.Frame;
 import java.awt.Panel;
 import java.awt.Point;
@@ -44,11 +43,10 @@
 /*
  * @test
  * @key headful
- * @bug 6776743
+ * @bug 6776743 8173409
  * @summary Opaque overlapping test for each AWT component
  * @library /java/awt/patchlib  ../../regtesthelpers
- * @modules java.desktop/com.sun.awt
- *          java.desktop/java.awt.peer
+ * @modules java.desktop/java.awt.peer
  *          java.desktop/sun.awt
  * @build java.desktop/java.awt.Helper
  * @build Util
@@ -134,12 +132,10 @@
         // flag value.
         for (int i = 0; i < 9; ++i) {
             if (i == 3) {
-                AWTUtilities.setComponentMixingCutoutShape(light,
-                        new Rectangle());
+                light.setMixingCutoutShape(new Rectangle());
             }
             if (i == 6) {
-                AWTUtilities.setComponentMixingCutoutShape(light,
-                        null);
+                light.setMixingCutoutShape(null);
             }
 
             robot.mousePress(InputEvent.BUTTON1_MASK);
--- a/jdk/test/java/awt/Mixing/OpaqueTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/awt/Mixing/OpaqueTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -24,11 +24,10 @@
 /*
   @test
   @key headful
-  @bug 4811096
+  @bug 4811096 8173409
   @summary Tests whether opaque and non-opaque components mix correctly
   @author anthony.petrov@...: area=awt.mixing
   @library ../regtesthelpers
-  @modules java.desktop/com.sun.awt
   @build Util
   @run main OpaqueTest
 */
@@ -44,7 +43,6 @@
 import java.awt.event.*;
 import javax.swing.*;
 import test.java.awt.regtesthelpers.Util;
-import com.sun.awt.AWTUtilities;
 
 
 
@@ -125,12 +123,10 @@
         // flag value.
         for (int i = 0; i < 9; ++i) {
             if (i == 3) {
-                AWTUtilities.setComponentMixingCutoutShape(light,
-                        new Rectangle());
+                light.setMixingCutoutShape(new Rectangle());
             }
             if (i == 6) {
-                AWTUtilities.setComponentMixingCutoutShape(light,
-                        null);
+                light.setMixingCutoutShape(null);
             }
 
             robot.mousePress(InputEvent.BUTTON1_MASK);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Window/WindowResizingOnDPIChanging/WindowResizingOnDPIChangingTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,278 @@
+/*
+ * Copyright (c) 2017, 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.awt.Color;
+import java.awt.FlowLayout;
+import java.awt.Font;
+import java.awt.Frame;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.HeadlessException;
+import java.awt.Image;
+import java.awt.Insets;
+import java.awt.Panel;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.awt.geom.AffineTransform;
+import java.awt.image.AbstractMultiResolutionImage;
+import java.awt.image.BufferedImage;
+import java.awt.image.ImageObserver;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+
+/* @test
+ * @bug 8147440 8147016
+ * @summary HiDPI (Windows): Swing components have incorrect sizes after
+ *          changing display resolution
+ * @run main/manual/othervm WindowResizingOnDPIChangingTest
+ */
+public class WindowResizingOnDPIChangingTest {
+
+    private static volatile boolean testResult = false;
+    private static volatile CountDownLatch countDownLatch;
+    private static TestFrame undecoratedFrame;
+    private static TestFrame decoratedFrame;
+    private static JFrame mainFrame;
+
+    private static final String INSTRUCTIONS = "INSTRUCTIONS:\n"
+            + "Verify that window is properly resized after the display DPI updating.\n"
+            + "\n"
+            + "The test is applicable for OSes that allows to change the display DPI\n"
+            + "without the system rebooting (like Windows 8.1 and higher). Press PASS for other\n"
+            + "systems. \n"
+            + "\n"
+            + "1. Set the display DPI size to 192 (DPI scale factor 200%)\n"
+            + "2. Press Show Frames button\n"
+            + "Two frames decorated and undecorated appear.\n"
+            + "3. Check that the string \"scale 2x\" is painted on the windows.\n"
+            + "4. Set the display DPI size to 96 (DPI scale factor 100%)\n"
+            + "5. Check that the string \"scale: 1x\" is painted on the windows.\n"
+            + "6. Check that the windows are properly resized in the same way as native applications\n"
+            + "7. Check that the windows are properly repainted and do not contain drawing artifacts\n"
+            + "If so, press PASS, else press FAIL.\n";
+
+    public static void main(String args[]) throws Exception {
+
+        countDownLatch = new CountDownLatch(1);
+        SwingUtilities.invokeLater(WindowResizingOnDPIChangingTest::createUI);
+        countDownLatch.await(15, TimeUnit.MINUTES);
+        if (!testResult) {
+            throw new RuntimeException("Test fails!");
+        }
+    }
+
+    private static void createUI() {
+
+        mainFrame = new JFrame("DPI change test");
+        GridBagLayout layout = new GridBagLayout();
+        JPanel mainControlPanel = new JPanel(layout);
+        JPanel resultButtonPanel = new JPanel(layout);
+
+        GridBagConstraints gbc = new GridBagConstraints();
+
+        JPanel testPanel = new JPanel(new FlowLayout());
+        JButton frameButton = new JButton("Show Frames");
+        frameButton.addActionListener((e) -> {
+            int x = 20;
+            int y = 10;
+            int w = 400;
+            int h = 300;
+
+            undecoratedFrame = new TestFrame(w, h, true);
+            undecoratedFrame.setLocation(x, y);
+            undecoratedFrame.setVisible(true);
+
+            decoratedFrame = new TestFrame(w, h, false);
+            decoratedFrame.setLocation(x + w + 10, y);
+            decoratedFrame.setVisible(true);
+
+        });
+        testPanel.add(frameButton);
+
+        gbc.gridx = 0;
+        gbc.gridy = 0;
+        gbc.fill = GridBagConstraints.HORIZONTAL;
+        mainControlPanel.add(testPanel, gbc);
+
+        JTextArea instructionTextArea = new JTextArea();
+        instructionTextArea.setText(INSTRUCTIONS);
+        instructionTextArea.setEditable(false);
+        instructionTextArea.setBackground(Color.white);
+
+        gbc.gridx = 0;
+        gbc.gridy = 1;
+        gbc.fill = GridBagConstraints.HORIZONTAL;
+        mainControlPanel.add(instructionTextArea, gbc);
+
+        JButton passButton = new JButton("Pass");
+        passButton.setActionCommand("Pass");
+        passButton.addActionListener((ActionEvent e) -> {
+            testResult = true;
+            disposeFrames();
+            countDownLatch.countDown();
+
+        });
+
+        JButton failButton = new JButton("Fail");
+        failButton.setActionCommand("Fail");
+        failButton.addActionListener(new ActionListener() {
+            @Override
+            public void actionPerformed(ActionEvent e) {
+                disposeFrames();
+                countDownLatch.countDown();
+            }
+        });
+
+        gbc.gridx = 0;
+        gbc.gridy = 0;
+        resultButtonPanel.add(passButton, gbc);
+
+        gbc.gridx = 1;
+        gbc.gridy = 0;
+        resultButtonPanel.add(failButton, gbc);
+
+        gbc.gridx = 0;
+        gbc.gridy = 2;
+        mainControlPanel.add(resultButtonPanel, gbc);
+
+        mainFrame.add(mainControlPanel);
+        mainFrame.pack();
+
+        mainFrame.addWindowListener(new WindowAdapter() {
+
+            @Override
+            public void windowClosing(WindowEvent e) {
+                disposeFrames();
+                countDownLatch.countDown();
+            }
+        });
+        mainFrame.setVisible(true);
+    }
+
+    private static void disposeFrames() {
+        if (decoratedFrame != null && decoratedFrame.isVisible()) {
+            decoratedFrame.dispose();
+        }
+        if (undecoratedFrame != null && undecoratedFrame.isVisible()) {
+            undecoratedFrame.dispose();
+        }
+        if (mainFrame != null && mainFrame.isVisible()) {
+            mainFrame.dispose();
+        }
+    }
+
+    static class TestFrame extends Frame {
+
+        private final TestMultiResolutionImage mrImage;
+
+        public TestFrame(int width, int height, boolean undecorated) throws HeadlessException {
+            super("Test Frame. Undecorated: " + undecorated);
+            setSize(width, height);
+            mrImage = new TestMultiResolutionImage(width, height);
+
+            setUndecorated(undecorated);
+            Panel panel = new Panel(new FlowLayout()) {
+                @Override
+                public void paint(Graphics g) {
+                    super.paint(g);
+                    AffineTransform tx = ((Graphics2D) g).getTransform();
+                    mrImage.scaleX = tx.getScaleX();
+                    mrImage.scaleY = tx.getScaleY();
+                    Insets insets = getInsets();
+                    g.drawImage(mrImage, insets.left, insets.bottom, null);
+                }
+            };
+            add(panel);
+        }
+    }
+
+    static class TestMultiResolutionImage extends AbstractMultiResolutionImage {
+
+        final int width;
+        final int height;
+        double scaleX;
+        double scaleY;
+
+        public TestMultiResolutionImage(int width, int height) {
+            this.width = width;
+            this.height = height;
+        }
+
+        @Override
+        public int getWidth(ImageObserver observer) {
+            return width;
+        }
+
+        @Override
+        public int getHeight(ImageObserver observer) {
+            return height;
+        }
+
+        @Override
+        protected Image getBaseImage() {
+            return getResolutionVariant(width, height);
+        }
+
+        @Override
+        public Image getResolutionVariant(double destImageWidth, double destImageHeight) {
+
+            int w = (int) destImageWidth;
+            int h = (int) destImageHeight;
+
+            BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
+            Graphics2D g = img.createGraphics();
+            g.scale(scaleX, scaleY);
+            int red = (int) (255 / scaleX);
+            int green = (int) (250 / scaleX);
+            int blue = (int) (20 / scaleX);
+            g.setColor(new Color(red, green, blue));
+            g.fillRect(0, 0, width, height);
+
+            g.setColor(Color.decode("#87CEFA"));
+            Font f = g.getFont();
+            g.setFont(new Font(f.getName(), Font.BOLD, 24));
+            g.drawString(String.format("scales: [%1.2fx, %1.2fx]", scaleX, scaleY),
+                    width / 6, height / 2);
+
+            g.dispose();
+            return img;
+        }
+
+        @Override
+        public List<Image> getResolutionVariants() {
+            return Collections.unmodifiableList(Arrays.asList(getBaseImage()));
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/Window/WindowResizingOnDPIChanging/WindowResizingOnMovingToAnotherDisplay.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,274 @@
+/*
+ * Copyright (c) 2017, 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.awt.Color;
+import java.awt.FlowLayout;
+import java.awt.Font;
+import java.awt.Frame;
+import java.awt.Graphics;
+import java.awt.Graphics2D;
+import java.awt.GridBagConstraints;
+import java.awt.GridBagLayout;
+import java.awt.HeadlessException;
+import java.awt.Image;
+import java.awt.Insets;
+import java.awt.Panel;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import java.awt.geom.AffineTransform;
+import java.awt.image.AbstractMultiResolutionImage;
+import java.awt.image.BufferedImage;
+import java.awt.image.ImageObserver;
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+import java.util.concurrent.CountDownLatch;
+import java.util.concurrent.TimeUnit;
+import javax.swing.JButton;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.SwingUtilities;
+
+/* @test
+ * @bug 8147440 8147016
+ * @summary HiDPI (Windows): Swing components have incorrect sizes after
+ *          changing display resolution
+ * @run main/manual/othervm WindowResizingOnMovingToAnotherDisplay
+ */
+public class WindowResizingOnMovingToAnotherDisplay {
+
+    private static volatile boolean testResult = false;
+    private static volatile CountDownLatch countDownLatch;
+    private static TestFrame frame;
+    private static JFrame mainFrame;
+
+    private static final String INSTRUCTIONS = "INSTRUCTIONS:\n"
+            + "Verify that a window is properly resized after moving to a display"
+            + " with different DPI.\n"
+            + "\n"
+            + "The test is applicable for a multi-monitor system where displays"
+            + " are configured to have different DPI\n"
+            + "\n"
+            + "1. Press Show Frame button\n"
+            + "The frame appear.\n"
+            + "2. Check that the string \"scales [ScaleX, ScaleY]\" is painted on the window"
+            + " where ScaleX and ScaleY are the scales for current display.\n"
+            + "The scales are calculated as DPI / 96 and are 1 for the DPI value 96"
+            + " and 2 for the DPI value 192.\n"
+            + "3. Move the frame to the second display.\n"
+            + "4. Check that the string \"scales [ScaleX, ScaleY]\" is updated"
+            + " to show the right display scales.\n"
+            + "5. Check that the window  is properly resized.\n"
+            + "6. Check that the window is properly repainted and does not contain drawing artifacts\n"
+            + "Try different display positions (left, right, top, bottom).\n"
+            + "If all tests are passed, press PASS, else press FAIL.\n";
+
+    public static void main(String args[]) throws Exception {
+
+        countDownLatch = new CountDownLatch(1);
+        SwingUtilities.invokeLater(WindowResizingOnMovingToAnotherDisplay::createUI);
+        countDownLatch.await(15, TimeUnit.MINUTES);
+        if (!testResult) {
+            throw new RuntimeException("Test fails!");
+        }
+    }
+
+    private static void createUI() {
+
+        mainFrame = new JFrame("DPI change test");
+        GridBagLayout layout = new GridBagLayout();
+        JPanel mainControlPanel = new JPanel(layout);
+        JPanel resultButtonPanel = new JPanel(layout);
+
+        GridBagConstraints gbc = new GridBagConstraints();
+
+        JPanel testPanel = new JPanel(new FlowLayout());
+        JButton frameButton = new JButton("Show Frame");
+        frameButton.addActionListener((e) -> {
+            int x = 20;
+            int y = 10;
+            int w = 400;
+            int h = 300;
+
+            frame = new TestFrame(w, h);
+            frame.setLocation(x, y);
+            frame.setVisible(true);
+
+        });
+        testPanel.add(frameButton);
+
+        gbc.gridx = 0;
+        gbc.gridy = 0;
+        gbc.fill = GridBagConstraints.HORIZONTAL;
+        mainControlPanel.add(testPanel, gbc);
+
+        JTextArea instructionTextArea = new JTextArea();
+        instructionTextArea.setText(INSTRUCTIONS);
+        instructionTextArea.setEditable(false);
+        instructionTextArea.setBackground(Color.white);
+
+        gbc.gridx = 0;
+        gbc.gridy = 1;
+        gbc.fill = GridBagConstraints.HORIZONTAL;
+        mainControlPanel.add(instructionTextArea, gbc);
+
+        JButton passButton = new JButton("Pass");
+        passButton.setActionCommand("Pass");
+        passButton.addActionListener((ActionEvent e) -> {
+            testResult = true;
+            disposeFrames();
+            countDownLatch.countDown();
+
+        });
+
+        JButton failButton = new JButton("Fail");
+        failButton.setActionCommand("Fail");
+        failButton.addActionListener(new ActionListener() {
+            @Override
+            public void actionPerformed(ActionEvent e) {
+                disposeFrames();
+                countDownLatch.countDown();
+            }
+        });
+
+        gbc.gridx = 0;
+        gbc.gridy = 0;
+        resultButtonPanel.add(passButton, gbc);
+
+        gbc.gridx = 1;
+        gbc.gridy = 0;
+        resultButtonPanel.add(failButton, gbc);
+
+        gbc.gridx = 0;
+        gbc.gridy = 2;
+        mainControlPanel.add(resultButtonPanel, gbc);
+
+        mainFrame.add(mainControlPanel);
+        mainFrame.pack();
+
+        mainFrame.addWindowListener(new WindowAdapter() {
+
+            @Override
+            public void windowClosing(WindowEvent e) {
+                disposeFrames();
+                countDownLatch.countDown();
+            }
+        });
+        mainFrame.setVisible(true);
+    }
+
+    private static void disposeFrames() {
+        if (frame != null && frame.isVisible()) {
+            frame.dispose();
+        }
+
+        if (mainFrame != null && mainFrame.isVisible()) {
+            mainFrame.dispose();
+        }
+    }
+
+    static class TestFrame extends Frame {
+
+        private final TestMultiResolutionImage mrImage;
+
+        public TestFrame(int width, int height) throws HeadlessException {
+            super("Test Frame");
+            setSize(width, height);
+            mrImage = new TestMultiResolutionImage(width, height);
+
+            Panel panel = new Panel(new FlowLayout()) {
+                @Override
+                public void paint(Graphics g) {
+                    super.paint(g);
+                    AffineTransform tx = ((Graphics2D) g).getTransform();
+                    mrImage.scaleX = tx.getScaleX();
+                    mrImage.scaleY = tx.getScaleY();
+                    Insets insets = getInsets();
+                    g.drawImage(mrImage, insets.left, insets.bottom, null);
+                }
+            };
+            add(panel);
+        }
+    }
+
+    static class TestMultiResolutionImage extends AbstractMultiResolutionImage {
+
+        final int width;
+        final int height;
+        double scaleX;
+        double scaleY;
+
+        public TestMultiResolutionImage(int width, int height) {
+            this.width = width;
+            this.height = height;
+        }
+
+        @Override
+        public int getWidth(ImageObserver observer) {
+            return width;
+        }
+
+        @Override
+        public int getHeight(ImageObserver observer) {
+            return height;
+        }
+
+        @Override
+        protected Image getBaseImage() {
+            return getResolutionVariant(width, height);
+        }
+
+        @Override
+        public Image getResolutionVariant(double destImageWidth, double destImageHeight) {
+
+            int w = (int) destImageWidth;
+            int h = (int) destImageHeight;
+
+            BufferedImage img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
+            Graphics2D g = img.createGraphics();
+            g.scale(scaleX, scaleY);
+            int red = (int) (255 / scaleX);
+            int green = (int) (250 / scaleX);
+            int blue = (int) (20 / scaleX);
+            g.setColor(new Color(red, green, blue));
+            g.fillRect(0, 0, width, height);
+
+            g.setColor(Color.decode("#87CEFA"));
+            Font f = g.getFont();
+            g.setFont(new Font(f.getName(), Font.BOLD, 24));
+            g.drawString(String.format("scales: [%1.2fx, %1.2fx]", scaleX, scaleY),
+                    width / 6, height / 2);
+
+            g.dispose();
+            return img;
+        }
+
+        @Override
+        public List<Image> getResolutionVariants() {
+            return Collections.unmodifiableList(Arrays.asList(getBaseImage()));
+        }
+    }
+}
--- a/jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/IOExceptionIfEncodedURLTest.sh	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/awt/appletviewer/IOExceptionIfEncodedURLTest/IOExceptionIfEncodedURLTest.sh	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2008, 2017, 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
@@ -24,7 +24,7 @@
 #!/bin/ksh -p
 #
 #   @test    IOExceptionIfEncodedURLTest.sh
-#   @bug     6193279 6619458
+#   @bug     6193279 6619458 8137087
 #   @summary REGRESSION: AppletViewer throws IOException when path is encoded URL
 #   @author  Dmitry Cherepanov: area=appletviewer
 #   @modules java.base/sun.net.www
@@ -56,7 +56,7 @@
 #Call this to run the test with a file name
 test()
  {
-   ${TESTJAVA}${FILESEP}bin${FILESEP}appletviewer -Xnosecurity ${URL} > err 2>&1 &
+   "${TESTJAVA}"${FILESEP}bin${FILESEP}appletviewer -Xnosecurity ${URL} > err 2>&1 &
    APPLET_ID=$!
    sleep 15
    kill -9 $APPLET_ID
@@ -134,7 +134,9 @@
       DEFAULT_JDK="/cygdrive/c/Program\ Files/Java/jdk1.8.0"
       FILESEP="/"
       PATHSEP=";"
-      TMP=`cd "${SystemRoot}/Temp"; echo ${PWD}`
+      TMP=`cd "${SYSTEMROOT}/Temp"; echo ${PWD}`
+      x="cygpath -m $PWD"
+      PWD=$(eval $x)
       ;;
 
     AIX )
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/font/Fallback/MissingGlyphTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,162 @@
+/*
+ * Copyright (c) 2017, 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 8147002
+ * @summary  Verifies if Arabic character alef is rendered in osx
+ * @run main/manual MissingGlyphTest
+ */
+import java.awt.Font;
+import java.awt.BorderLayout;
+import java.awt.Color;
+import java.awt.FlowLayout;
+import java.awt.Graphics;
+import java.awt.event.WindowAdapter;
+import java.awt.event.WindowEvent;
+import javax.swing.JButton;
+import javax.swing.JDialog;
+import javax.swing.JFrame;
+import javax.swing.JPanel;
+import javax.swing.JTextArea;
+import javax.swing.JComponent;
+import javax.swing.SwingUtilities;
+import javax.swing.WindowConstants;
+
+public class MissingGlyphTest {
+    private static Thread mainThread;
+    private static boolean testPassed;
+    private static boolean testGeneratedInterrupt;
+    private static JFrame frame;
+
+    public static void main(String[] args) throws Exception {
+        if (!System.getProperty("os.name").startsWith("Mac")) {
+            return;
+        }
+        SwingUtilities.invokeAndWait(() -> {
+            doTest(MissingGlyphTest::glyphTest);
+        });
+        mainThread = Thread.currentThread();
+        try {
+            Thread.sleep(180000);
+        } catch (InterruptedException e) {
+            if (!testPassed && testGeneratedInterrupt) {
+                throw new RuntimeException("Alef character is not rendered");
+            }
+        }
+        if (!testGeneratedInterrupt) {
+            throw new RuntimeException("user has not executed the test");
+        }
+    }
+
+    private static void glyphTest() {
+        frame = new JFrame("Test");
+        frame.add(new MyComponent());
+        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
+        frame.setSize(200, 200);
+        frame.setLocationRelativeTo(null);
+        frame.setVisible(true);
+    }
+
+    public static synchronized void pass() {
+        testPassed = true;
+        testGeneratedInterrupt = true;
+        mainThread.interrupt();
+    }
+
+    public static synchronized void fail() {
+        testPassed = false;
+        testGeneratedInterrupt = true;
+        mainThread.interrupt();
+    }
+
+    private static void doTest(Runnable action) {
+        String description
+                = " The test is supposed to display arabic alef character.\n"
+                + " If it resembles like the one shown in\n "
+                + " www.fileformat.info/info/unicode/char/0627/index.htm\n "
+                + " in Italic style ,press PASS.\n"
+                + " If the glyph is not shown or empty rectangle is shown, press FAIL";
+
+        final JDialog dialog = new JDialog();
+        dialog.setTitle("printBannerTest");
+        JTextArea textArea = new JTextArea(description);
+        textArea.setEditable(false);
+        final JButton testButton = new JButton("Start Test");
+        final JButton passButton = new JButton("PASS");
+        passButton.setEnabled(false);
+        passButton.addActionListener((e) -> {
+            dialog.dispose();
+            frame.dispose();
+            pass();
+        });
+        final JButton failButton = new JButton("FAIL");
+        failButton.setEnabled(false);
+        failButton.addActionListener((e) -> {
+            dialog.dispose();
+            frame.dispose();
+            fail();
+        });
+        testButton.addActionListener((e) -> {
+            testButton.setEnabled(false);
+            action.run();
+            passButton.setEnabled(true);
+            failButton.setEnabled(true);
+        });
+        JPanel mainPanel = new JPanel(new BorderLayout());
+        mainPanel.add(textArea, BorderLayout.CENTER);
+        JPanel buttonPanel = new JPanel(new FlowLayout());
+        buttonPanel.add(testButton);
+        buttonPanel.add(passButton);
+        buttonPanel.add(failButton);
+        mainPanel.add(buttonPanel, BorderLayout.SOUTH);
+        dialog.add(mainPanel);
+        dialog.pack();
+        dialog.setVisible(true);
+        dialog.addWindowListener(new WindowAdapter() {
+           @Override
+            public void windowClosing(WindowEvent e) {
+                System.out.println("main dialog closing");
+                testGeneratedInterrupt = false;
+                mainThread.interrupt();
+            }
+        });
+    }
+}
+
+class MyComponent extends JComponent {
+    private final Font font = new Font("Menlo", Font.ITALIC, 100);
+    private final String text = "\u0627"; // Arabic letter alef
+
+    @Override
+    protected void paintComponent(Graphics g) {
+        if (font.canDisplayUpTo(text) == -1) {
+            g.setColor(Color.black);
+            g.setFont(font);
+            g.drawString(text, 70, 110);
+        }
+    }
+}
+
+
+
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/font/TextLayout/HitTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,49 @@
+/*
+ * Copyright (c) 2017, 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
+ * @summary verify Hit index with supplementary characters.
+ * @bug 8173028
+ */
+
+import java.awt.Font;
+import java.awt.font.FontRenderContext;
+import java.awt.font.TextHitInfo;
+import java.awt.font.TextLayout;
+
+public class HitTest {
+
+  public static void main(String args[]) {
+      String s = new String(new int[]{0x1d400, 0x61}, 0, 2);
+      Font font = new Font("Dialog", Font.PLAIN, 12);
+      FontRenderContext frc = new FontRenderContext(null, false, false);
+      TextLayout tl = new TextLayout(s, font, frc);
+      TextHitInfo currHit = TextHitInfo.beforeOffset(3);
+      TextHitInfo prevHit = tl.getNextLeftHit(currHit);
+      System.out.println("index=" + prevHit.getCharIndex()+
+                         " leading edge=" + prevHit.isLeadingEdge());
+      if (prevHit.getCharIndex() != 2) {
+          throw new RuntimeException("Expected 2 for hit index");
+      }
+   }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/font/TextLayout/MissingCodePointLayoutTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,40 @@
+/*
+ * Copyright (c) 2017, 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
+ */
+
+/* @test
+ * @summary Verify no exception for unsupported code point.
+ * @bug 8172967
+ */
+import java.awt.Font;
+import java.awt.font.FontRenderContext;
+import java.awt.font.TextLayout;
+
+public class MissingCodePointLayoutTest {
+    public static void main(String[] args) {
+        Font font = new Font("Tahoma", Font.PLAIN, 12);
+        String text = "\ude00";
+        FontRenderContext frc = new FontRenderContext(null, false, false);
+        TextLayout layout = new TextLayout(text, font, frc);
+        layout.getCaretShapes(0);
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/image/ColorModel/EqualsTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,86 @@
+/*
+ * Copyright (c) 2017, 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 4524500 7107905
+ * @run main EqualsTest
+ * @summary Tests whether ColorModel.equals() succeeds using a
+ * user-implemented subclass of ColorModel which calls the ColorModel(int bits)
+ * constructor. The test fails if an exception is thrown when equals()
+ * is called or if equals() returns an incorrect value.
+ */
+
+import java.awt.image.ColorModel;
+
+public class EqualsTest {
+
+    public static void main(String[] args) {
+        SimpleColorModel scm1 = new SimpleColorModel(3);
+        SimpleColorModel scm2 = new SimpleColorModel(3);
+        SimpleColorModel scm3 = new SimpleColorModel(8);
+        ColorModel rgbcm = ColorModel.getRGBdefault();
+
+        try {
+            if (scm1.equals(scm2)) {
+                throw new RuntimeException("Test 1 failed: " +
+                                           "scm1 should not equal scm2");
+            }
+
+            if (scm1.equals(scm3)) {
+                throw new RuntimeException("Test 2 failed: " +
+                                           "scm1 should not equal scm3");
+            }
+
+            if (scm1.equals(rgbcm) || rgbcm.equals(scm1)) {
+                throw new RuntimeException("Test 3 failed: " +
+                                           "scm1 should not equal rgbcm");
+            }
+        } catch (Exception e) {
+            throw new RuntimeException("Test failed: " + e);
+        }
+    }
+
+    private static class SimpleColorModel extends ColorModel {
+
+        public SimpleColorModel(int bits) {
+            super(bits);
+        }
+
+        public int getRed(int pixel) {
+            return 0;
+        }
+
+        public int getGreen(int pixel) {
+            return 0;
+        }
+
+        public int getBlue(int pixel) {
+            return 0;
+        }
+
+        public int getAlpha(int pixel) {
+            return 0;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/image/ComponentColorModel/ComponentColorModelEqualsTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,118 @@
+/*
+ * Copyright (c) 2017, 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     7107905
+ * @summary Test verifies whether equals() and hashCode() methods in
+ *          ComponentColorModel works properly.
+ * @run     main ComponentColorModelEqualsTest
+ */
+
+import java.awt.Transparency;
+import java.awt.color.ColorSpace;
+import java.awt.image.ComponentColorModel;
+import java.awt.image.DataBuffer;
+
+public class ComponentColorModelEqualsTest {
+
+    private static void verifyEquals(ComponentColorModel m1,
+                                     ComponentColorModel m2) {
+        if (m1.equals(null)) {
+            throw new RuntimeException("equals(null) returns true");
+        }
+        if (!(m1.equals(m2))) {
+            throw new RuntimeException("equals() method is not working"
+                    + " properly");
+        }
+        if (!(m2.equals(m1))) {
+            throw new RuntimeException("equals() method is not working"
+                    + " properly");
+        }
+        if (m1.hashCode() != m2.hashCode()) {
+            throw new RuntimeException("HashCode is not same for same"
+                    + " ComponentColorModels");
+        }
+    }
+
+    private static void testConstructor1() {
+        /*
+         * verify equality with constructor
+         * ComponentColorModel(ColorSpace colorSpace,
+         *                  int[] bits,
+         *                  boolean hasAlpha,
+         *                  boolean isAlphaPremultiplied,
+         *                  int transparency,
+         *                  int transferType)
+         */
+        ComponentColorModel model1 =
+            new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
+                                    new int[] {8, 8, 8},
+                                    false,
+                                    false,
+                                    Transparency.OPAQUE,
+                                    DataBuffer.TYPE_BYTE);
+        ComponentColorModel model2 =
+            new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
+                                    new int[] {8, 8, 8},
+                                    false,
+                                    false,
+                                    Transparency.OPAQUE,
+                                    DataBuffer.TYPE_BYTE);
+        verifyEquals(model1, model2);
+    }
+
+    private static void testConstructor2() {
+        /*
+         * verify equality with constructor
+         * ComponentColorModel(ColorSpace colorSpace,
+         *                  boolean hasAlpha,
+         *                  boolean isAlphaPremultiplied,
+         *                  int transparency,
+         *                  int transferType)
+         */
+        ComponentColorModel model1 =
+            new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
+                                    false,
+                                    false,
+                                    Transparency.OPAQUE,
+                                    DataBuffer.TYPE_BYTE);
+        ComponentColorModel model2 =
+            new ComponentColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
+                                    false,
+                                    false,
+                                    Transparency.OPAQUE,
+                                    DataBuffer.TYPE_BYTE);
+        verifyEquals(model1, model2);
+    }
+
+    private static void testSameComponentColorModel() {
+        testConstructor1();
+        testConstructor2();
+    }
+    public static void main(String[] args) {
+        // verify ComponentColorModel equality using different constructors.
+        testSameComponentColorModel();
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/image/IndexColorModel/IndexColorModelEqualsTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,250 @@
+/*
+ * Copyright (c) 2017, 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     7107905
+ * @summary Test verifies whether equals() and hashCode() methods in
+ *          IndexColorModel works properly for IndexColorModel unique
+ *          properties.
+ * @run     main IndexColorModelEqualsTest
+ */
+
+import java.awt.image.DataBuffer;
+import java.awt.image.IndexColorModel;
+import java.math.BigInteger;
+
+public class IndexColorModelEqualsTest {
+
+    private static void verifyEquals(IndexColorModel m1,
+                                     IndexColorModel m2) {
+        if (m1.equals(null)) {
+            throw new RuntimeException("equals(null) returns true");
+        }
+        if (!(m1.equals(m2))) {
+            throw new RuntimeException("equals() method is not working"
+                    + " properly");
+        }
+        if (!(m2.equals(m1))) {
+            throw new RuntimeException("equals() method is not working"
+                    + " properly");
+        }
+        if (m1.hashCode() != m2.hashCode()) {
+            throw new RuntimeException("HashCode is not same for same"
+                    + " IndexColorModels");
+        }
+    }
+
+    private static void testColorMapEquality() {
+        // test with different cmap values.
+        IndexColorModel model1 = new IndexColorModel(8, 3, new int[] {1, 2, 3},
+                0, true, -1, DataBuffer.TYPE_BYTE);
+        IndexColorModel model2 = new IndexColorModel(8, 3, new int[] {4, 5, 6},
+                0, true, -1, DataBuffer.TYPE_BYTE);
+        if (model1.equals(model2)) {
+            throw new RuntimeException("equals() method is determining"
+                    + " ColorMap equality improperly");
+        }
+        if (model2.equals(model1)) {
+            throw new RuntimeException("equals() method is determining"
+                    + " ColorMap equality improperly");
+        }
+    }
+
+    private static void testSizeEquality() {
+        // test with different size for cmap.
+        IndexColorModel model1 = new IndexColorModel(8, 4,
+                new int[] {1, 2, 3, 4},
+                0, true, -1, DataBuffer.TYPE_BYTE);
+        IndexColorModel model2 = new IndexColorModel(8, 3,
+                new int[] {1, 2, 3},
+                0, true, -1, DataBuffer.TYPE_BYTE);
+        if (model1.equals(model2)) {
+            throw new RuntimeException("equals() method is determining"
+                    + " Map size equality improperly");
+        }
+        if (model2.equals(model1)) {
+            throw new RuntimeException("equals() method is determining"
+                    + " Map size equality improperly");
+        }
+    }
+
+    private static void testTransparentIndexEquality() {
+        // test with different values for transparent_index.
+        IndexColorModel model1 = new IndexColorModel(8, 3, new int[] {1, 2, 3},
+                0, true, 1, DataBuffer.TYPE_BYTE);
+        IndexColorModel model2 = new IndexColorModel(8, 3, new int[] {1, 2, 3},
+                0, true, 2, DataBuffer.TYPE_BYTE);
+        if (model1.equals(model2)) {
+            throw new RuntimeException("equals() method is determining"
+                    + " TransparentIndex equality improperly");
+        }
+        if (model2.equals(model1)) {
+            throw new RuntimeException("equals() method is determining"
+                    + " TransparentIndex equality improperly");
+        }
+    }
+
+    private static void testValidPixelsEquality() {
+        // test with different valid pixels.
+        /*
+         * In setRGBs() function of IndexColorModel we override
+         * transparent_index value to map to pixel value if alpha is 0x00
+         * so we should have atleast minimum alpha value to verify
+         * equality of validBits thats why we have color value as
+         * 16777216(2 ^ 24).
+         */
+        int color = 16777216;
+        IndexColorModel model1 = new IndexColorModel(8, 3, new int[] {color,
+                color, color}, 0, DataBuffer.TYPE_BYTE, new BigInteger("1"));
+        IndexColorModel model2 = new IndexColorModel(8, 3, new int[] {color,
+                color, color}, 0, DataBuffer.TYPE_BYTE, new BigInteger("2"));
+        if (model1.equals(model2)) {
+            throw new RuntimeException("equals() method is determining"
+                    + " Valid pixels equality improperly");
+        }
+        if (model2.equals(model1)) {
+            throw new RuntimeException("equals() method is determining"
+                    + " Valid pixels equality improperly");
+        }
+    }
+
+    private static void testConstructor1() {
+        /*
+         * verify equality with constructor
+         * IndexColorModel(int bits, int size, byte[] r, byte[] g, byte[] b)
+         */
+        IndexColorModel model1 = new IndexColorModel(8, 2,
+                new byte[] {1, 2}, new byte[] {1, 2}, new byte[] {1, 2});
+        IndexColorModel model2 = new IndexColorModel(8, 2,
+                new byte[] {1, 2}, new byte[] {1, 2}, new byte[] {1, 2});
+        verifyEquals(model1, model2);
+    }
+
+    private static void testConstructor2() {
+        /*
+         * verify equality with constructor
+         * IndexColorModel(int bits, int size, byte[] r, byte[] g, byte[] b,
+         * byte[] a)
+         */
+        IndexColorModel model1 = new IndexColorModel(8, 2, new byte[] {1, 2},
+                new byte[] {1, 2}, new byte[] {1, 2}, new byte[] {1, 2});
+        IndexColorModel model2 = new IndexColorModel(8, 2, new byte[] {1, 2},
+                new byte[] {1, 2}, new byte[] {1, 2}, new byte[] {1, 2});
+        verifyEquals(model1, model2);
+    }
+
+    private static void testConstructor3() {
+        /*
+         * verify equality with constructor
+         * IndexColorModel(int bits, int size, byte[] r, byte[] g, byte[] b,
+         * int trans)
+         */
+        IndexColorModel model1 = new IndexColorModel(8, 2, new byte[] {1, 2},
+                new byte[] {1, 2}, new byte[] {1, 2}, 1);
+        IndexColorModel model2 = new IndexColorModel(8, 2, new byte[] {1, 2},
+                new byte[] {1, 2}, new byte[] {1, 2}, 1);
+        verifyEquals(model1, model2);
+    }
+
+    private static void testConstructor4() {
+        /*
+         * verify equality with constructor
+         * IndexColorModel(int bits, int size, byte[] cmap, int start,
+         * boolean hasalpha)
+         */
+        IndexColorModel model1 = new IndexColorModel(8, 1,
+                new byte[] {1, 2, 3, 4}, 0, true);
+        IndexColorModel model2 = new IndexColorModel(8, 1,
+                new byte[] {1, 2, 3, 4}, 0, true);
+        verifyEquals(model1, model2);
+    }
+
+    private static void testConstructor5() {
+        /*
+         * verify equality with constructor
+         * IndexColorModel(int bits, int size, byte[] cmap, int start,
+         * boolean hasalpha, int trans)
+         */
+        IndexColorModel model1 = new IndexColorModel(8, 1,
+                new byte[] {1, 2, 3, 4}, 0, true, 0);
+        IndexColorModel model2 = new IndexColorModel(8, 1,
+                new byte[] {1, 2, 3, 4}, 0, true, 0);
+        verifyEquals(model1, model2);
+    }
+
+    private static void testConstructor6() {
+        /*
+         * verify equality with constructor
+         * IndexColorModel(int bits, int size, int[] cmap, int start,
+         * boolean hasalpha, int trans, int transferType)
+         */
+        IndexColorModel model1 = new IndexColorModel(8, 3, new int[] {1, 2, 3},
+                0, true, -1, DataBuffer.TYPE_BYTE);
+        IndexColorModel model2 = new IndexColorModel(8, 3, new int[] {1, 2, 3},
+                0, true, -1, DataBuffer.TYPE_BYTE);
+        verifyEquals(model1, model2);
+    }
+
+    private static void testConstructor7() {
+        /*
+         * verify equality with constructor
+         * IndexColorModel(int bits, int size, int[] cmap, int start,
+         * int transferType, BigInteger validBits)
+         */
+        /*
+         * In setRGBs() function of IndexColorModel we override
+         * transparent_index value to map to pixel value if alpha is 0x00
+         * so we should have atleast minimum alpha value to keep
+         * both model1 and model2 same.
+         */
+        int color = 16777216;
+        IndexColorModel model1 = new IndexColorModel(8, 3, new int[] {color,
+                color, color}, 0, DataBuffer.TYPE_BYTE, new BigInteger("1"));
+        IndexColorModel model2 = new IndexColorModel(8, 3, new int[] {color,
+                color, color}, 0, DataBuffer.TYPE_BYTE, new BigInteger("1"));
+        verifyEquals(model1, model2);
+    }
+
+    private static void testSameIndexColorModel() {
+        testConstructor1();
+        testConstructor2();
+        testConstructor3();
+        testConstructor4();
+        testConstructor5();
+        testConstructor6();
+        testConstructor7();
+    }
+    public static void main(String[] args) {
+        /* test whether equals() method works properly for parameters
+         * unique to IndexColorModel.
+         */
+        testColorMapEquality();
+        testSizeEquality();
+        testTransparentIndexEquality();
+        testValidPixelsEquality();
+        // verify same IndexColorModel equality using different constructors.
+        testSameIndexColorModel();
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/awt/image/PackedColorModel/PackedColorModelEqualsTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,119 @@
+/*
+ * Copyright (c) 2017, 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     7107905
+ * @summary Test verifies whether equals() and hashCode() methods in
+ *          PackedColorModel works properly.
+ * @run     main PackedColorModelEqualsTest
+ */
+
+import java.awt.color.ColorSpace;
+import java.awt.image.DataBuffer;
+import java.awt.image.DirectColorModel;
+
+public class PackedColorModelEqualsTest {
+
+    private static void verifyEquals(DirectColorModel m1,
+                                     DirectColorModel m2) {
+        if (m1.equals(null)) {
+            throw new RuntimeException("equals(null) returns true");
+        }
+        if (!(m1.equals(m2))) {
+            throw new RuntimeException("equals() method is not working"
+                    + " properly");
+        }
+        if (!(m2.equals(m1))) {
+            throw new RuntimeException("equals() method is not working"
+                    + " properly");
+        }
+        if (m1.hashCode() != m2.hashCode()) {
+            throw new RuntimeException("HashCode is not same for same"
+                    + " PackedColorModels");
+        }
+    }
+
+    private static void testMaskArrayEquality() {
+        /*
+         * Test with different maskArray values, since PackedColorModel
+         * is abstract we use subclass DirectColorModel.
+         */
+        DirectColorModel model1 =
+            new DirectColorModel(24, 0x00FF0000, 0x0000FF00, 0x000000FF);
+        DirectColorModel model2 =
+            new DirectColorModel(24, 0x000000FF, 0x0000FF00, 0x00FF0000);
+        if (model1.equals(model2)) {
+            throw new RuntimeException("equals() method is determining"
+                    + " ColorMap equality improperly");
+        }
+        if (model2.equals(model1)) {
+            throw new RuntimeException("equals() method is determining"
+                    + " ColorMap equality improperly");
+        }
+    }
+
+    private static void testConstructor1() {
+        /*
+         * verify equality with constructor
+         * DirectColorModel(int bits, int rmask, int gmask, int bmask,
+         *    int amask)
+         */
+        DirectColorModel model1 =
+            new DirectColorModel(32, 0xFF000000, 0x00FF0000,
+                    0x0000FF00, 0x000000FF);
+        DirectColorModel model2 =
+            new DirectColorModel(32, 0xFF000000, 0x00FF0000,
+                    0x0000FF00, 0x000000FF);
+        verifyEquals(model1, model2);
+    }
+
+    private static void testConstructor2() {
+        /*
+         * verify equality with constructor
+         * DirectColorModel(ColorSpace space, int bits, int rmask, int gmask,
+         * int bmask, int amask, boolean isAlphaPremultiplied, int transferType)
+         */
+        DirectColorModel model1 =
+            new DirectColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
+                    32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF,
+                    false, DataBuffer.TYPE_BYTE);
+        DirectColorModel model2 =
+            new DirectColorModel(ColorSpace.getInstance(ColorSpace.CS_sRGB),
+                    32, 0xFF000000, 0x00FF0000, 0x0000FF00, 0x000000FF,
+                    false, DataBuffer.TYPE_BYTE);
+        verifyEquals(model1, model2);
+    }
+
+    private static void testSamePackedColorModel() {
+        testConstructor1();
+        testConstructor2();
+    }
+    public static void main(String[] args) {
+        // test with different mask array.
+        testMaskArrayEquality();
+        // verify PackedColorModel equality using different constructors.
+        testSamePackedColorModel();
+    }
+}
+
--- a/jdk/test/java/awt/jdk/TestJDKAWTUtils.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,59 +0,0 @@
-/*
- * 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 8167126
- */
-import java.awt.BorderLayout;
-import java.awt.Font;
-import java.awt.Rectangle;
-import javax.swing.JButton;
-import javax.swing.JFrame;
-import javax.swing.JPanel;
-import javax.swing.SwingUtilities;
-
-public class TestJDKAWTUtils {
-
-    static JFrame f;
-    public static void main(String[] args) throws Exception {
-
-        SwingUtilities.invokeAndWait(() -> {
-            f = new JFrame("test");
-            JPanel p = new JPanel();
-            JButton b = new JButton("Hello");
-            b.setFont(new Font(Font.DIALOG, Font.PLAIN, 80));
-            p.setLayout(new BorderLayout());
-            p.add("Center", b);
-            f.getContentPane().add(p);
-            f.pack();
-            f.setVisible(true);
-            Rectangle r = new Rectangle(0, 0, 50, 50);
-            jdk.awt.AWTUtils.setComponentMixingCutoutShape(b, r);
-        });
-        Thread.sleep(2000);
-        SwingUtilities.invokeAndWait(() -> f.dispose());
-    }
-}
--- a/jdk/test/java/awt/print/PrinterJob/PrintAttributeUpdateTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/awt/print/PrinterJob/PrintAttributeUpdateTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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 8042713
+  @bug 8042713 8170578
   @summary  Print Dialog does not update attribute set with page range
   @run main/manual PrintAttributeUpdateTest
  */
--- a/jdk/test/java/io/FileInputStream/LargeFileAvailable.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/io/FileInputStream/LargeFileAvailable.java	Thu Mar 16 20:47:03 2017 +0000
@@ -71,6 +71,9 @@
         } finally {
             file.delete();
         }
+
+        System.out.println("Test succeeded.");
+        System.out.flush();
     }
 
     // Skip toSkip number of bytes and expect that the available() method
--- a/jdk/test/java/io/FilePermission/ReadFileOnPath.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/io/FilePermission/ReadFileOnPath.java	Thu Mar 16 20:47:03 2017 +0000
@@ -57,7 +57,7 @@
                 "module-info.class", "base", "p/App.class", "p/child");
 
         // exploded module
-        test("--module-path", "modules", "-m", "m/p.App", "SS+++++");
+        test("--module-path", "modules", "-m", "m/p.App", "SS++++0");
 
         // module in jar
         test("--module-path", "new.jar", "-m", "m/p.App", "SSSS++0");
--- a/jdk/test/java/lang/Class/forName/modules/TestLayer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/Class/forName/modules/TestLayer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -46,9 +46,9 @@
         ModuleFinder finder = ModuleFinder.of(MODS_DIR);
 
         Configuration parent = Layer.boot().configuration();
-        Configuration cf = parent.resolveRequiresAndUses(ModuleFinder.of(),
-                                                         finder,
-                                                         modules);
+        Configuration cf = parent.resolveAndBind(ModuleFinder.of(),
+                                                 finder,
+                                                 modules);
 
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer = Layer.boot().defineModulesWithManyLoaders(cf, scl);
--- a/jdk/test/java/lang/Class/forName/modules/src/m3/p3/NoAccess.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/Class/forName/modules/src/m3/p3/NoAccess.java	Thu Mar 16 20:47:03 2017 +0000
@@ -50,9 +50,9 @@
         Layer bootLayer = Layer.boot();
         Configuration parent = bootLayer.configuration();
 
-        Configuration cf = parent.resolveRequiresAndUses(finder,
-                                                         ModuleFinder.of(),
-                                                         Set.of("m1", "m2"));
+        Configuration cf = parent.resolveAndBind(finder,
+                                                 ModuleFinder.of(),
+                                                 Set.of("m1", "m2"));
 
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer = bootLayer.defineModulesWithManyLoaders(cf, scl);
--- a/jdk/test/java/lang/Class/getPackageName/Basic.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/Class/getPackageName/Basic.java	Thu Mar 16 20:47:03 2017 +0000
@@ -154,8 +154,8 @@
         return new Object[][] {
 
             { Basic.class,                  TEST_PACKAGE },
-            { Basic[].class,                null },
-            { Basic[][].class,              null },
+            { Basic[].class,                TEST_PACKAGE },
+            { Basic[][].class,              TEST_PACKAGE },
 
             { getNestedClass1(),            TEST_PACKAGE },
             { getNestedClass2(),            TEST_PACKAGE },
@@ -174,14 +174,14 @@
             { getAnonymousClass6(),         TEST_PACKAGE },
 
             { Object.class,                 "java.lang" },
-            { Object[].class,               null },
-            { Object[][].class,             null },
+            { Object[].class,               "java.lang" },
+            { Object[][].class,             "java.lang" },
 
-            { int.class,                    null },
-            { int[].class,                  null },
-            { int[][].class,                null },
+            { int.class,                    "java.lang" },
+            { int[].class,                  "java.lang" },
+            { int[][].class,                "java.lang" },
 
-            { void.class,                   null },
+            { void.class,                   "java.lang" },
 
         };
     }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/ClassLoader/securityManager/ClassLoaderTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,297 @@
+/*
+ * Copyright (c) 2017, 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 8168423
+ * @summary Different types of ClassLoader running with(out) SecurityManager and
+ *          (in)valid security policy file.
+ * @library /lib/testlibrary
+ * @modules java.base/jdk.internal.module
+ * @build JarUtils CompilerUtils
+ * @run main/timeout=240 ClassLoaderTest
+ */
+import java.io.File;
+import java.io.OutputStream;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.StandardCopyOption;
+import java.util.Map;
+import java.util.HashMap;
+import java.lang.module.ModuleDescriptor;
+import jdk.internal.module.ModuleInfoWriter;
+import jdk.testlibrary.ProcessTools;
+
+public class ClassLoaderTest {
+
+    private static final String SRC = System.getProperty("test.src");
+    private static final Path CL_SRC = Paths.get(SRC, "TestClassLoader.java");
+    private static final Path C_SRC = Paths.get(SRC, "TestClient.java");
+    private static final Path CL_BIN = Paths.get("classes", "clbin");
+    private static final Path C_BIN = Paths.get("classes", "cbin");
+    private static final Path ARTIFACT_DIR = Paths.get("jars");
+    private static final Path VALID_POLICY = Paths.get(SRC, "valid.policy");
+    private static final Path INVALID_POLICY
+            = Paths.get(SRC, "malformed.policy");
+    private static final Path NO_POLICY = null;
+    private static final String LOCALE = "-Duser.language=en -Duser.region=US";
+    /*
+     * Here is the naming convention followed for each jar.
+     * cl.jar   - Regular custom class loader jar.
+     * mcl.jar  - Modular custom class loader jar.
+     * c.jar    - Regular client jar.
+     * mc.jar   - Modular client jar.
+     * amc.jar  - Modular client referring automated custom class loader jar.
+     */
+    private static final Path CL_JAR = ARTIFACT_DIR.resolve("cl.jar");
+    private static final Path MCL_JAR = ARTIFACT_DIR.resolve("mcl.jar");
+    private static final Path C_JAR = ARTIFACT_DIR.resolve("c.jar");
+    private static final Path MC_JAR = ARTIFACT_DIR.resolve("mc.jar");
+    private static final Path AMC_JAR = ARTIFACT_DIR.resolve("amc.jar");
+    private static final Map<String, String> MSG_MAP = new HashMap<>();
+
+    static {
+        // This mapping help process finding expected message based
+        // on the key passed as argument while executing java command.
+        MSG_MAP.put("MissingModule", "Module cl not found, required by mc");
+        MSG_MAP.put("ErrorPolicy", "java.security.policy: error parsing file");
+        MSG_MAP.put(
+                "SystemCL", "jdk.internal.loader.ClassLoaders$AppClassLoader");
+        MSG_MAP.put("CustomCL", "cl.TestClassLoader");
+    }
+
+    public static void main(String[] args) throws Exception {
+
+        // Generates regular and modular jars before start processing it.
+        setUp();
+        processForEachPolicyFile();
+    }
+
+    /**
+     * Test cases are based on the following logic,
+     *  for (policyFile : {"NO_POLICY", "VALID", "MALFORMED"}) {
+     *      for (classLoader : {"SystemClassLoader", "CustomClassLoader"}){
+     *          for (clientModule : {"NAMED", "AUTOMATIC", "UNNAMED"}) {
+     *              for (classLoaderModule : {"NAMED", "AUTOMATIC", "UNNAMED"}) {
+     *                  Create and run java command for each possible Test case
+     *              }
+     *          }
+     *      }
+     *  }
+     */
+    private static void processForEachPolicyFile() throws Exception {
+
+        final String regCLloc = CL_JAR.toFile().getAbsolutePath();
+        final String modCLloc = MCL_JAR.toFile().getAbsolutePath();
+        final String regCloc = C_JAR.toFile().getAbsolutePath();
+        final String modCloc = MC_JAR.toFile().getAbsolutePath();
+        final String autoModCloc = AMC_JAR.toFile().getAbsolutePath();
+        final String separator = File.pathSeparator;
+
+        for (Path policy
+                : new Path[]{NO_POLICY, VALID_POLICY, INVALID_POLICY}) {
+            final String policyFile = (policy != null)
+                    ? policy.toFile().getAbsolutePath() : null;
+            final boolean malformedPolicy
+                    = (policy == null) ? false : policy.equals(INVALID_POLICY);
+
+            for (boolean useSCL : new boolean[]{true, false}) {
+                final String clVmArg = (useSCL) ? ""
+                        : "-Djava.system.class.loader=cl.TestClassLoader";
+                final String autoAddModArg
+                        = (useSCL) ? "" : "--add-modules=cl";
+                final String addmodArg = (useSCL) ? "" : "--add-modules=mcl";
+                final String sMArg = (policy != null) ? String.format(
+                        "-Djava.security.manager -Djava.security.policy=%s",
+                        policyFile) : "";
+                final String smMsg = (policy != null) ? "With SecurityManager"
+                        : "Without SecurityManager";
+                final String expectedResult = ((!malformedPolicy)
+                        ? ((useSCL) ? "PASS SystemCL" : "PASS CustomCL")
+                        : "FAIL ErrorPolicy");
+
+                // NAMED-NAMED, NAMED-AUTOMATIC, NAMED-UNNAMED
+                System.out.printf("Case:- Modular Client and %s %s%n",
+                        ((useSCL) ? "SystemClassLoader"
+                                : "Modular CustomClassLoader"), smMsg);
+                execute(new String[]{String.format(
+                    "--module-path %s%s%s %s %s %s -m mc/c.TestClient",
+                    modCloc, separator, modCLloc, LOCALE, clVmArg, sMArg),
+                    expectedResult});
+                System.out.printf("Case:- Modular Client and %s %s%n", ((useSCL)
+                        ? "SystemClassLoader"
+                        : "Automatic modular CustomClassLoader"), smMsg);
+                execute(new String[]{String.format(
+                    "--module-path %s%s%s %s %s %s -m mc/c.TestClient",
+                    autoModCloc, separator, regCLloc, LOCALE, clVmArg, sMArg),
+                    expectedResult});
+                System.out.printf("Case:- Modular Client and %s %s%n", ((useSCL)
+                        ? "SystemClassLoader"
+                        : "Unknown modular CustomClassLoader"), smMsg);
+                execute(new String[]{String.format(
+                    "--module-path %s -cp %s %s %s %s -m mc/c.TestClient",
+                    autoModCloc, regCLloc, LOCALE, clVmArg, sMArg),
+                    "FAIL MissingModule"});
+
+                // AUTOMATIC-NAMED, AUTOMATIC-AUTOMATIC, AUTOMATIC-UNNAMED
+                System.out.printf("Case:- Automated modular Client and %s %s%n",
+                        ((useSCL) ? "SystemClassLoader"
+                                : "Modular CustomClassLoader"), smMsg);
+                execute(new String[]{String.format(
+                    "--module-path %s%s%s %s %s %s %s -m c/c.TestClient",
+                    regCloc, separator, modCLloc, addmodArg, LOCALE, clVmArg,
+                    sMArg), expectedResult});
+                System.out.printf("Case:- Automated modular Client and %s %s%n",
+                        ((useSCL) ? "SystemClassLoader"
+                                : "Automatic modular CustomClassLoader"),
+                        smMsg);
+                execute(new String[]{String.format(
+                    "--module-path %s%s%s %s %s %s %s -m c/c.TestClient",
+                    regCloc, separator, regCLloc, autoAddModArg, LOCALE,
+                    clVmArg, sMArg), expectedResult});
+                System.out.printf("Case:- Automated modular Client and %s %s%n",
+                        ((useSCL) ? "SystemClassLoader"
+                                : "Unknown modular CustomClassLoader"), smMsg);
+                execute(new String[]{String.format(
+                    "--module-path %s -cp %s %s %s %s -m c/c.TestClient",
+                    regCloc, regCLloc, LOCALE, clVmArg, sMArg),
+                    expectedResult});
+
+                // UNNAMED-NAMED, UNNAMED-AUTOMATIC, UNNAMED-UNNAMED
+                System.out.printf("Case:- Unknown modular Client and %s %s%n",
+                        ((useSCL) ? "SystemClassLoader"
+                                : "Modular CustomClassLoader"), smMsg);
+                execute(new String[]{String.format(
+                    "-cp %s --module-path %s %s %s %s %s c.TestClient",
+                    regCloc, modCLloc, addmodArg, LOCALE, clVmArg, sMArg),
+                    expectedResult});
+                System.out.printf("Case:- Unknown modular Client and %s %s%n",
+                        ((useSCL) ? "SystemClassLoader"
+                                : "Automatic modular CustomClassLoader"),
+                        smMsg);
+                execute(new String[]{String.format(
+                    "-cp %s --module-path %s %s %s %s %s c.TestClient",
+                    regCloc, regCLloc, autoAddModArg, LOCALE, clVmArg, sMArg),
+                    expectedResult});
+                System.out.printf("Case:- Unknown modular Client and %s %s%n",
+                        ((useSCL) ? "SystemClassLoader"
+                                : "Unknown modular CustomClassLoader"), smMsg);
+                execute(new String[]{String.format(
+                    "-cp %s%s%s %s %s %s c.TestClient", regCloc, separator,
+                    regCLloc, LOCALE, clVmArg, sMArg), expectedResult});
+
+                // Regular jars in module-path and Modular jars in class-path.
+                System.out.printf("Case:- Regular Client and %s "
+                        + "inside --module-path %s.%n", ((useSCL)
+                                ? "SystemClassLoader"
+                                : "Unknown modular CustomClassLoader"), smMsg);
+                execute(new String[]{String.format(
+                    "--module-path %s%s%s %s %s %s %s -m c/c.TestClient",
+                    regCloc, separator, regCLloc, autoAddModArg, LOCALE,
+                    clVmArg, sMArg), expectedResult});
+                System.out.printf("Case:- Modular Client and %s in -cp %s%n",
+                        ((useSCL) ? "SystemClassLoader"
+                                : "Modular CustomClassLoader"), smMsg);
+                execute(new String[]{String.format(
+                    "-cp %s%s%s %s %s %s c.TestClient", modCloc, separator,
+                    modCLloc, LOCALE, clVmArg, sMArg), expectedResult});
+            }
+        }
+    }
+
+    /**
+     * Execute with command arguments and process the result.
+     */
+    private static void execute(String[] args) throws Exception {
+
+        String status = null;
+        String msgKey = null;
+        if ((args != null && args.length > 1)) {
+            String[] secArgs = args[1].split("\\s+");
+            status = (secArgs.length > 0) ? secArgs[0] : null;
+            msgKey = (secArgs.length > 1) ? secArgs[1] : null;
+        }
+        String out = ProcessTools.executeTestJvm(args[0].split("\\s+"))
+                .getOutput();
+        // Handle response.
+        if ((status != null && "PASS".equals(status) && msgKey != null
+                && out.contains(MSG_MAP.get(msgKey)))) {
+            System.out.printf("PASS: Expected Result: %s.%n",
+                    MSG_MAP.get(msgKey));
+        } else if ((status != null && "FAIL".equals(status) && msgKey != null
+                && out.contains(MSG_MAP.get(msgKey)))) {
+            System.out.printf("PASS: Expected Failure: %s.%n",
+                    MSG_MAP.get(msgKey));
+        } else if (out.contains("Exception") || out.contains("Error")) {
+            System.out.printf("OUTPUT: %s", out);
+            throw new RuntimeException("FAIL: Unknown Exception.");
+        } else {
+            System.out.printf("OUTPUT: %s", out);
+            throw new RuntimeException("FAIL: Unknown Test case found");
+        }
+    }
+
+    /**
+     * Creates regular/modular jar files for TestClient and TestClassLoader.
+     */
+    private static void setUp() throws Exception {
+
+        boolean compiled = CompilerUtils.compile(CL_SRC, CL_BIN);
+        compiled &= CompilerUtils.compile(C_SRC, C_BIN);
+        if (!compiled) {
+            throw new RuntimeException("Test Setup failed.");
+        }
+        // Generate regular jar files for TestClient and TestClassLoader
+        JarUtils.createJarFile(CL_JAR, CL_BIN);
+        JarUtils.createJarFile(C_JAR, C_BIN);
+        // Generate modular jar files for TestClient and TestClassLoader with
+        // their corresponding ModuleDescriptor.
+        Files.copy(CL_JAR, MCL_JAR, StandardCopyOption.REPLACE_EXISTING);
+        updateModuleDescr(MCL_JAR, ModuleDescriptor.newModule("mcl")
+                .exports("cl").requires("java.base").build());
+        Files.copy(C_JAR, MC_JAR, StandardCopyOption.REPLACE_EXISTING);
+        updateModuleDescr(MC_JAR, ModuleDescriptor.newModule("mc")
+                .exports("c").requires("java.base").requires("mcl").build());
+        Files.copy(C_JAR, AMC_JAR, StandardCopyOption.REPLACE_EXISTING);
+        updateModuleDescr(AMC_JAR, ModuleDescriptor.newModule("mc")
+                .exports("c").requires("java.base").requires("cl").build());
+    }
+
+    /**
+     * Update regular jars and include module-info.class inside it to make
+     * modular jars.
+     */
+    private static void updateModuleDescr(Path jar, ModuleDescriptor mDescr)
+            throws Exception {
+        if (mDescr != null) {
+            Path dir = Files.createTempDirectory("tmp");
+            Path mi = dir.resolve("module-info.class");
+            try (OutputStream out = Files.newOutputStream(mi)) {
+                ModuleInfoWriter.write(mDescr, out);
+            }
+            System.out.format("Adding 'module-info.class' to jar '%s'%n", jar);
+            JarUtils.updateJarFile(jar, dir);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/ClassLoader/securityManager/TestClassLoader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2017, 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 cl;
+
+public class TestClassLoader extends ClassLoader {
+
+    /**
+     * This constructor is used to set the parent ClassLoader
+     */
+    public TestClassLoader(ClassLoader parent) {
+        super(parent);
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/ClassLoader/securityManager/TestClient.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2017, 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 c;
+
+public class TestClient {
+
+    public static void main(String[] args) {
+
+        // Initialize policy file.
+        System.getProperty("test.src");
+        System.out.printf("ContextClassLoader: %s%n",
+                Thread.currentThread().getContextClassLoader().toString());
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/ClassLoader/securityManager/malformed.policy	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,4 @@
+grant {
+    xyz;
+    permission java.util.PropertyPermission "test.src", "read";
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/ClassLoader/securityManager/valid.policy	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,4 @@
+grant codeBase "file:./jars/*" {
+    permission java.lang.RuntimePermission "createClassLoader";
+    permission java.util.PropertyPermission "test.src", "read";
+};
\ No newline at end of file
--- a/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/SecurityManager/CheckPackageAccess.java	Thu Mar 16 20:47:03 2017 +0000
@@ -33,6 +33,7 @@
 
 import java.lang.module.ModuleFinder;
 import java.lang.module.ModuleReference;
+import java.lang.reflect.Layer;
 import java.util.Arrays;
 import java.util.List;
 import java.util.Optional;
@@ -80,25 +81,33 @@
         }
 
         void test() {
-            System.out.println("Testing module " + moduleName);
+            final boolean isModulePresent =
+                        Layer.boot().findModule(moduleName).isPresent();
+            System.out.format("Testing module: %1$s. Module is%2$s present.\n",
+                        moduleName, isModulePresent ? "" : " NOT");
 
-            // access to exported pkg should pass
-            testNonRestricted(exports);
+            if (isModulePresent) {
 
-            // access to opened pkg should pass
-            opens.ifPresent(Test::testNonRestricted);
+                // access to exported pkg should pass
+                testNonRestricted(exports);
+
+                // access to opened pkg should pass
+                opens.ifPresent(Test::testNonRestricted);
 
-            // access to concealed pkg should fail
-            testRestricted(conceals);
+                // access to concealed pkg should fail
+                testRestricted(conceals);
 
-            // access to qualified export pkg should fail
-            qualExports.ifPresent(Test::testRestricted);
+                // access to qualified export pkg should fail
+                qualExports.ifPresent(Test::testRestricted);
 
-            // access to qualified open pkg should fail
-            qualOpens.ifPresent(Test::testRestricted);
+                // access to qualified open pkg should fail
+                qualOpens.ifPresent(Test::testRestricted);
 
-            // access to qualified opened pkg that is also exported should pass
-            qualOpensAndExports.ifPresent(Test::testNonRestricted);
+                // access to qualified opened pkg that is also exported should pass
+                qualOpensAndExports.ifPresent(Test::testNonRestricted);
+            } else {
+                System.out.println("Skipping tests for module.");
+            }
         }
 
         private static void testRestricted(String pkg) {
--- a/jdk/test/java/lang/StackTraceElement/WithClassLoaderName.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/StackTraceElement/WithClassLoaderName.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -26,6 +26,7 @@
  * @bug 6479237
  * @summary Basic test StackTraceElement with class loader names
  * @library lib /lib/testlibrary
+ * @modules jdk.compiler
  * @build m1/* WithClassLoaderName
  * @run main/othervm m1/com.app.Main
  * @run main/othervm WithClassLoaderName
--- a/jdk/test/java/lang/StackWalker/Basic.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/StackWalker/Basic.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,18 +23,21 @@
 
 /*
  * @test
- * @bug 8140450
+ * @bug 8140450 8173898
  * @summary Basic test for the StackWalker::walk method
  * @run testng Basic
  */
 
 import java.lang.StackWalker.StackFrame;
 import java.util.List;
+import java.util.Objects;
 import java.util.stream.Collectors;
+import java.util.stream.Stream;
 import static java.lang.StackWalker.Option.*;
 
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
+import static org.testng.Assert.*;
 
 public class Basic {
     private static boolean verbose = false;
@@ -60,6 +63,17 @@
         }
     }
 
+    @Test
+    public static void testWalkFromConstructor() throws Exception {
+        System.out.println("testWalkFromConstructor:");
+        List<String> found = ((ConstructorNewInstance)ConstructorNewInstance.class.getMethod("create")
+                             .invoke(null)).collectedFrames();
+        assertEquals(List.of(ConstructorNewInstance.class.getName()+"::<init>",
+                             ConstructorNewInstance.class.getName()+"::create",
+                             Basic.class.getName()+"::testWalkFromConstructor"),
+                     found);
+    }
+
     private final int depth;
     Basic(int depth) {
         this.depth = depth;
@@ -77,6 +91,47 @@
         assertEquals(limit, frames.size());
     }
 
+    static class ConstructorNewInstance {
+        static final StackWalker walker =
+            StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
+        List<String> testFramesOrReflectionFrames;
+        public ConstructorNewInstance() {
+            testFramesOrReflectionFrames = walker.walk(this::parse);
+        }
+        public List<String> collectedFrames() {
+            return testFramesOrReflectionFrames;
+        }
+        public boolean accept(StackFrame f) {
+            // Frames whose class names don't contain "."
+            // are our own test frames. These are the ones
+            // we expect.
+            // Frames whose class names contain ".reflect."
+            // are reflection frames. None should be present,
+            // since they are supposed to be filtered by
+            // by StackWalker. If we find any, we want to fail.
+            if (!f.getClassName().contains(".")
+                || f.getClassName().contains(".reflect.")) {
+                System.out.println("    " + f);
+                return true;
+            }
+            // Filter out all other frames (in particular
+            // those from the test framework) in order to
+            // have predictable results.
+            return false;
+        }
+        public String frame(StackFrame f) {
+            return f.getClassName() + "::" + f.getMethodName();
+        }
+        List<String> parse(Stream<StackFrame> s) {
+            return s.filter(this::accept)
+                    .map(this::frame)
+                    .collect(Collectors.toList());
+        }
+        public static ConstructorNewInstance create() throws Exception {
+            return ConstructorNewInstance.class.getConstructor().newInstance();
+        }
+    }
+
     class StackBuilder {
         private final int stackDepth;
         private final int limit;
@@ -131,9 +186,4 @@
         }
     }
 
-    static void assertEquals(int x, int y) {
-        if (x != y) {
-            throw new RuntimeException(x + " != " + y);
-        }
-    }
 }
--- a/jdk/test/java/lang/StackWalker/CallerFromMain.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/StackWalker/CallerFromMain.java	Thu Mar 16 20:47:03 2017 +0000
@@ -51,7 +51,7 @@
         try {
             Class<?> c = sw.getCallerClass();
             throw new RuntimeException("UOE not thrown. Caller: " + c);
-        } catch (IllegalStateException e) {}
+        } catch (IllegalCallerException e) {}
 
         // StackWalker::getCallerClass
         // Runnable::run
--- a/jdk/test/java/lang/StackWalker/CountLocalSlots.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,62 +0,0 @@
-/*
- * 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.
- */
-
-/*
- * @test
- * @bug 8147039
- * @summary Confirm locals[] always has expected length, even for "dead" locals
- * @modules java.base/java.lang:open
- * @compile LocalsAndOperands.java
- * @run testng/othervm -Xcomp CountLocalSlots
- */
-
-import org.testng.annotations.Test;
-import java.lang.StackWalker.StackFrame;
-
-public class CountLocalSlots {
-    final static boolean debug = true;
-
-    @Test(dataProvider = "provider", dataProviderClass = LocalsAndOperands.class)
-    public void countLocalSlots(StackFrame... frames) {
-        for (StackFrame frame : frames) {
-            if (debug) {
-                System.out.println("Running countLocalSlots");
-                LocalsAndOperands.dumpStackWithLocals(frames);
-            }
-            // Confirm expected number of locals
-            String methodName = frame.getMethodName();
-            Integer expectedObj = (Integer) LocalsAndOperands.Tester.NUM_LOCALS.get(methodName);
-            if (expectedObj == null) {
-                if (!debug) { LocalsAndOperands.dumpStackWithLocals(frames); }
-                throw new RuntimeException("No NUM_LOCALS entry for " +
-                        methodName + "().  Update test?");
-            }
-            Object[] locals = (Object[]) LocalsAndOperands.invokeGetLocals(frame);
-            if (locals.length != expectedObj) {
-                if (!debug) { LocalsAndOperands.dumpStackWithLocals(frames); }
-                throw new RuntimeException(methodName + "(): number of locals (" +
-                        locals.length + ") did not match expected (" + expectedObj + ")");
-            }
-        }
-    }
-}
--- a/jdk/test/java/lang/StackWalker/LocalsAndOperands.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/StackWalker/LocalsAndOperands.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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,33 +23,54 @@
 
 /*
  * @test
- * @bug 8020968 8147039
+ * @bug 8020968 8147039 8156073
  * @summary Tests for locals and operands
  * @modules java.base/java.lang:open
- * @run testng LocalsAndOperands
+ * @run testng/othervm -Xint -DtestUnused=true LocalsAndOperands
+ * @run testng/othervm -Xcomp LocalsAndOperands
+ * @run testng/othervm -Xcomp -XX:-TieredCompilation LocalsAndOperands
  */
 
 import org.testng.annotations.*;
+import static org.testng.Assert.*;
 import java.lang.StackWalker.StackFrame;
+import static java.lang.StackWalker.Option.*;
 import java.lang.reflect.*;
 import java.util.*;
 import java.util.stream.*;
 
 public class LocalsAndOperands {
-    static final boolean debug = true;
+    static final boolean debug = false;
+    static final boolean is32bit;
+    static final boolean testUnused;
 
     static Class<?> liveStackFrameClass;
-    static Class<?> primitiveValueClass;
+    static Class<?> primitiveSlotClass;
+    static Class<?> primitiveSlot32Class;
+    static Class<?> primitiveSlot64Class;
+
     static StackWalker extendedWalker;
     static Method getLocals;
     static Method getOperands;
     static Method getMonitors;
-    static Method primitiveType;
+    static Method primitiveSize;
+    static Method primitiveLongValue;
+    static Method primitiveIntValue;
+    static Method getExtendedWalker;
+
+    private static final long LOWER_LONG_VAL = 4L; // Lower bits
+    private static final long UPPER_LONG_VAL = 0x123400000000L; // Upper bits
+    private static final long NEG_LONG_VAL = Long.MIN_VALUE;
+
+    private static final double LOWER_DOUBLE_VAL = Double.longBitsToDouble(0xABCDL);
+    private static final double UPPER_DOUBLE_VAL = Double.longBitsToDouble(0x432100000000L);
 
     static {
         try {
             liveStackFrameClass = Class.forName("java.lang.LiveStackFrame");
-            primitiveValueClass = Class.forName("java.lang.LiveStackFrame$PrimitiveValue");
+            primitiveSlotClass = Class.forName("java.lang.LiveStackFrame$PrimitiveSlot");
+            primitiveSlot32Class = Class.forName("java.lang.LiveStackFrameInfo$PrimitiveSlot32");
+            primitiveSlot64Class = Class.forName("java.lang.LiveStackFrameInfo$PrimitiveSlot64");
 
             getLocals = liveStackFrameClass.getDeclaredMethod("getLocals");
             getLocals.setAccessible(true);
@@ -60,12 +81,31 @@
             getMonitors = liveStackFrameClass.getDeclaredMethod("getMonitors");
             getMonitors.setAccessible(true);
 
-            primitiveType = primitiveValueClass.getDeclaredMethod("type");
-            primitiveType.setAccessible(true);
+            primitiveSize = primitiveSlotClass.getDeclaredMethod("size");
+            primitiveSize.setAccessible(true);
+
+            primitiveLongValue = primitiveSlotClass.getDeclaredMethod("longValue");
+            primitiveLongValue.setAccessible(true);
+
+            primitiveIntValue = primitiveSlotClass.getDeclaredMethod("intValue");
+            primitiveIntValue.setAccessible(true);
 
-            Method method = liveStackFrameClass.getMethod("getStackWalker");
-            method.setAccessible(true);
-            extendedWalker = (StackWalker) method.invoke(null);
+            getExtendedWalker = liveStackFrameClass.getMethod("getStackWalker", Set.class);
+            getExtendedWalker.setAccessible(true);
+            extendedWalker = (StackWalker) getExtendedWalker.invoke(null,
+                    EnumSet.noneOf(StackWalker.Option.class));
+
+            String dataModel = System.getProperty("sun.arch.data.model");
+            if ("32".equals(dataModel)) {
+                is32bit = true;
+            } else if ("64".equals(dataModel)) {
+                is32bit= false;
+            } else {
+                throw new RuntimeException("Weird data model:" + dataModel);
+            }
+            System.out.println("VM bits: " + dataModel);
+
+            testUnused = System.getProperty("testUnused") != null;
         } catch (Throwable t) { throw new RuntimeException(t); }
     }
 
@@ -80,47 +120,17 @@
      * DataProviders *
      *****************/
 
-    /** Calls testLocals() and provides LiveStackFrames for testLocals* methods */
-    @DataProvider
-    public static StackFrame[][] provider() {
-        return new StackFrame[][] {
-            new Tester().testLocals()
-        };
-    }
-
-    /**
-     * Calls testLocalsKeepAlive() and provides LiveStackFrames for testLocals* methods.
-     * Local variables in testLocalsKeepAlive() are ensured to not become dead.
-     */
+    /** Calls KnownLocalsTester.testLocals* and provides LiveStackFrames */
     @DataProvider
-    public static StackFrame[][] keepAliveProvider() {
-        return new StackFrame[][] {
-            new Tester().testLocalsKeepAlive()
-        };
-    }
-
-    /**
-     * Provides StackFrames from a StackWalker without the LOCALS_AND_OPERANDS
-     * option.
-     */
-    @DataProvider
-    public static StackFrame[][] noLocalsProvider() {
-        // Use default StackWalker
-        return new StackFrame[][] {
-            new Tester(StackWalker.getInstance(), true).testLocals()
-        };
-    }
-
-    /**
-     * Calls testLocals() and provides LiveStackFrames for *all* called methods,
-     * including test infrastructure (jtreg, testng, etc)
-     *
-     */
-    @DataProvider
-    public static StackFrame[][] unfilteredProvider() {
-        return new StackFrame[][] {
-            new Tester(extendedWalker, false).testLocals()
-        };
+    public static StackFrame[][] knownLocalsProvider() {
+        List<StackFrame[]> list = new ArrayList<>(3);
+        list.add(new KnownLocalsTester().testLocalsKeepAlive());
+        list.add(new KnownLocalsTester().testLocalsKeepAliveArgs(0xA, 'z',
+                "himom", 0x3FF00000000L + 0xFFFF, Math.PI));
+        if (testUnused) {
+            list.add(new KnownLocalsTester().testLocalsUnused());
+        }
+        return list.toArray(new StackFrame[1][1]);
     }
 
     /****************
@@ -128,135 +138,123 @@
      ****************/
 
     /**
-     * Check for expected local values and types in the LiveStackFrame
+     * Check for expected local values in the LiveStackFrame
      */
-    @Test(dataProvider = "keepAliveProvider")
+    @Test(dataProvider = "knownLocalsProvider")
     public static void checkLocalValues(StackFrame... frames) {
-        if (debug) {
-            System.out.println("Running checkLocalValues");
-            dumpStackWithLocals(frames);
-        }
-        Arrays.stream(frames).filter(f -> f.getMethodName()
-                                           .equals("testLocalsKeepAlive"))
-                                           .forEach(
-            f -> {
-                Object[] locals = invokeGetLocals(f);
-                for (int i = 0; i < locals.length; i++) {
-                    // Value
-                    String expected = Tester.LOCAL_VALUES[i];
-                    Object observed = locals[i];
-                    if (expected != null /* skip nulls in golden values */ &&
-                            !expected.equals(observed.toString())) {
-                        System.err.println("Local value mismatch:");
-                        if (!debug) { dumpStackWithLocals(frames); }
-                        throw new RuntimeException("local " + i + " value is " +
-                                observed + ", expected " + expected);
-                    }
-
-                    // Type
-                    expected = Tester.LOCAL_TYPES[i];
-                    observed = type(locals[i]);
-                    if (expected != null /* skip nulls in golden values */ &&
-                            !expected.equals(observed)) {
-                        System.err.println("Local type mismatch:");
-                        if (!debug) { dumpStackWithLocals(frames); }
-                        throw new RuntimeException("local " + i + " type is " +
-                                observed + ", expected " + expected);
-                    }
-                }
-            }
-        );
+        dumpFramesIfDebug(frames);
+        try {
+            Stream.of(frames)
+                  .filter(f -> KnownLocalsTester.TEST_METHODS.contains(f.getMethodName()))
+                  .forEach(LocalsAndOperands::checkFrameLocals);
+        } catch (Exception e) { dumpFramesIfNotDebug(frames); throw e; }
     }
 
     /**
-     * Basic sanity check for locals and operands
+     * Check the locals in the given StackFrame against the expected values.
      */
-    @Test(dataProvider = "provider")
-    public static void sanityCheck(StackFrame... frames) {
-        if (debug) {
-            System.out.println("Running sanityCheck");
-        }
-        try {
-            Stream<StackFrame> stream = Arrays.stream(frames);
-            if (debug) {
-                stream.forEach(LocalsAndOperands::printLocals);
+    private static void checkFrameLocals(StackFrame f) {
+        Object[] expectedArray = KnownLocalsTester.LOCAL_VALUES;
+        Object[] locals = invokeGetLocals(f);
+
+        for (int i = 0; i < locals.length; i++) {
+            Object expected = expectedArray[i];
+            Object observed = locals[i];
+
+            if (expected == null) { /* skip nulls in golden values */
+                continue;
+            } else if (expected instanceof KnownLocalsTester.TwoSlotValue) {
+                // confirm integrity of expected values
+                assertEquals(expectedArray[i+1], null,
+                        "Malformed array of expected values - slot after TwoSlotValue should be null");
+                assertLongIsInSlots(locals[i], locals[i+1],
+                        ((KnownLocalsTester.TwoSlotValue)expected).value);
+                i++; // skip following slot
+            } else if (primitiveSlotClass.isInstance(observed)) { // single slot primitive
+                assertTrue(primitiveValueEquals(observed, expected),
+                        "Local value mismatch: local " + i + " value is " +
+                          observed + ", expected " + expected);
+            } else if (expected instanceof Class) {
+                assertTrue(((Class)expected).isInstance(observed),
+                        "Local value mismatch: local " + i + " expected instancof " +
+                          expected + " but got " + observed);
+            } else if (expected instanceof String) {
+                assertEquals(expected, observed, "Local value mismatch: local " +
+                        i + " value is " + observed + ", expected " + expected);
             } else {
-                System.out.println(stream.count() + " frames");
+                throw new RuntimeException("Unrecognized expected local value " +
+                        i + ": " + expected);
             }
-        } catch (Throwable t) {
-            dumpStackWithLocals(frames);
-            throw t;
         }
     }
 
     /**
      * Sanity check for locals and operands, including testng/jtreg frames
+     * using all StackWalker options.
      */
-    @Test(dataProvider = "unfilteredProvider")
-    public static void unfilteredSanityCheck(StackFrame... frames) {
+    @Test
+    public synchronized void fullStackSanityCheck() throws Throwable {
         if (debug) {
-            System.out.println("Running unfilteredSanityCheck");
+            System.out.println("Running fullStackSanityCheck");
         }
-        try {
-            Stream<StackFrame> stream = Arrays.stream(frames);
+        StackWalker sw = (StackWalker) getExtendedWalker.invoke(null,
+                EnumSet.of(SHOW_HIDDEN_FRAMES, SHOW_REFLECT_FRAMES,
+                           RETAIN_CLASS_REFERENCE));
+        sw.forEach(f -> {
             if (debug) {
-                stream.forEach(f -> { System.out.println(f + ": " +
-                        invokeGetLocals(f).length + " locals"); } );
+                printLocals(f);
             } else {
-                System.out.println(stream.count() + " frames");
+                try {
+                    System.out.println("    " + f + ": " +
+                      ((Object[]) getLocals.invoke(f)).length + " locals, " +
+                      ((Object[]) getOperands.invoke(f)).length + " operands, " +
+                      ((Object[]) getMonitors.invoke(f)).length + " monitors");
+                } catch (IllegalAccessException|InvocationTargetException t) {
+                    throw new RuntimeException(t);
+                }
             }
-        } catch (Throwable t) {
-            dumpStackWithLocals(frames);
-            throw t;
-        }
+        });
     }
 
     /**
      * Test that LiveStackFrames are not provided with the default StackWalker
      * options.
      */
-    @Test(dataProvider = "noLocalsProvider")
-    public static void withoutLocalsAndOperands(StackFrame... frames) {
-        for (StackFrame frame : frames) {
-            if (liveStackFrameClass.isInstance(frame)) {
-                throw new RuntimeException("should not be LiveStackFrame");
-            }
-        }
+    @Test
+    public static void noLocalsSanityCheck() {
+        StackWalker sw = StackWalker.getInstance();
+        sw.forEach(f -> {
+            assertFalse(liveStackFrameClass.isInstance(f),
+                        "should not be LiveStackFrame");
+        });
     }
 
-    static class Tester {
+    /**
+     * Class stack-walking methods with a known set of methods and local variables.
+     */
+    static class KnownLocalsTester {
         private StackWalker walker;
-        private boolean filter = true; // Filter out testng/jtreg/etc frames?
 
-        Tester() {
+        KnownLocalsTester() {
             this.walker = extendedWalker;
         }
 
-        Tester(StackWalker walker, boolean filter) {
-            this.walker = walker;
-            this.filter = filter;
-        }
-
         /**
          * Perform stackwalk without keeping local variables alive and return an
          * array of the collected StackFrames
          */
-        private synchronized StackFrame[] testLocals() {
+        private synchronized StackFrame[] testLocalsUnused() {
             // Unused local variables will become dead
-            int x = 10;
-            char c = 'z';
+            int x = 0xA;
+            char c = 'z'; // 0x7A
             String hi = "himom";
-            long l = 1000000L;
-            double d =  3.1415926;
+            long l = 0x3FF00000000L + 0xFFFFL;
+            double d =  Math.PI;
 
-            if (filter) {
-                return walker.walk(s -> s.filter(f -> TEST_METHODS.contains(f
-                        .getMethodName())).collect(Collectors.toList()))
-                        .toArray(new StackFrame[0]);
-            } else {
-                return walker.walk(s -> s.collect(Collectors.toList()))
-                        .toArray(new StackFrame[0]);
-            }
+            return walker.walk(s ->
+                s.filter(f -> TEST_METHODS.contains(f.getMethodName()))
+                 .toArray(StackFrame[]::new)
+            );
         }
 
         /**
@@ -264,64 +262,153 @@
          * the collected StackFrames
          */
         private synchronized StackFrame[] testLocalsKeepAlive() {
-            int x = 10;
-            char c = 'z';
+            int x = 0xA;
+            char c = 'z'; // 0x7A
             String hi = "himom";
-            long l = 1000000L;
-            double d =  3.1415926;
+            long l = 0x3FF00000000L + 0xFFFFL;
+            double d =  Math.PI;
 
-            List<StackWalker.StackFrame> frames;
-            if (filter) {
-                frames = walker.walk(s -> s.filter(f -> TEST_METHODS.contains(f
-                        .getMethodName())).collect(Collectors.toList()));
-            } else {
-                frames = walker.walk(s -> s.collect(Collectors.toList()));
-            }
+            StackFrame[] frames = walker.walk(s ->
+                s.filter(f -> TEST_METHODS.contains(f.getMethodName()))
+                 .toArray(StackFrame[]::new)
+            );
 
             // Use local variables so they stay alive
-            System.out.println("Stayin' alive: "+x+" "+c+" "+hi+" "+l+" "+d);
-            return frames.toArray(new StackFrame[0]); // FIXME: convert to Array here
+            System.out.println("Stayin' alive: "+this+" "+x+" "+c+" "+hi+" "+l+" "+d);
+            return frames;
+        }
+
+        /**
+         * Perform stackwalk, keeping method arguments alive, and return a list of
+         * the collected StackFrames
+         */
+        private synchronized StackFrame[] testLocalsKeepAliveArgs(int x, char c,
+                                                                  String hi, long l,
+                                                                  double d) {
+            StackFrame[] frames = walker.walk(s ->
+                s.filter(f -> TEST_METHODS.contains(f.getMethodName()))
+                 .toArray(StackFrame[]::new)
+            );
+
+            // Use local variables so they stay alive
+            System.out.println("Stayin' alive: "+this+" "+x+" "+c+" "+hi+" "+l+" "+d);
+            return frames;
+        }
+
+        // An expected two-slot local (i.e. long or double)
+        static class TwoSlotValue {
+            public long value;
+            public TwoSlotValue(long value) { this.value = value; }
         }
 
-        // Expected values for locals in testLocals() & testLocalsKeepAlive()
-        // TODO: use real values instead of Strings, rebuild doubles & floats, etc
-        private final static String[] LOCAL_VALUES = new String[] {
-            null, // skip, LocalsAndOperands$Tester@XXX identity is different each run
-            "10",
-            "122",
+        // Expected values for locals in KnownLocalsTester.testLocals* methods
+        private final static Object[] LOCAL_VALUES = new Object[] {
+            LocalsAndOperands.KnownLocalsTester.class,
+            Integer.valueOf(0xA),
+            Integer.valueOf(0x7A),
             "himom",
-            "0",
-            null, // skip, fix in 8156073
-            null, // skip, fix in 8156073
-            null, // skip, fix in 8156073
-            "0"
+            new TwoSlotValue(0x3FF00000000L + 0xFFFFL),
+            null, // 2nd slot
+            new TwoSlotValue(Double.doubleToRawLongBits(Math.PI)),
+            null, // 2nd slot
+            Integer.valueOf(0)
         };
 
-        // Expected types for locals in testLocals() & testLocalsKeepAlive()
-        // TODO: use real types
-        private final static String[] LOCAL_TYPES = new String[] {
-            null, // skip
-            "I",
-            "I",
-            "java.lang.String",
-            "I",
-            "I",
-            "I",
-            "I",
-            "I"
-        };
+        private final static List<String> TEST_METHODS =
+                List.of("testLocalsUnused",
+                        "testLocalsKeepAlive",
+                        "testLocalsKeepAliveArgs");
+    }
+
+    /* Simpler tests of long & double arguments */
+
+    @Test
+    public static void testUsedLongArg() throws Exception {
+        usedLong(LOWER_LONG_VAL);
+        usedLong(UPPER_LONG_VAL);
+        usedLong(NEG_LONG_VAL);
+    }
+
+    private static void usedLong(long longArg) throws Exception {
+        StackFrame[] frames = extendedWalker.walk(s ->
+            s.filter(f -> "usedLong".equals(f.getMethodName()))
+             .toArray(StackFrame[]::new)
+        );
+        try {
+            dumpFramesIfDebug(frames);
+
+            Object[] locals = (Object[]) getLocals.invoke(frames[0]);
+            assertLongIsInSlots(locals[0], locals[1], longArg);
+            System.out.println("Stayin' alive: " + longArg);
+        } catch (Exception t) {
+            dumpFramesIfNotDebug(frames);
+            throw t;
+        }
+    }
+
+    @Test
+    public static void testUnusedLongArg() throws Exception {
+        if (testUnused) {
+            unusedLong(NEG_LONG_VAL);
+        }
+    }
 
-        final static Map NUM_LOCALS = Map.of("testLocals", 8,
-                                             "testLocalsKeepAlive",
-                                             LOCAL_VALUES.length);
-        private final static Collection<String> TEST_METHODS = NUM_LOCALS.keySet();
+    private static void unusedLong(long longArg) throws Exception {
+        StackFrame[] frames = extendedWalker.walk(s ->
+            s.filter(f -> "unusedLong".equals(f.getMethodName()))
+             .toArray(StackFrame[]::new)
+        );
+        try {
+            dumpFramesIfDebug(frames);
+
+            final Object[] locals = (Object[]) getLocals.invoke(frames[0]);
+            assertLongIsInSlots(locals[0], locals[1], NEG_LONG_VAL);
+        } catch (Exception t) {
+            dumpFramesIfNotDebug(frames);
+            throw t;
+        }
+    }
+
+    @Test
+    public static void testUsedDoubleArg() throws Exception {
+        usedDouble(LOWER_DOUBLE_VAL);
+        usedDouble(UPPER_DOUBLE_VAL);
     }
 
+    private static void usedDouble(double doubleArg) throws Exception {
+        StackFrame[] frames = extendedWalker.walk(s ->
+            s.filter(f -> "usedDouble".equals(f.getMethodName()))
+             .toArray(StackFrame[]::new)
+        );
+        try {
+            dumpFramesIfDebug(frames);
+
+            Object[] locals = (Object[]) getLocals.invoke(frames[0]);
+            assertDoubleIsInSlots(locals[0], locals[1], doubleArg);
+            System.out.println("Stayin' alive: " + doubleArg);
+        } catch (Exception t) {
+            dumpFramesIfNotDebug(frames);
+            throw t;
+        }
+    }
+
+    /*******************
+     * Utility Methods *
+     *******************/
+
     /**
      * Print stack trace with locals
      */
     public static void dumpStackWithLocals(StackFrame...frames) {
-        Arrays.stream(frames).forEach(LocalsAndOperands::printLocals);
+        Stream.of(frames).forEach(LocalsAndOperands::printLocals);
+    }
+
+    public static void dumpFramesIfDebug(StackFrame...frames) {
+        if (debug) { dumpStackWithLocals(frames); }
+    }
+
+    public static void dumpFramesIfNotDebug(StackFrame...frames) {
+        if (!debug) { dumpStackWithLocals(frames); }
     }
 
     /**
@@ -329,10 +416,21 @@
      */
     public static void printLocals(StackWalker.StackFrame frame) {
         try {
-            System.out.println(frame);
+            System.out.println("Locals for: " + frame);
             Object[] locals = (Object[]) getLocals.invoke(frame);
             for (int i = 0; i < locals.length; i++) {
-                System.out.format("  local %d: %s type %s\n", i, locals[i], type(locals[i]));
+                String localStr = null;
+
+                if (primitiveSlot64Class.isInstance(locals[i])) {
+                    localStr = String.format("0x%X",
+                            (Long)primitiveLongValue.invoke(locals[i]));
+                } else if (primitiveSlot32Class.isInstance(locals[i])) {
+                    localStr = String.format("0x%X",
+                            (Integer)primitiveIntValue.invoke(locals[i]));
+                } else if (locals[i] != null) {
+                    localStr = locals[i].toString();
+                }
+                System.out.format("  local %d: %s type %s\n", i, localStr, type(locals[i]));
             }
 
             Object[] operands = (Object[]) getOperands.invoke(frame);
@@ -352,12 +450,87 @@
         try {
             if (o == null) {
                 return "null";
-            } else if (primitiveValueClass.isInstance(o)) {
-                char c = (char)primitiveType.invoke(o);
-                return String.valueOf(c);
+            } else if (primitiveSlotClass.isInstance(o)) {
+                int s = (int)primitiveSize.invoke(o);
+                return s + "-byte primitive";
             } else {
                 return o.getClass().getName();
             }
         } catch(Exception e) { throw new RuntimeException(e); }
     }
+
+    /*
+     * Check if the PrimitiveValue "primVal" contains the specified value,
+     * either a Long or an Integer.
+     */
+    static boolean primitiveValueEquals(Object primVal, Object expectedVal) {
+        try {
+            if (expectedVal instanceof Long) {
+                assertFalse(is32bit);
+                assertTrue(primitiveSlot64Class.isInstance(primVal));
+                assertTrue(8 == (int)primitiveSize.invoke(primVal));
+                return Objects.equals(primitiveLongValue.invoke(primVal), expectedVal);
+            } else if (expectedVal instanceof Integer) {
+                int expectedInt = (Integer)expectedVal;
+                if (is32bit) {
+                    assertTrue(primitiveSlot32Class.isInstance(primVal),
+                            "expected a PrimitiveSlot32 on 32-bit VM");
+                    assertTrue(4 == (int)primitiveSize.invoke(primVal));
+                    return expectedInt == (int)primitiveIntValue.invoke(primVal);
+                } else {
+                    assertTrue(primitiveSlot64Class.isInstance(primVal),
+                            "expected a PrimitiveSlot64 on 64-bit VM");
+                    assertTrue(8 == (int)primitiveSize.invoke(primVal));
+                    // Look for int expectedVal in high- or low-order 32 bits
+                    long primValLong = (long)primitiveLongValue.invoke(primVal);
+                    return (int)(primValLong & 0x00000000FFFFFFFFL) == expectedInt ||
+                           (int)(primValLong >>> 32) == expectedInt;
+                }
+            } else {
+                throw new RuntimeException("Called with non-Integer/Long: " + expectedVal);
+            }
+        } catch (IllegalAccessException|InvocationTargetException e) {
+            throw new RuntimeException(e);
+        }
+
+    }
+
+    /*
+     * Assert that the expected 2-slot long value is stored somewhere in the
+     * pair of slots.
+     * Throw exception if long value isn't in the two slots given.
+     * Accounts for 32 vs 64 bit, but is lax on endianness (accepts either)
+     */
+    static void assertLongIsInSlots(Object primVal0, Object primVal1, long expected) {
+        try {
+            if (is32bit) {
+                int upper = (int)(expected & 0xFFFFFFFFL);
+                int lower = (int)(expected >> 32);
+
+                if (!((primitiveValueEquals(primVal0, upper) &&
+                       primitiveValueEquals(primVal1, lower)) ||
+                      (primitiveValueEquals(primVal0, lower) &&
+                       primitiveValueEquals(primVal1, upper)))) {
+                    throw new RuntimeException(String.format("0x%X and 0x%X of 0x%016X not found in 0x%X and 0x%X",
+                            upper, lower, expected,
+                            (int)primitiveIntValue.invoke(primVal0),
+                            (int)primitiveIntValue.invoke(primVal1)));
+                }
+            } else {
+                if (!(primitiveValueEquals(primVal0, expected) ||
+                      primitiveValueEquals(primVal1, expected))) {
+                    throw new RuntimeException(String.format("0x%016X not found in 0x%016X or 0x%016X",
+                            expected,
+                            (long)primitiveLongValue.invoke(primVal0),
+                            (long)primitiveLongValue.invoke(primVal1)));
+                }
+            }
+        } catch (IllegalAccessException|InvocationTargetException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    static void assertDoubleIsInSlots(Object primVal0, Object primVal1, double expected) {
+        assertLongIsInSlots(primVal0, primVal1, Double.doubleToRawLongBits(expected));
+    }
 }
--- a/jdk/test/java/lang/StackWalker/LocalsCrash.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,75 +0,0 @@
-/*
- * 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.
- */
-
-/*
- * @test
- * @bug 8147039
- * @summary Test for -Xcomp crash that happened before 8147039 fix
- * @modules java.base/java.lang:open
- * @run testng/othervm -Xcomp LocalsCrash
- */
-
-import org.testng.annotations.*;
-import java.lang.reflect.*;
-import java.util.List;
-import java.util.stream.Collectors;
-
-public class LocalsCrash {
-    static Class<?> liveStackFrameClass;
-    static Method getStackWalker;
-
-    static {
-        try {
-            liveStackFrameClass = Class.forName("java.lang.LiveStackFrame");
-            getStackWalker = liveStackFrameClass.getMethod("getStackWalker");
-            getStackWalker.setAccessible(true);
-        } catch (Throwable t) { throw new RuntimeException(t); }
-    }
-
-    private StackWalker walker;
-
-    LocalsCrash() {
-        try {
-            walker = (StackWalker) getStackWalker.invoke(null);
-        } catch (Exception e) { throw new RuntimeException(e); }
-    }
-
-    @Test
-    public void test00() { doStackWalk(); }
-
-    @Test
-    public void test01() { doStackWalk(); }
-
-    private synchronized List<StackWalker.StackFrame> doStackWalk() {
-        try {
-            // Unused local variables will become dead
-            int x = 10;
-            char c = 'z';
-            String hi = "himom";
-            long l = 1000000L;
-            double d =  3.1415926;
-
-            return walker.walk(s -> s.collect(Collectors.toList()));
-        } catch (Exception e) { throw new RuntimeException(e); }
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/StackWalker/ReflectionFrames.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,842 @@
+/*
+ * Copyright (c) 2017, 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 8173898
+ * @summary Basic test for checking filtering of reflection frames
+ * @run testng ReflectionFrames
+ */
+
+import java.lang.StackWalker.StackFrame;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.invoke.MethodType;
+import java.util.EnumSet;
+import java.util.List;
+import java.util.function.Supplier;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+import static java.lang.StackWalker.Option.*;
+
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+import static org.testng.Assert.*;
+
+public class ReflectionFrames {
+    final static boolean verbose = false;
+
+    /**
+     * This test invokes new StackInspector() directly from
+     * the caller StackInspector.Caller.create method.
+     * It checks that the caller is StackInspector.Caller.
+     * It also checks the expected frames collected
+     * by walking the stack from the default StackInspector()
+     * constructor.
+     * This is done twice, once using a default StackWalker
+     * that hides reflection frames, once using a StackWalker
+     * configured to show reflection frames.
+     */
+    @Test
+    public static void testNewStackInspector() throws Exception {
+        // Sets the default walker which hides reflection
+        // frames.
+        StackInspector.walker.set(StackInspector.walkerHide);
+
+        // Calls the StackInspector.create method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The create method invokes new StackInspector() directly.
+        // No reflection frame should appear.
+        System.out.println("testNewStackInspector: create");
+
+        StackInspector obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("create", How.class)
+                             .invoke(null, How.NEW));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             ReflectionFrames.class.getName()
+                                 +"::testNewStackInspector"));
+        assertEquals(obj.cls, StackInspector.Caller.class);
+        assertEquals(obj.filtered, 0);
+
+        // Calls the StackInspector.reflect method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The reflect method invokes the create method through
+        // reflection.
+        // The create method invokes new StackInspector() directly.
+        // No reflection frame should appear.
+        System.out.println("testNewStackInspector: reflect");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("reflect", How.class)
+                             .invoke(null, How.NEW));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             StackInspector.Caller.class.getName()
+                                 +"::reflect",
+                             ReflectionFrames.class.getName()
+                                 +"::testNewStackInspector"));
+        assertEquals(obj.cls, StackInspector.Caller.class);
+        assertEquals(obj.filtered, 0);
+
+        // Calls the StackInspector.handle method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The handle method invokes the create method using
+        // a MethodHandle.
+        // The create method invokes new StackInspector() directly.
+        // No reflection frame should appear.
+        System.out.println("testNewStackInspector: handle");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("handle", How.class)
+                             .invoke(null, How.NEW));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             StackInspector.Caller.class.getName()
+                                 +"::handle",
+                             ReflectionFrames.class.getName()
+                                 +"::testNewStackInspector"));
+        assertEquals(obj.cls, StackInspector.Caller.class);
+        assertEquals(obj.filtered, 0);
+
+        // Sets a non-default walker configured to show
+        // reflection frames
+        StackInspector.walker.set(StackInspector.walkerShow);
+
+        // Calls the StackInspector.create method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The create method invokes new StackInspector() directly.
+        // We should see all reflection frames, except the
+        // jdk.internal.reflect frames which we are filtering
+        // out in StackInspector::filter.
+        System.out.println("testNewStackInspector: create: show reflect");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("create", How.class)
+                             .invoke(null, How.NEW));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             Method.class.getName()
+                                 +"::invoke",
+                             ReflectionFrames.class.getName()
+                                 +"::testNewStackInspector"));
+        assertEquals(obj.cls, StackInspector.Caller.class);
+        assertNotEquals(obj.filtered, 0);
+
+        // Calls the StackInspector.reflect method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The reflect method invokes the create method through
+        // reflection.
+        // The create method invokes new StackInspector() directly.
+        // We should see all reflection frames, except the
+        // jdk.internal.reflect frames which we are filtering
+        // out in StackInspector::filter.
+        System.out.println("testNewStackInspector: reflect: show reflect");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("reflect", How.class)
+                             .invoke(null, How.NEW));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             Method.class.getName()
+                                 +"::invoke",
+                             StackInspector.Caller.class.getName()
+                                 +"::reflect",
+                             Method.class.getName()
+                                 +"::invoke",
+                             ReflectionFrames.class.getName()
+                                 +"::testNewStackInspector"));
+        assertEquals(obj.cls, StackInspector.Caller.class);
+        assertNotEquals(obj.filtered, 0);
+
+        // Calls the StackInspector.handle method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The handle method invokes the create method using
+        // MethodHandle.
+        // The create method invokes new StackInspector() directly.
+        // We should see all reflection frames, except the
+        // jdk.internal.reflect frames which we are filtering
+        // out in StackInspector::filter.
+        System.out.println("testNewStackInspector: handle: show reflect");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("handle", How.class)
+                             .invoke(null, How.NEW));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             // MethodHandle::invoke remains hidden
+                             StackInspector.Caller.class.getName()
+                                 +"::handle",
+                             Method.class.getName()
+                                 +"::invoke",
+                             ReflectionFrames.class.getName()
+                                 +"::testNewStackInspector"));
+        assertEquals(obj.cls, StackInspector.Caller.class);
+        assertNotEquals(obj.filtered, 0);
+    }
+
+   /**
+     * This test invokes Constructor.newInstance() from
+     * the caller StackInspector.Caller.create method.
+     * It checks that the caller is StackInspector.Caller.
+     * It also checks the expected frames collected
+     * by walking the stack from the default StackInspector()
+     * constructor.
+     * This is done twice, once using a default StackWalker
+     * that hides reflection frames, once using a StackWalker
+     * configured to show reflection frames.
+     */
+    @Test
+    public static void testConstructor() throws Exception {
+        // Sets the default walker which hides reflection
+        // frames.
+        StackInspector.walker.set(StackInspector.walkerHide);
+
+        // Calls the StackInspector.create method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The create method invokes Constructor.newInstance().
+        // No reflection frame should appear.
+        System.out.println("testConstructor: create");
+
+        StackInspector obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("create", How.class)
+                             .invoke(null, How.CONSTRUCTOR));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             ReflectionFrames.class.getName()
+                                 +"::testConstructor"));
+        assertEquals(obj.cls, StackInspector.Caller.class);
+        assertEquals(obj.filtered, 0);
+
+        // Calls the StackInspector.reflect method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The reflect method invokes the create method through
+        // reflection.
+        // The create method invokes Constructor.newInstance().
+        // No reflection frame should appear.
+        System.out.println("testConstructor: reflect");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("reflect", How.class)
+                             .invoke(null, How.CONSTRUCTOR));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             StackInspector.Caller.class.getName()
+                                 +"::reflect",
+                             ReflectionFrames.class.getName()
+                                 +"::testConstructor"));
+        assertEquals(obj.cls, StackInspector.Caller.class);
+        assertEquals(obj.filtered, 0);
+
+        // Calls the StackInspector.handle method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The handle method invokes the create method using
+        // MethodHandle.
+        // The create method invokes Constructor.newInstance().
+        // No reflection frame should appear.
+        System.out.println("testConstructor: handle");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("handle", How.class)
+                             .invoke(null, How.CONSTRUCTOR));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             StackInspector.Caller.class.getName()
+                                 +"::handle",
+                             ReflectionFrames.class.getName()
+                                 +"::testConstructor"));
+        assertEquals(obj.cls, StackInspector.Caller.class);
+        assertEquals(obj.filtered, 0);
+
+        // Sets a non-default walker configured to show
+        // reflection frames
+        StackInspector.walker.set(StackInspector.walkerShow);
+
+        // Calls the StackInspector.create method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The create method invokes Constructor.newInstance().
+        // We should see all reflection frames, except the
+        // jdk.internal.reflect frames which we are filtering
+        // out in StackInspector::filter.
+        System.out.println("testConstructor: create: show reflect");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("create", How.class)
+                             .invoke(null, How.CONSTRUCTOR));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             Constructor.class.getName()
+                                 +"::newInstance",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             Method.class.getName()
+                                 +"::invoke",
+                             ReflectionFrames.class.getName()
+                                 +"::testConstructor"));
+        assertEquals(obj.cls, StackInspector.Caller.class);
+        assertNotEquals(obj.filtered, 0);
+
+        // Calls the StackInspector.reflect method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The reflect method invokes the create method through
+        // reflection.
+        // The create method invokes Constructor.newInstance().
+        // We should see all reflection frames, except the
+        // jdk.internal.reflect frames which we are filtering
+        // out in StackInspector::filter.
+        System.out.println("testConstructor: reflect: show reflect");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("reflect", How.class)
+                             .invoke(null, How.CONSTRUCTOR));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             Constructor.class.getName()
+                                 +"::newInstance",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             Method.class.getName()
+                                 +"::invoke",
+                             StackInspector.Caller.class.getName()
+                                 +"::reflect",
+                             Method.class.getName()
+                                 +"::invoke",
+                             ReflectionFrames.class.getName()
+                                 +"::testConstructor"));
+        assertEquals(obj.cls, StackInspector.Caller.class);
+        assertNotEquals(obj.filtered, 0);
+
+        // Calls the StackInspector.handle method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The handle method invokes the create method using
+        // MethodHandle.
+        // The create method invokes Constructor.newInstance().
+        // We should see all reflection frames, except the
+        // jdk.internal.reflect frames which we are filtering
+        // out in StackInspector::filter.
+        System.out.println("testConstructor: handle: show reflect");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("handle", How.class)
+                             .invoke(null, How.CONSTRUCTOR));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             Constructor.class.getName()
+                                 +"::newInstance",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             // MethodHandle::invoke remains hidden
+                             StackInspector.Caller.class.getName()
+                                 +"::handle",
+                             Method.class.getName()
+                                 +"::invoke",
+                             ReflectionFrames.class.getName()
+                                 +"::testConstructor"));
+        assertEquals(obj.cls, StackInspector.Caller.class);
+        assertNotEquals(obj.filtered, 0);
+    }
+
+   /**
+     * This test invokes StackInspector.class.newInstance() from
+     * the caller StackInspector.Caller.create method. Because
+     * Class.newInstance() is not considered as a
+     * reflection frame, the the caller returned by
+     * getCallerClass() should appear to be java.lang.Class
+     * and not StackInspector.Caller.
+     * It also checks the expected frames collected
+     * by walking the stack from the default StackInspector()
+     * constructor.
+     * This is done twice, once using a default StackWalker
+     * that hides reflection frames, once using a StackWalker
+     * configured to show reflection frames.
+     */
+    @Test
+    public static void testNewInstance() throws Exception {
+        // Sets the default walker which hides reflection
+        // frames.
+        StackInspector.walker.set(StackInspector.walkerHide);
+
+        // Calls the StackInspector.create method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The create method invokes StackInspector.class.newInstance().
+        // No reflection frame should appear, except
+        // Class::newInstance which is not considered as
+        // a reflection frame.
+        System.out.println("testNewInstance: create");
+
+        StackInspector obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("create", How.class)
+                             .invoke(null, How.CLASS));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             Class.class.getName()
+                                 +"::newInstance",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             ReflectionFrames.class.getName()
+                                 +"::testNewInstance"));
+        // Because Class.newInstance is not filtered, then the
+        // caller is Class.class
+        assertEquals(obj.cls, Class.class);
+        assertEquals(obj.filtered, 0);
+
+        // Calls the StackInspector.reflect method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The reflect method invokes the create method through
+        // reflection.
+        // The create method invokes StackInspector.class.newInstance().
+        // No reflection frame should appear, except
+        // Class::newInstance which is not considered as
+        // a reflection frame.
+        System.out.println("testNewInstance: reflect");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("reflect", How.class)
+                             .invoke(null, How.CLASS));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             Class.class.getName()
+                                 +"::newInstance",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             StackInspector.Caller.class.getName()
+                                 +"::reflect",
+                             ReflectionFrames.class.getName()
+                                 +"::testNewInstance"));
+
+        // Because Class.newInstance is not filtered, then the
+        // caller is Class.class
+        assertEquals(obj.cls, Class.class);
+        assertEquals(obj.filtered, 0);
+
+        // Calls the StackInspector.handle method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The handle method invokes the create method using
+        // reflection.
+        // The create method invokes StackInspector.class.newInstance().
+        // No reflection frame should appear, except
+        // Class::newInstance which is not considered as
+        // a reflection frame.
+        System.out.println("testNewInstance: handle");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("handle", How.class)
+                             .invoke(null, How.CLASS));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             Class.class.getName()
+                                 +"::newInstance",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             StackInspector.Caller.class.getName()
+                                 +"::handle",
+                             ReflectionFrames.class.getName()
+                                 +"::testNewInstance"));
+
+        // Because Class.newInstance is not filtered, then the
+        // caller is Class.class
+        assertEquals(obj.cls, Class.class);
+        assertEquals(obj.filtered, 0);
+
+        // Sets a non-default walker configured to show
+        // reflection frames
+        StackInspector.walker.set(StackInspector.walkerShow);
+
+        // Calls the StackInspector.create method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The create method invokes StackInspector.class.newInstance().
+        // We should see all reflection frames, except the
+        // jdk.internal.reflect frames which we are filtering
+        // out in StackInspector::filter.
+        System.out.println("testNewInstance: create: show reflect");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("create", How.class)
+                             .invoke(null, How.CLASS));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             Constructor.class.getName()
+                                 +"::newInstance",
+                             Class.class.getName()
+                                 +"::newInstance",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             Method.class.getName()
+                                 +"::invoke",
+                             ReflectionFrames.class.getName()
+                                 +"::testNewInstance"));
+        // Because Class.newInstance is not filtered, then the
+        // caller is Class.class
+        assertEquals(obj.cls, Class.class);
+        assertNotEquals(obj.filtered, 0);
+
+        // Calls the StackInspector.reflect method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The reflect method invokes the create method through
+        // reflection.
+        // The create method invokes StackInspector.class.newInstance().
+        // We should see all reflection frames, except the
+        // jdk.internal.reflect frames which we are filtering
+        // out in StackInspector::filter.
+        System.out.println("testNewInstance: reflect: show reflect");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("reflect", How.class)
+                             .invoke(null, How.CLASS));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             Constructor.class.getName()
+                                 +"::newInstance",
+                             Class.class.getName()
+                                 +"::newInstance",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             Method.class.getName()
+                                 +"::invoke",
+                             StackInspector.Caller.class.getName()
+                                 +"::reflect",
+                             Method.class.getName()
+                                 +"::invoke",
+                             ReflectionFrames.class.getName()
+                                 +"::testNewInstance"));
+
+        // Because Class.newInstance is not filtered, then the
+        // caller is Class.class
+        assertEquals(obj.cls, Class.class);
+        assertNotEquals(obj.filtered, 0);
+
+        // Calls the StackInspector.handle method through reflection
+        // and check the frames collected in the StackInspector
+        // default constructor.
+        // The handle method invokes the create method using
+        // MethodHandle.
+        // The create method invokes StackInspector.class.newInstance().
+        // We should see all reflection frames, except the
+        // jdk.internal.reflect frames which we are filtering
+        // out in StackInspector::filter.
+        System.out.println("testNewInstance: handle: show reflect");
+
+        obj = ((StackInspector)StackInspector.Caller.class
+                             .getMethod("handle", How.class)
+                             .invoke(null, How.CLASS));
+        assertEquals(obj.collectedFrames,
+                     List.of(StackInspector.class.getName()
+                                 +"::<init>",
+                             Constructor.class.getName()
+                                 +"::newInstance",
+                             Class.class.getName()
+                                 +"::newInstance",
+                             StackInspector.Caller.class.getName()
+                                 +"::create",
+                             // MethodHandle::invoke remains hidden
+                             StackInspector.Caller.class.getName()
+                                 +"::handle",
+                             Method.class.getName()
+                                 +"::invoke",
+                             ReflectionFrames.class.getName()
+                                 +"::testNewInstance"));
+
+        // Because Class.newInstance is not filtered, then the
+        // caller is Class.class
+        assertEquals(obj.cls, Class.class);
+        assertNotEquals(obj.filtered, 0);
+    }
+
+    @Test
+    public static void testGetCaller() throws Exception {
+        // Sets the default walker which hides reflection
+        // frames.
+        StackInspector.walker.set(StackInspector.walkerHide);
+
+        assertEquals(StackInspector.getCaller(), ReflectionFrames.class);
+        assertEquals(StackInspector.class.getMethod("getCaller").invoke(null),
+                     ReflectionFrames.class);
+
+        // Sets a non-default walker configured to show
+        // reflection frames
+        StackInspector.walker.set(StackInspector.walkerShow);
+
+        assertEquals(StackInspector.getCaller(), ReflectionFrames.class);
+        assertEquals(StackInspector.class.getMethod("getCaller").invoke(null),
+                     ReflectionFrames.class);
+    }
+
+    @Test
+    public static void testReflectCaller() throws Exception {
+        // Sets the default walker which hides reflection
+        // frames.
+        StackInspector.walker.set(StackInspector.walkerHide);
+
+        assertEquals(StackInspector.reflectCaller(), ReflectionFrames.class);
+        assertEquals(StackInspector.class.getMethod("reflectCaller").invoke(null),
+                     ReflectionFrames.class);
+
+        // Sets a non-default walker configured to show
+        // reflection frames
+        StackInspector.walker.set(StackInspector.walkerShow);
+
+        assertEquals(StackInspector.reflectCaller(), ReflectionFrames.class);
+        assertEquals(StackInspector.class.getMethod("reflectCaller").invoke(null),
+                     ReflectionFrames.class);
+    }
+
+    @Test
+    public static void testSupplyCaller() throws Exception {
+        // Sets the default walker which hides reflection
+        // frames.
+        StackInspector.walker.set(StackInspector.walkerHide);
+
+        assertEquals(StackInspector.supplyCaller(), ReflectionFrames.class);
+        assertEquals(StackInspector.class.getMethod("supplyCaller").invoke(null),
+                     ReflectionFrames.class);
+
+        // Sets a non-default walker configured to show
+        // reflection frames
+        StackInspector.walker.set(StackInspector.walkerShow);
+
+        assertEquals(StackInspector.supplyCaller(), ReflectionFrames.class);
+        assertEquals(StackInspector.class.getMethod("supplyCaller").invoke(null),
+                     ReflectionFrames.class);
+    }
+
+    @Test
+    public static void testHandleCaller() throws Exception {
+        // Sets the default walker which hides reflection
+        // frames.
+        StackInspector.walker.set(StackInspector.walkerHide);
+
+        assertEquals(StackInspector.handleCaller(), ReflectionFrames.class);
+        assertEquals(StackInspector.class.getMethod("handleCaller").invoke(null),
+                     ReflectionFrames.class);
+
+        // Sets a non-default walker configured to show
+        // reflection frames
+        StackInspector.walker.set(StackInspector.walkerShow);
+
+        assertEquals(StackInspector.handleCaller(), ReflectionFrames.class);
+        assertEquals(StackInspector.class.getMethod("handleCaller").invoke(null),
+                     ReflectionFrames.class);
+    }
+
+    static enum How { NEW, CONSTRUCTOR, CLASS};
+
+    /**
+     * An object that collect stack frames by walking the stack
+     * (and calling getCallerClass()) from within its constructor.
+     * For the purpose of this test, StackInspector objects are
+     * always created from the nested StackInspector.Caller class,
+     * which should therefore appear as the caller of the
+     * StackInspector constructor.
+     */
+    static class StackInspector {
+        static final StackWalker walkerHide =
+            StackWalker.getInstance(StackWalker.Option.RETAIN_CLASS_REFERENCE);
+        static final StackWalker walkerShow =
+            StackWalker.getInstance(EnumSet.of(
+                           StackWalker.Option.RETAIN_CLASS_REFERENCE,
+                           StackWalker.Option.SHOW_REFLECT_FRAMES));
+        final static ThreadLocal<StackWalker> walker = new ThreadLocal<>() {
+             protected StackWalker initialValue() {
+                 return walkerHide;
+             }
+        };
+
+        List<String> collectedFrames;
+        Class<?> cls = null;
+        boolean stop;
+        int filtered;
+        final boolean filterImplFrames;
+
+        public StackInspector() {
+            stop = false;
+            // if reflection frames are not hidden, we want to
+            // filter implementation frames before collecting
+            // to avoid depending on internal details.
+            filterImplFrames = walker.get() == walkerShow;
+            collectedFrames = walker.get().walk(this::parse);
+            cls = walker.get().getCallerClass();
+        }
+
+        public List<String> collectedFrames() {
+            return collectedFrames;
+        }
+
+        // The takeWhile method arrange for stopping frame collection
+        // as soon as a frame from ReflectionFrames.class is reached.
+        // The first such frame encountered is still included in the
+        // collected frames, but collection stops right after.
+        // This makes it possible to filter out anything above the
+        // the test method frame, such as frames from the test
+        // framework.
+        public boolean takeWhile(StackFrame f) {
+            if (stop) return false;
+            if (verbose) System.out.println("    " + f);
+            stop = stop || f.getDeclaringClass() == ReflectionFrames.class;
+            return true;
+        }
+
+        // filter out implementation frames to avoid depending
+        // on implementation details. If present, Class::newInstance,
+        // Method::invoke and Constructor::newInstance will
+        // still appear in the collected frames, which is
+        // sufficient for the purpose of the test.
+        // In the case where the StackWalker itself is supposed to
+        // filter the reflection frames, then this filter will always
+        // return true. This way, if such a reflection frame appears when
+        // it sjould have been filtered by StackWalker, it will make the
+        // test fail.
+        public boolean filter(StackFrame f) {
+            if (filterImplFrames &&
+                f.getClassName().startsWith("jdk.internal.reflect.")) {
+                filtered++;
+                return false;
+            }
+            if (!verbose) System.out.println("    " + f);
+            return true;
+        }
+
+        public String frame(StackFrame f) {
+            return f.getClassName() + "::" + f.getMethodName();
+        }
+
+        List<String> parse(Stream<StackFrame> s) {
+            return s.takeWhile(this::takeWhile)
+                    .filter(this::filter)
+                    .map(this::frame)
+                    .collect(Collectors.toList());
+        }
+
+        /**
+         * The Caller class is used to create instances of
+         * StackInspector, either direcltly, or throug reflection.
+         */
+        public static class Caller {
+            public static StackInspector create(How how) throws Exception {
+                switch(how) {
+                    case NEW: return new StackInspector();
+                    case CONSTRUCTOR: return StackInspector.class
+                        .getConstructor().newInstance();
+                    case CLASS: return StackInspector.class.newInstance();
+                    default: throw new AssertionError(String.valueOf(how));
+                }
+            }
+            public static StackInspector reflect(How how) throws Exception {
+                return (StackInspector) Caller.class.getMethod("create", How.class)
+                      .invoke(null, how);
+            }
+            public static StackInspector handle(How how) throws Exception {
+                Lookup lookup = MethodHandles.lookup();
+                MethodHandle mh = lookup.findStatic(Caller.class, "create",
+                        MethodType.methodType(StackInspector.class, How.class));
+                try {
+                    return (StackInspector) mh.invoke(how);
+                } catch (Error | Exception x) {
+                    throw x;
+                } catch(Throwable t) {
+                    throw new AssertionError(t);
+                }
+            }
+        }
+
+        public static Class<?> getCaller() throws Exception {
+            return walker.get().getCallerClass();
+        }
+
+        public static Class<?> reflectCaller() throws Exception {
+            return (Class<?>)StackWalker.class.getMethod("getCallerClass")
+                .invoke(walker.get());
+        }
+
+        public static Class<?> supplyCaller() throws Exception {
+            return ((Supplier<Class<?>>)StackInspector.walker.get()::getCallerClass).get();
+        }
+
+        public static Class<?> handleCaller() throws Exception {
+            Lookup lookup = MethodHandles.lookup();
+            MethodHandle mh = lookup.findVirtual(StackWalker.class, "getCallerClass",
+                    MethodType.methodType(Class.class));
+            try {
+                return (Class<?>) mh.invoke(walker.get());
+            } catch (Error | Exception x) {
+                throw x;
+            } catch(Throwable t) {
+                throw new AssertionError(t);
+            }
+        }
+    }
+}
--- a/jdk/test/java/lang/invoke/AccessControlTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/invoke/AccessControlTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -118,6 +118,8 @@
                 suffix = "/noaccess";
             else if (lookupModes == PUBLIC)
                 suffix = "/public";
+             else if (lookupModes == (PUBLIC|UNCONDITIONAL))
+                suffix = "/publicLookup";
             else if (lookupModes == (PUBLIC|MODULE))
                 suffix = "/module";
             else if (lookupModes == (PUBLIC|MODULE|PACKAGE))
@@ -140,23 +142,24 @@
          * [A2] However, the resulting {@code Lookup} object is guaranteed
          * to have no more access capabilities than the original.
          * In particular, access capabilities can be lost as follows:<ul>
-         * <li>[A3] If the new lookup class differs from the old one,
-         * protected members will not be accessible by virtue of inheritance.
+         * <li> [A3] If the old lookup class is in a named module, and the new
+         * lookup class is in a different module {@code M}, then no members, not
+         * even public members in {@code M}'s exported packages, will be accessible.
+         * The exception to this is when this lookup is publicLookup, in which case
+         * public access is not lost.
+         * <li> [A4] If the old lookup class is in an unnamed module, and the new
+         * lookup class is a different module then module access is lost.
+         * <li> [A5] If the new lookup class differs from the old one then UNCONDITIONAL
+         * is lost. If the new lookup class is not within the same package member as the
+         * old one, protected members will not be accessible by virtue of inheritance.
          * (Protected members may continue to be accessible because of package sharing.)
-         * <li>[A4] If the new lookup class is in a different package
-         * than the old one, protected and default (package) members will not be accessible.
-         * <li>[A5] If the new lookup class is not within the same package member
+         * <li> [A6] If the new lookup class is in a different package than the old one,
+         * protected and default (package) members will not be accessible.
+         * <li> [A7] If the new lookup class is not within the same package member
          * as the old one, private members will not be accessible.
-         * <li>[A6] If the new lookup class is not accessible to the old lookup class,
-         * using the original access modes,
+         * <li> [A8] If the new lookup class is not accessible to the old lookup class,
          * then no members, not even public members, will be accessible.
-         * <li>[A7] If the new lookup class for this {@code Lookup} is in the unnamed module,
-         * and the new lookup class is in a named module {@code M}, then no members in
-         * {@code M}'s non-exported packages will be accessible.
-         * <li>[A8] If the lookup for this {@code Lookup} is in a named module, and the
-         * new lookup class is in a different module, then no members, not even
-         * public members in {@code M}'s exported packages, will be accessible.
-         * [A8] (In all other cases, public members will continue to be accessible.)
+         * <li> [A9] (In all other cases, public members will continue to be accessible.)
          * </ul>
          * Other than the above cases, the new lookup will have the same
          * access capabilities as the original. [A10]
@@ -171,36 +174,35 @@
             boolean sameModule = (c1.getModule() == c2.getModule()) ||
                                  (!c1.getModule().isNamed() && !c2.getModule().isNamed());
             boolean samePackage = (c1.getClassLoader() == c2.getClassLoader() &&
-                                   packagePrefix(c1).equals(packagePrefix(c2)));
+                                   c1.getPackageName().equals(c2.getPackageName()));
             boolean sameTopLevel = (topLevelClass(c1) == topLevelClass(c2));
             boolean sameClass = (c1 == c2);
             assert(samePackage  || !sameTopLevel);
             assert(sameTopLevel || !sameClass);
-            boolean accessible = sameClass;  // [A6]
+            boolean accessible = sameClass;
             if ((m1 & PACKAGE) != 0)  accessible |= samePackage;
             if ((m1 & PUBLIC ) != 0)  accessible |= (c2.getModifiers() & PUBLIC) != 0;
             if (!sameModule) {
-                if (c1.getModule().isNamed()) {
-                    accessible = false;  // [A8]
+                if (c1.getModule().isNamed() && (m1 & UNCONDITIONAL) == 0) {
+                    accessible = false;  // [A3]
                 } else {
-                    // Different module; loose MODULE and lower access.
-                    changed |= (MODULE|PACKAGE|PRIVATE|PROTECTED);  // [A7]
+                    changed |= (MODULE|PACKAGE|PRIVATE|PROTECTED);    // [A3] [A4]
                 }
             }
             if (!accessible) {
                 // Different package and no access to c2; lose all access.
-                changed |= (PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED);  // [A6]
+                changed |= (PUBLIC|MODULE|PACKAGE|PRIVATE|PROTECTED);  // [A8]
             }
             if (!samePackage) {
                 // Different package; loose PACKAGE and lower access.
-                changed |= (PACKAGE|PRIVATE|PROTECTED);  // [A4]
+                changed |= (PACKAGE|PRIVATE|PROTECTED);  // [A6]
             }
             if (!sameTopLevel) {
-                // Different top-level class.  Lose PRIVATE and lower access.
-                changed |= (PRIVATE|PROTECTED);  // [A5]
+                // Different top-level class.  Lose PRIVATE and PROTECTED access.
+                changed |= (PRIVATE|PROTECTED);  // [A5] [A7]
             }
             if (!sameClass) {
-                changed |= (PROTECTED);     // [A3]
+                changed |= (UNCONDITIONAL);     // [A5]
             } else {
                 assert(changed == 0);       // [A10] (no deprivation if same class)
             }
@@ -228,11 +230,10 @@
             Class<?> c1 = lookupClass();
             Class<?> c2 = m.getDeclaringClass();
 
-            // if the lookup class is in a loose module with PUBLIC access then
-            // public members of public types in all unnamed modules can be accessed
-            if (isLooseModule(c1.getModule())
+            // publicLookup has access to all public types/members of types in unnamed modules
+            if ((lookupModes & UNCONDITIONAL) != 0
                 && (lookupModes & PUBLIC) != 0
-                && (!c2.getModule().isNamed())
+                && !c2.getModule().isNamed()
                 && Modifier.isPublic(c2.getModifiers())
                 && Modifier.isPublic(m.getModifiers()))
                 return true;
@@ -261,17 +262,12 @@
             if (load && c2.getClassLoader() != null) {
                 if (c1.getClassLoader() == null) {
                     // not visible
-                return false;
-            }
-                if (c1 == publicLookup().lookupClass()) {
-                    // not visible as lookup class is defined by child of the boot loader
                     return false;
                 }
             }
 
-            // if the lookup class is in a loose module with PUBLIC access then
-            // public types in all unnamed modules can be accessed
-            if (isLooseModule(c1.getModule())
+            // publicLookup has access to all public types/members of types in unnamed modules
+            if ((lookupModes & UNCONDITIONAL) != 0
                 && (lookupModes & PUBLIC) != 0
                 && (!c2.getModule().isNamed())
                 && Modifier.isPublic(c2.getModifiers()))
@@ -295,11 +291,6 @@
             }
             return r;
         }
-
-        private boolean isLooseModule(Module m) {
-            ClassLoader cl = new ClassLoader() { };
-            return m.canRead(cl.getUnnamedModule());
-        }
     }
 
     private static Class<?> topLevelClass(Class<?> cls) {
@@ -311,14 +302,6 @@
         return c;
     }
 
-    private static String packagePrefix(Class<?> c) {
-        while (c.isArray())  c = c.getComponentType();
-        String s = c.getName();
-        assert(s.indexOf('/') < 0);
-        return s.substring(0, s.lastIndexOf('.')+1);
-    }
-
-
     private final TreeSet<LookupCase> CASES = new TreeSet<>();
     private final TreeMap<LookupCase,TreeSet<LookupCase>> CASE_EDGES = new TreeMap<>();
     private final ArrayList<ClassLoader> LOADERS = new ArrayList<>();
--- a/jdk/test/java/lang/invoke/DropLookupModeTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/invoke/DropLookupModeTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -65,6 +65,10 @@
         lookup = fullPowerLookup.dropLookupMode(PUBLIC);
         assertTrue(lookup.lookupClass() == lc);
         assertTrue(lookup.lookupModes() == 0);
+
+        lookup = fullPowerLookup.dropLookupMode(UNCONDITIONAL);
+        assertTrue(lookup.lookupClass() == lc);
+        assertTrue(lookup.lookupModes() == (PUBLIC|MODULE|PACKAGE|PRIVATE));
     }
 
     /**
@@ -108,7 +112,7 @@
     public void testPublicLookup() {
         final Lookup publicLookup = MethodHandles.publicLookup();
         final Class<?> lc = publicLookup.lookupClass();
-        assertTrue(publicLookup.lookupModes() == PUBLIC);
+        assertTrue(publicLookup.lookupModes() == (PUBLIC|UNCONDITIONAL));
 
         Lookup lookup = publicLookup.dropLookupMode(PRIVATE);
         assertTrue(lookup.lookupClass() == lc);
@@ -129,6 +133,10 @@
         lookup = publicLookup.dropLookupMode(PUBLIC);
         assertTrue(lookup.lookupClass() == lc);
         assertTrue(lookup.lookupModes() == 0);
+
+        lookup = publicLookup.dropLookupMode(UNCONDITIONAL);
+        assertTrue(lookup.lookupClass() == lc);
+        assertTrue(lookup.lookupModes() == PUBLIC);
     }
 
     @DataProvider(name = "badInput")
--- a/jdk/test/java/lang/invoke/LFCaching/LFGarbageCollectedTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/invoke/LFCaching/LFGarbageCollectedTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -82,9 +82,9 @@
                 throw new Error("Unexpected error: Lambda form of the method handle is null");
             }
 
-            String debugName = (String)DEBUG_NAME.get(lambdaForm);
-            if (debugName != null && debugName.startsWith("identity_")) {
-                // Ignore identity_* LambdaForms.
+            String kind = KIND_FIELD.get(lambdaForm).toString();
+            if (kind.equals("IDENTITY")) {
+                // Ignore identity LambdaForms.
                 return;
             }
 
--- a/jdk/test/java/lang/invoke/LFCaching/LFMultiThreadCachingTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/invoke/LFCaching/LFMultiThreadCachingTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -30,7 +30,7 @@
  * @library /lib/testlibrary/jsr292 /lib/testlibrary
  * @modules java.base/java.lang.invoke:open
  *          java.base/java.lang.ref:open
- *          jdk.management
+ *          java.management
  * @build TestMethods
  * @build LambdaFormTestCase
  * @build LFCachingTestCase
--- a/jdk/test/java/lang/invoke/LFCaching/LFSingleThreadCachingTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/invoke/LFCaching/LFSingleThreadCachingTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -30,6 +30,7 @@
  * @library /lib/testlibrary/jsr292 /lib/testlibrary
  * @modules java.base/java.lang.ref:open
  *          java.base/java.lang.invoke:open
+ *          java.management
  * @build TestMethods
  * @build LambdaFormTestCase
  * @build LFCachingTestCase
--- a/jdk/test/java/lang/invoke/LFCaching/LambdaFormTestCase.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/invoke/LFCaching/LambdaFormTestCase.java	Thu Mar 16 20:47:03 2017 +0000
@@ -51,7 +51,7 @@
      * used to get a lambda form from a method handle.
      */
     protected static final Method INTERNAL_FORM;
-    protected static final Field DEBUG_NAME;
+    protected static final Field KIND_FIELD;
     protected static final Field REF_FIELD;
     private static final List<GarbageCollectorMXBean> gcInfo;
 
@@ -64,8 +64,8 @@
             INTERNAL_FORM = MethodHandle.class.getDeclaredMethod("internalForm");
             INTERNAL_FORM.setAccessible(true);
 
-            DEBUG_NAME = Class.forName("java.lang.invoke.LambdaForm").getDeclaredField("debugName");
-            DEBUG_NAME.setAccessible(true);
+            KIND_FIELD = Class.forName("java.lang.invoke.LambdaForm").getDeclaredField("kind");
+            KIND_FIELD.setAccessible(true);
 
             REF_FIELD = Reference.class.getDeclaredField("referent");
             REF_FIELD.setAccessible(true);
--- a/jdk/test/java/lang/invoke/MethodHandles/privateLookupIn/Driver.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/invoke/MethodHandles/privateLookupIn/Driver.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,7 +23,7 @@
 
 /**
  * @test
- * @build test/* m1/* m2/* m3/*
+ * @build test/* m1/* m2/* m3/* Unnamed
  * @run testng/othervm test/p.PrivateLookupInTests
  * @summary Unit tests for MethodHandles.privateLookupIn
  */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/MethodHandles/privateLookupIn/Unnamed.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+
+public class Unnamed { }
--- a/jdk/test/java/lang/invoke/MethodHandles/privateLookupIn/test/p/PrivateLookupInTests.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/invoke/MethodHandles/privateLookupIn/test/p/PrivateLookupInTests.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -126,6 +126,26 @@
         Object obj = mh.invokeExact();
     }
 
+    // test target class in unnamed module
+    public void testTargetClassInUnnamedModule() throws Throwable {
+        Class<?> clazz = Class.forName("Unnamed");
+        assertFalse(clazz.getModule().isNamed());
+
+        // thisModule does not read the unnamed module
+        Module thisModule = getClass().getModule();
+        assertFalse(thisModule.canRead(clazz.getModule()));
+        try {
+            MethodHandles.privateLookupIn(clazz, MethodHandles.lookup());
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+        // thisModule reads the unnamed module
+        thisModule.addReads(clazz.getModule());
+        Lookup lookup = MethodHandles.privateLookupIn(clazz, MethodHandles.lookup());
+        assertTrue(lookup.lookupClass() == clazz);
+        assertTrue(lookup.hasPrivateAccess());
+    }
+
     // test does not read m2, m2 opens p2 to test
     @Test(expectedExceptions = {IllegalAccessException.class})
     public void testCallerDoesNotRead() throws Throwable {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/lambda/InheritedMethodTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,85 @@
+/*
+ * Copyright (c) 2017, 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 8174399
+ * @summary LambdaMetafactory should be able to handle inherited methods as 'implMethod'
+ */
+import java.lang.ReflectiveOperationException;
+import java.lang.invoke.*;
+
+public class InheritedMethodTest {
+
+    public static MethodType mt(Class<?> ret, Class<?>... params) { return MethodType.methodType(ret, params); }
+
+    public interface StringFactory {
+        String get();
+    }
+
+    public interface I {
+        String iString();
+    }
+
+    public interface J extends I {}
+
+    public static abstract class C implements I {}
+
+    public static class D extends C implements J {
+        public String toString() { return "a"; }
+        public String iString() { return "b"; }
+    }
+
+    private static final MethodHandles.Lookup lookup = MethodHandles.lookup();
+
+    public static void main(String... args) throws Throwable {
+        test(lookup.findVirtual(C.class, "toString", mt(String.class)), "a");
+        test(lookup.findVirtual(C.class, "iString", mt(String.class)), "b");
+        test(lookup.findVirtual(J.class, "toString", mt(String.class)), "a");
+        test(lookup.findVirtual(J.class, "iString", mt(String.class)), "b");
+        test(lookup.findVirtual(I.class, "toString", mt(String.class)), "a");
+        test(lookup.findVirtual(I.class, "iString", mt(String.class)), "b");
+    }
+
+    static void test(MethodHandle implMethod, String expected) throws Throwable {
+        testMetafactory(implMethod, expected);
+        testAltMetafactory(implMethod, expected);
+    }
+
+    static void testMetafactory(MethodHandle implMethod, String expected) throws Throwable {
+        CallSite cs = LambdaMetafactory.metafactory(lookup, "get", mt(StringFactory.class, D.class), mt(String.class),
+                                                    implMethod, mt(String.class));
+        StringFactory factory = (StringFactory) cs.dynamicInvoker().invokeExact(new D());
+        String actual = factory.get();
+        if (!expected.equals(actual)) throw new AssertionError("Unexpected result: " + actual);
+    }
+
+    static void testAltMetafactory(MethodHandle implMethod, String expected) throws Throwable {
+        CallSite cs = LambdaMetafactory.altMetafactory(lookup, "get", mt(StringFactory.class, D.class), mt(String.class),
+                                                       implMethod, mt(String.class), LambdaMetafactory.FLAG_SERIALIZABLE);
+        StringFactory factory = (StringFactory) cs.dynamicInvoker().invokeExact(new D());
+        String actual = factory.get();
+        if (!expected.equals(actual)) throw new AssertionError("Unexpected result: " + actual);
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/lambda/MetafactoryDescriptorTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,269 @@
+/*
+ * Copyright (c) 2017, 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 8035776 8173587
+ * @summary metafactory should fail if instantiatedMethodType does not match sam/bridge descriptors
+ */
+import java.lang.invoke.*;
+import java.util.*;
+
+public class MetafactoryDescriptorTest {
+
+    static final MethodHandles.Lookup lookup = MethodHandles.lookup();
+
+    static MethodType mt(Class<?> ret, Class<?>... params) {
+        return MethodType.methodType(ret, params);
+    }
+
+    public interface I {}
+
+    public static class C {
+        public static void m_void(String arg) {}
+        public static boolean m_boolean(String arg) { return true; }
+        public static char m_char(String arg) { return 'x'; }
+        public static byte m_byte(String arg) { return 12; }
+        public static short m_short(String arg) { return 12; }
+        public static int m_int(String arg) { return 12; }
+        public static long m_long(String arg) { return 12; }
+        public static float m_float(String arg) { return 12; }
+        public static double m_double(String arg) { return 12; }
+        public static String m_String(String arg) { return ""; }
+        public static Integer m_Integer(String arg) { return 23; }
+        public static Object m_Object(String arg) { return new Object(); }
+
+        public static String n_boolean(boolean arg) { return ""; }
+        public static String n_char(char arg) { return ""; }
+        public static String n_byte(byte arg) { return ""; }
+        public static String n_short(short arg) { return ""; }
+        public static String n_int(int arg) { return ""; }
+        public static String n_long(long arg) { return ""; }
+        public static String n_float(float arg) { return ""; }
+        public static String n_double(double arg) { return ""; }
+        public static String n_String(String arg) { return ""; }
+        public static String n_Integer(Integer arg) { return ""; }
+        public static String n_Object(Object arg) { return ""; }
+
+        public static MethodHandle getM(Class<?> c) {
+            try {
+                return lookup.findStatic(C.class, "m_" + c.getSimpleName(), mt(c, String.class));
+            }
+            catch (NoSuchMethodException | IllegalAccessException e) {
+                throw new RuntimeException(e);
+            }
+        }
+
+        public static MethodHandle getN(Class<?> c) {
+            if (c == void.class) return null;
+            try {
+                return lookup.findStatic(C.class, "n_" + c.getSimpleName(), mt(String.class, c));
+            }
+            catch (NoSuchMethodException | IllegalAccessException e) {
+                throw new RuntimeException(e);
+            }
+        }
+
+    }
+
+    public static void main(String... args) {
+        Class<?>[] t = { void.class, boolean.class, char.class,
+                         byte.class, short.class, int.class, long.class, float.class, double.class,
+                         String.class, Integer.class, Object.class };
+
+        for (int i = 0; i < t.length; i++) {
+            MethodHandle m = C.getM(t[i]);
+            MethodHandle n = C.getN(t[i]); // null for void.class
+            for (int j = 0; j < t.length; j++) {
+                boolean correctRet = t[j].isAssignableFrom(t[i]) || conversions.contains(t[i], t[j]);
+                test(correctRet, m, mt(t[i], String.class), mt(t[j], String.class));
+                testBridge(correctRet, m, mt(t[i], String.class), mt(t[i], String.class),
+                           mt(t[j], Object.class));
+                testBridge(correctRet, m, mt(t[i], String.class), mt(t[i], String.class),
+                           mt(t[i], CharSequence.class), mt(t[j], Object.class));
+
+                if (t[i] != void.class && t[j] != void.class) {
+                    boolean correctParam = t[j].isAssignableFrom(t[i]);
+                    test(correctParam, n, mt(String.class, t[i]), mt(String.class, t[j]));
+                    testBridge(correctParam, n, mt(String.class, t[i]), mt(String.class, t[i]),
+                            mt(Object.class, t[j]));
+                    testBridge(correctParam, n, mt(String.class, t[i]), mt(String.class, t[i]),
+                            mt(CharSequence.class, t[i]), mt(Object.class, t[j]));
+                }
+
+            }
+        }
+    }
+
+    static void test(boolean correct, MethodHandle mh, MethodType instMT, MethodType samMT) {
+        tryMetafactory(correct, mh, instMT, samMT);
+        tryAltMetafactory(correct, mh, instMT, samMT);
+    }
+
+    static void testBridge(boolean correct, MethodHandle mh, MethodType instMT, MethodType samMT, MethodType... bridgeMTs) {
+        tryAltMetafactory(correct, mh, instMT, samMT, bridgeMTs);
+    }
+
+    static void tryMetafactory(boolean correct, MethodHandle mh, MethodType instMT, MethodType samMT) {
+        try {
+            LambdaMetafactory.metafactory(lookup, "run", mt(I.class),
+                                          samMT, mh, instMT);
+            if (!correct) {
+                throw new AssertionError("Unexpected linkage without error:" +
+                                         " impl=" + mh +
+                                         ", inst=" + instMT +
+                                         ", sam=" + samMT);
+            }
+        }
+        catch (LambdaConversionException e) {
+            if (correct) {
+                throw new AssertionError("Unexpected linkage error:" +
+                                         " e=" + e +
+                                         ", impl=" + mh +
+                                         ", inst=" + instMT +
+                                         ", sam=" + samMT);
+            }
+        }
+    }
+
+    static void tryAltMetafactory(boolean correct, MethodHandle mh, MethodType instMT, MethodType samMT,
+                                  MethodType... bridgeMTs) {
+        boolean bridge = bridgeMTs.length > 0;
+        Object[] args = new Object[bridge ? 5+bridgeMTs.length : 4];
+        args[0] = samMT;
+        args[1] = mh;
+        args[2] = instMT;
+        args[3] = bridge ? LambdaMetafactory.FLAG_BRIDGES : 0;
+        if (bridge) {
+            args[4] = bridgeMTs.length;
+            for (int i = 0; i < bridgeMTs.length; i++) args[5+i] = bridgeMTs[i];
+        }
+        try {
+            LambdaMetafactory.altMetafactory(lookup, "run", mt(I.class), args);
+            if (!correct) {
+                throw new AssertionError("Unexpected linkage without error:" +
+                                         " impl=" + mh +
+                                         ", inst=" + instMT +
+                                         ", sam=" + samMT +
+                                         ", bridges=" + Arrays.toString(bridgeMTs));
+            }
+        }
+        catch (LambdaConversionException e) {
+            if (correct) {
+                throw new AssertionError("Unexpected linkage error:" +
+                                         " e=" + e +
+                                         ", impl=" + mh +
+                                         ", inst=" + instMT +
+                                         ", sam=" + samMT +
+                                         ", bridges=" + Arrays.toString(bridgeMTs));
+            }
+        }
+    }
+
+    private static class ConversionTable {
+        private final Map<Class<?>, Set<Class<?>>> pairs = new HashMap<>();
+
+        public void put(Class<?> from, Class<?> to) {
+            Set<Class<?>> set = pairs.computeIfAbsent(from, f -> new HashSet<>());
+            set.add(to);
+        }
+
+        public boolean contains(Class<?> from, Class<?> to) {
+            return pairs.containsKey(from) && pairs.get(from).contains(to);
+        }
+    }
+
+    private static ConversionTable conversions = new ConversionTable();
+    static {
+        conversions.put(char.class, int.class);
+        conversions.put(char.class, long.class);
+        conversions.put(char.class, float.class);
+        conversions.put(char.class, double.class);
+        conversions.put(char.class, Character.class);
+        conversions.put(char.class, Object.class);
+        conversions.put(Character.class, char.class);
+        conversions.put(Character.class, int.class);
+        conversions.put(Character.class, long.class);
+        conversions.put(Character.class, float.class);
+        conversions.put(Character.class, double.class);
+
+        conversions.put(byte.class, short.class);
+        conversions.put(byte.class, int.class);
+        conversions.put(byte.class, long.class);
+        conversions.put(byte.class, float.class);
+        conversions.put(byte.class, double.class);
+        conversions.put(byte.class, Byte.class);
+        conversions.put(byte.class, Object.class);
+        conversions.put(Byte.class, byte.class);
+        conversions.put(Byte.class, short.class);
+        conversions.put(Byte.class, int.class);
+        conversions.put(Byte.class, long.class);
+        conversions.put(Byte.class, float.class);
+        conversions.put(Byte.class, double.class);
+
+        conversions.put(short.class, int.class);
+        conversions.put(short.class, long.class);
+        conversions.put(short.class, float.class);
+        conversions.put(short.class, double.class);
+        conversions.put(short.class, Short.class);
+        conversions.put(short.class, Object.class);
+        conversions.put(Short.class, short.class);
+        conversions.put(Short.class, int.class);
+        conversions.put(Short.class, long.class);
+        conversions.put(Short.class, float.class);
+        conversions.put(Short.class, double.class);
+
+        conversions.put(int.class, long.class);
+        conversions.put(int.class, float.class);
+        conversions.put(int.class, double.class);
+        conversions.put(int.class, Integer.class);
+        conversions.put(int.class, Object.class);
+        conversions.put(Integer.class, int.class);
+        conversions.put(Integer.class, long.class);
+        conversions.put(Integer.class, float.class);
+        conversions.put(Integer.class, double.class);
+
+        conversions.put(long.class, float.class);
+        conversions.put(long.class, double.class);
+        conversions.put(long.class, Long.class);
+        conversions.put(long.class, Object.class);
+        conversions.put(Long.class, long.class);
+        conversions.put(Long.class, float.class);
+        conversions.put(Long.class, double.class);
+
+        conversions.put(float.class, double.class);
+        conversions.put(float.class, Float.class);
+        conversions.put(float.class, Object.class);
+        conversions.put(Float.class, float.class);
+        conversions.put(Float.class, double.class);
+
+        conversions.put(double.class, Double.class);
+        conversions.put(double.class, Object.class);
+        conversions.put(Double.class, double.class);
+
+        conversions.put(boolean.class, Boolean.class);
+        conversions.put(boolean.class, Object.class);
+        conversions.put(Boolean.class, boolean.class);
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/lambda/MetafactoryMethodNameTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,197 @@
+/*
+ * Copyright (c) 2017, 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 8173587
+ * @summary metafactory should fail if the method name is not legal
+ */
+import java.lang.invoke.*;
+import java.util.*;
+
+public class MetafactoryMethodNameTest {
+
+    public static void main(String... args) {
+        goodName("x");
+        goodName("xy");
+
+        goodName("]");
+        goodName("x]");
+        goodName("]y");
+        goodName("x]y");
+
+        goodName("&");
+        goodName("x&");
+        goodName("&y");
+        goodName("x&y");
+
+        badName(".");
+        badName("x.");
+        badName(".y");
+        badName("x.y");
+
+        badName(";");
+        badName("x;");
+        badName(";y");
+        badName("x;y");
+
+        badName("[");
+        badName("x[");
+        badName("[y");
+        badName("x[y");
+
+        badName("/");
+        badName("x/");
+        badName("/y");
+        badName("x/y");
+
+        badName("<");
+        badName("x<");
+        badName("<y");
+        badName("x<y");
+
+        badName(">");
+        badName("x>");
+        badName(">y");
+        badName("x>y");
+
+        badName("");
+        badName("<init>");
+        badName("<clinit>");
+    }
+
+    static MethodType mt(Class<?> ret, Class<?>... params) {
+        return MethodType.methodType(ret, params);
+    }
+
+    static MethodHandle smh(Class<?> c, String name, MethodType desc) {
+        try {
+            return MethodHandles.lookup().findStatic(c, name, desc);
+        } catch (ReflectiveOperationException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    static Object[] arr(Object... args) {
+        return args;
+    }
+
+    public static class C {
+        public static void m() {}
+    }
+
+    public interface I {}
+
+    private static MethodHandles.Lookup lookup = MethodHandles.lookup();
+    private static MethodType toI = mt(I.class);
+    private static MethodType toVoid = mt(void.class);
+    private static MethodHandle mh = smh(C.class, "m", toVoid);
+    private static Class<?> lce = LambdaConversionException.class;
+
+    static void goodName(String name) {
+        succeedMFLinkage(lookup, name, toI, toVoid, mh, toVoid);
+        succeedAltMFLinkage(lookup, name, toI, arr(toVoid, mh, toVoid, LambdaMetafactory.FLAG_SERIALIZABLE));
+    }
+
+    static void badName(String name) {
+        failMFLinkage(lookup, name, toI, toVoid, mh, toVoid, lce);
+        failAltMFLinkage(lookup, name, toI, arr(toVoid, mh, toVoid, LambdaMetafactory.FLAG_SERIALIZABLE), lce);
+    }
+
+    static CallSite succeedMFLinkage(MethodHandles.Lookup lookup,
+                                    String name,
+                                    MethodType capType,
+                                    MethodType desc,
+                                    MethodHandle impl,
+                                    MethodType checked) {
+        try {
+            return LambdaMetafactory.metafactory(lookup, name, capType, desc, impl, checked);
+        } catch (Throwable t) {
+            String msg = String.format("Unexpected exception during linkage for metafactory(%s, %s, %s, %s, %s, %s)",
+                    lookup, name, capType, desc, impl, checked);
+            throw new AssertionError(msg, t);
+        }
+    }
+
+    static void failMFLinkage(MethodHandles.Lookup lookup,
+                              String name,
+                              MethodType capType,
+                              MethodType desc,
+                              MethodHandle impl,
+                              MethodType checked,
+                              Class<?> expectedExceptionType) {
+        try {
+            LambdaMetafactory.metafactory(lookup, name, capType, desc, impl, checked);
+        } catch (Throwable t) {
+            if (expectedExceptionType.isInstance(t)) {
+                return;
+            } else {
+                String msg = String.format("Unexpected exception: expected %s during linkage for metafactory(%s, %s, %s, %s, %s, %s)",
+                        expectedExceptionType.getName(),
+                        lookup, name, capType, desc, impl, checked);
+                throw new AssertionError(msg, t);
+            }
+        }
+        String msg = String.format("Unexpected success: expected %s during linkage for metafactory(%s, %s, %s, %s, %s, %s)",
+                expectedExceptionType.getName(),
+                lookup, name, capType, desc, impl, checked);
+        throw new AssertionError(msg);
+    }
+
+    static CallSite succeedAltMFLinkage(MethodHandles.Lookup lookup,
+                                        String name,
+                                        MethodType capType,
+                                        Object[] args) {
+        try {
+            return LambdaMetafactory.altMetafactory(lookup, name, capType, args);
+        } catch (Throwable t) {
+            String msg = String.format("Unexpected exception during linkage for metafactory(%s, %s, %s, %s)",
+                    lookup, name, capType, Arrays.asList(args));
+            throw new AssertionError(msg, t);
+        }
+    }
+
+    static void failAltMFLinkage(MethodHandles.Lookup lookup,
+                                 String name,
+                                 MethodType capType,
+                                 Object[] args,
+                                 Class<?> expectedExceptionType) {
+        try {
+            LambdaMetafactory.altMetafactory(lookup, name, capType, args);
+        } catch (Throwable t) {
+            if (expectedExceptionType.isInstance(t)) {
+                return;
+            } else {
+                String msg = String.format("Unexpected exception: expected %s during linkage for metafactory(%s, %s, %s, %s)",
+                        expectedExceptionType.getName(),
+                        lookup, name, capType, Arrays.asList(args));
+                throw new AssertionError(msg, t);
+            }
+        }
+        String msg = String.format("Unexpected success: expected %s during linkage for metafactory(%s, %s, %s, %s)",
+                expectedExceptionType.getName(),
+                lookup, name, capType, Arrays.asList(args));
+        throw new AssertionError(msg);
+    }
+
+}
--- a/jdk/test/java/lang/invoke/lambda/MetafactorySamReturnTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,167 +0,0 @@
-/*
- * Copyright (c) 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
- * 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 8035776
- * @summary metafactory should fail if impl return does not match sam/bridge returns
- */
-import java.lang.invoke.*;
-import java.util.Arrays;
-import static java.lang.invoke.MethodType.methodType;
-
-public class MetafactorySamReturnTest {
-
-    static final MethodHandles.Lookup lookup = MethodHandles.lookup();
-
-    public interface I {}
-
-    public static class C {
-        public static void m_void(String arg) {}
-        public static boolean m_boolean(String arg) { return true; }
-        public static char m_char(String arg) { return 'x'; }
-        public static byte m_byte(String arg) { return 12; }
-        public static short m_short(String arg) { return 12; }
-        public static int m_int(String arg) { return 12; }
-        public static long m_long(String arg) { return 12; }
-        public static float m_float(String arg) { return 12; }
-        public static double m_double(String arg) { return 12; }
-        public static String m_String(String arg) { return ""; }
-        public static Integer m_Integer(String arg) { return 23; }
-        public static Object m_Object(String arg) { return new Object(); }
-
-        public static MethodHandle getMH(Class<?> c) {
-            try {
-                return lookup.findStatic(C.class, "m_" + c.getSimpleName(), methodType(c, String.class));
-            }
-            catch (NoSuchMethodException | IllegalAccessException e) {
-                throw new RuntimeException(e);
-            }
-        }
-    }
-
-    public static void main(String... args) {
-        Class<?>[] t = { void.class, boolean.class, char.class,
-                         byte.class, short.class, int.class, long.class, float.class, double.class,
-                         String.class, Integer.class, Object.class };
-
-        for (int i = 0; i < t.length; i++) {
-            MethodHandle mh = C.getMH(t[i]);
-            for (int j = 0; j < t.length; j++) {
-                // TEMPORARY EXCEPTIONS
-                if (t[j] == void.class) continue;
-                if (t[i].isPrimitive() && t[j] == Object.class) continue;
-                if (t[i] == char.class && (t[j] == int.class || t[j] == long.class || t[j] == float.class || t[j] == double.class)) continue;
-                if (t[i] == byte.class && (t[j] == short.class || t[j] == int.class || t[j] == long.class || t[j] == float.class || t[j] == double.class)) continue;
-                if (t[i] == short.class && (t[j] == int.class || t[j] == long.class || t[j] == float.class || t[j] == double.class)) continue;
-                if (t[i] == int.class && (t[j] == long.class || t[j] == float.class || t[j] == double.class)) continue;
-                if (t[i] == long.class && (t[j] == float.class || t[j] == double.class)) continue;
-                if (t[i] == float.class && t[j] == double.class) continue;
-                if (t[i] == int.class && t[j] == Integer.class) continue;
-                if (t[i] == Integer.class && (t[j] == int.class || t[j] == long.class || t[j] == float.class || t[j] == double.class)) continue;
-                // END TEMPORARY EXCEPTIONS
-                boolean correct = (t[i].isPrimitive() || t[j].isPrimitive())
-                                  ? t[i] == t[j]
-                                  : t[j].isAssignableFrom(t[i]);
-                MethodType mti = methodType(t[i], String.class);
-                MethodType mtiCS = methodType(t[i], CharSequence.class);
-                MethodType mtj = methodType(t[j], String.class);
-                MethodType mtjObj = methodType(t[j], Object.class);
-                test(correct, mh, mti, mtj);
-                testBridge(correct, mh, mti, mti, mtjObj);
-                testBridge(correct, mh, mti, mti, mtiCS, mtjObj);
-            }
-        }
-    }
-
-    static void test(boolean correct, MethodHandle mh, MethodType instMT, MethodType samMT) {
-        tryMetafactory(correct, mh, new Class<?>[]{}, instMT, samMT);
-        tryAltMetafactory(correct, mh, new Class<?>[]{}, instMT, samMT);
-    }
-
-    static void testBridge(boolean correct, MethodHandle mh, MethodType instMT, MethodType samMT, MethodType... bridgeMTs) {
-        tryAltMetafactory(correct, mh, new Class<?>[]{}, instMT, samMT, bridgeMTs);
-    }
-
-    static void tryMetafactory(boolean correct, MethodHandle mh, Class<?>[] captured,
-                               MethodType instMT, MethodType samMT) {
-        try {
-            LambdaMetafactory.metafactory(lookup, "run", methodType(I.class, captured),
-                                          samMT, mh, instMT);
-            if (!correct) {
-                throw new AssertionError("Uncaught linkage error:" +
-                                         " impl=" + mh +
-                                         ", captured=" + Arrays.toString(captured) +
-                                         ", inst=" + instMT +
-                                         ", sam=" + samMT);
-            }
-        }
-        catch (LambdaConversionException e) {
-            if (correct) {
-                throw new AssertionError("Unexpected linkage error:" +
-                                         " e=" + e +
-                                         ", impl=" + mh +
-                                         ", captured=" + Arrays.toString(captured) +
-                                         ", inst=" + instMT +
-                                         ", sam=" + samMT);
-            }
-        }
-    }
-
-    static void tryAltMetafactory(boolean correct, MethodHandle mh, Class<?>[] captured,
-                                  MethodType instMT, MethodType samMT, MethodType... bridgeMTs) {
-        boolean bridge = bridgeMTs.length > 0;
-        Object[] args = new Object[bridge ? 5+bridgeMTs.length : 4];
-        args[0] = samMT;
-        args[1] = mh;
-        args[2] = instMT;
-        args[3] = bridge ? LambdaMetafactory.FLAG_BRIDGES : 0;
-        if (bridge) {
-            args[4] = bridgeMTs.length;
-            for (int i = 0; i < bridgeMTs.length; i++) args[5+i] = bridgeMTs[i];
-        }
-        try {
-            LambdaMetafactory.altMetafactory(lookup, "run", methodType(I.class, captured), args);
-            if (!correct) {
-                throw new AssertionError("Uncaught linkage error:" +
-                                         " impl=" + mh +
-                                         ", captured=" + Arrays.toString(captured) +
-                                         ", inst=" + instMT +
-                                         ", sam=" + samMT +
-                                         ", bridges=" + Arrays.toString(bridgeMTs));
-            }
-        }
-        catch (LambdaConversionException e) {
-            if (correct) {
-                throw new AssertionError("Unexpected linkage error:" +
-                                         " e=" + e +
-                                         ", impl=" + mh +
-                                         ", captured=" + Arrays.toString(captured) +
-                                         ", inst=" + instMT +
-                                         ", sam=" + samMT +
-                                         ", bridges=" + Arrays.toString(bridgeMTs));
-            }
-        }
-    }
-
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/modules/Driver.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2017, 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
+ * @build m1/* m2/* Unnamed
+ * @run testng/othervm m1/p1.Main
+ * @summary Basic test case for module access checks and Lookup.in.
+ */
--- a/jdk/test/java/lang/invoke/modules/ModuleAccessControlTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,81 +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.
- */
-
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.Arrays;
-import java.util.List;
-
-import static jdk.testlibrary.ProcessTools.executeTestJava;
-
-import org.testng.annotations.BeforeTest;
-import org.testng.annotations.Test;
-import static org.testng.Assert.*;
-
-/**
- * @test
- * @library /lib/testlibrary
- * @modules jdk.compiler
- * @build CompilerUtils jdk.testlibrary.*
- * @run testng ModuleAccessControlTest
- * @summary Driver for testing module access checking by MethodHandles.Lookup
- */
-
-public class ModuleAccessControlTest {
-
-    private static final String TEST_SRC = System.getProperty("test.src");
-
-    private static final Path SRC_DIR = Paths.get(TEST_SRC, "src");
-    private static final Path MODS_DIR = Paths.get("mods");
-
-    // the names of the modules in this test
-    private static List<String> modules = Arrays.asList("m1", "m2");
-
-
-    /**
-     * Compiles all modules used by the test
-     */
-    @BeforeTest
-    public void compileAll() throws Exception {
-        for (String mn : modules) {
-            Path msrc = SRC_DIR.resolve(mn);
-            assertTrue(CompilerUtils
-                .compile(msrc, MODS_DIR, "--module-source-path", SRC_DIR.toString()));
-        }
-    }
-
-    /**
-     * Launch the test
-     */
-    @Test
-    public void runTest() throws Exception {
-        int exitValue = executeTestJava("--module-path", MODS_DIR.toString(),
-                                        "-m", "m1/p1.Main")
-                .outputTo(System.out)
-                .errorTo(System.out)
-                .getExitValue();
-
-        assertTrue(exitValue == 0);
-    }
-
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/modules/Unnamed.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+
+public class Unnamed { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/modules/m1/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 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
+ * 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.
+ */
+module m1 {
+    requires m2;
+    requires testng;
+    exports p1;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/modules/m1/p1/Main.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,367 @@
+/*
+ * Copyright (c) 2015, 2017, 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 p1;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodHandles.Lookup;
+import java.lang.invoke.MethodType;
+import java.lang.reflect.Layer;
+import java.lang.reflect.Module;
+
+import static java.lang.invoke.MethodHandles.Lookup.*;
+
+import org.testng.annotations.BeforeTest;
+import org.testng.annotations.Test;
+import static org.testng.Assert.*;
+
+/**
+ * Basic test case for module access checks and Lookup.in.
+ */
+
+@Test
+public class Main {
+
+    private Class<?> p1_Type1;        // m1, exported
+    private Class<?> p2_Type2;        // m1, not exported
+    private Class<?> q1_Type1;        // m2, exported
+    private Class<?> q2_Type2;        // m2, not exported
+    private Class<?> x500NameClass;   // java.base, not exported
+    private Class<?> unnamedClass;    // class in unnamed module
+
+    @BeforeTest
+    public void setup() throws Exception {
+        try {
+            p1_Type1 = Class.forName("p1.Type1");
+            p2_Type2 = Class.forName("p2.Type2");
+            q1_Type1 = Class.forName("q1.Type1");
+            q2_Type2 = Class.forName("q2.Type2");
+            x500NameClass = Class.forName("sun.security.x509.X500Name");
+            unnamedClass = Class.forName("Unnamed");
+        } catch (ClassNotFoundException e) {
+            throw new AssertionError(e);
+        }
+
+        // check setup
+        Module m1 = Layer.boot().findModule("m1").orElse(null);
+        assertNotNull(m1);
+        assertTrue(p1_Type1.getModule() == m1);
+        assertTrue(p2_Type2.getModule() == m1);
+        assertTrue(m1.isExported("p1"));
+        assertFalse(m1.isExported("p2"));
+
+        Module m2 = Layer.boot().findModule("m2").orElse(null);
+        assertNotNull(m2);
+        assertTrue(q1_Type1.getModule() == m2);
+        assertTrue(q2_Type2.getModule() == m2);
+        assertTrue(m2.isExported("q1"));
+        assertFalse(m2.isExported("q2"));
+
+        Module unnamedModule = unnamedClass.getModule();
+        assertFalse(unnamedModule.isNamed());
+
+        // m1 needs to read unnamed module
+        Main.class.getModule().addReads(unnamedModule);
+    }
+
+    /**
+     * MethodHandles.lookup()
+     *
+     * [A0] has module access
+     * [A1] can access all public types in m1
+     * [A2] can access public types in packages exported by modules that m1 reads
+     * [A3] cannot access public types in non-exported modules of modules that m1 reads
+     */
+    public void testLookup() throws Exception {
+        Lookup lookup = MethodHandles.lookup();
+        assertTrue((lookup.lookupModes() & MODULE) == MODULE); // [A0]
+
+        // m1
+        findConstructor(lookup, p1_Type1, void.class); // [A1]
+        findConstructor(lookup, p2_Type2, void.class); // [A1]
+
+        // m2
+        findConstructor(lookup, q1_Type1, void.class); // [A2]
+        findConstructorExpectingIAE(lookup, q2_Type2, void.class); // [A3]
+
+        // java.base
+        findConstructor(lookup, Object.class, void.class); // [A2]
+        findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class); // [A3]
+
+        // unnamed
+        findConstructor(lookup, unnamedClass, void.class);  // [A3]
+    }
+
+    /**
+     * Hop to lookup class in the same module
+     *
+     * [A0] module and public access is not lost
+     */
+    public void testToSameModule() throws Exception {
+        Lookup lookup = MethodHandles.lookup().in(p2_Type2);
+        assertTrue(lookup.lookupModes() == (MODULE|PUBLIC)); // [A0]
+
+        // m1
+        findConstructor(lookup, p1_Type1, void.class);
+        findConstructor(lookup, p2_Type2, void.class);
+
+        // m2
+        findConstructor(lookup, q1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, q2_Type2, void.class);
+
+        // java.base
+        findConstructor(lookup, Object.class, void.class);
+        findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class);
+
+        // unnamed
+        findConstructor(lookup, unnamedClass, void.class);
+    }
+
+    /**
+     * Hop to lookup class in another named module
+     *
+     * [A0] has no access
+     */
+    public void testFromNamedToNamedModule() throws Exception {
+        Lookup lookup = MethodHandles.lookup().in(q1_Type1);
+        assertTrue(lookup.lookupModes() == 0); // [A0]
+
+        // m1
+        findConstructorExpectingIAE(lookup, p1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, p2_Type2, void.class);
+
+        // m2
+        findConstructorExpectingIAE(lookup, q1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, q2_Type2, void.class);
+
+        // java.base
+        findConstructorExpectingIAE(lookup, Object.class, void.class);
+        findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class);
+
+        // unnamed
+        findConstructorExpectingIAE(lookup, unnamedClass, void.class);
+    }
+
+    /**
+     * Hop to lookup class in an unnamed module
+     *
+     * [A0] has no access
+     */
+    public void testFromNamedToUnnamedModule() throws Exception {
+        Lookup lookup = MethodHandles.lookup().in(unnamedClass);
+        assertTrue(lookup.lookupModes() == 0); // [A0]
+
+        // m1
+        findConstructorExpectingIAE(lookup, p1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, p2_Type2, void.class);
+
+        // m2
+        findConstructorExpectingIAE(lookup, q1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, q2_Type2, void.class);
+
+        // java.base
+        findConstructorExpectingIAE(lookup, Object.class, void.class);
+        findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class);
+
+        // unnamed
+        findConstructorExpectingIAE(lookup, unnamedClass, void.class);
+    }
+
+    /**
+     * Hop from unnamed to named module.
+     *
+     * [A0] retains PUBLIC access
+     */
+    public void testFromUnnamedToNamedModule() throws Exception {
+        Lookup lookup = MethodHandles.lookup();
+        lookup = MethodHandles.privateLookupIn(unnamedClass, lookup).in(p1_Type1);
+        assertTrue(lookup.lookupModes() == PUBLIC); // A0
+
+        // m1
+        findConstructor(lookup, p1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, p2_Type2, void.class);
+
+        // m2
+        findConstructor(lookup, q1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, q2_Type2, void.class);
+
+        // java.base
+        findConstructor(lookup, Object.class, void.class);
+        findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class);
+
+        // unnamed
+        findConstructor(lookup, unnamedClass, void.class);
+    }
+
+    /**
+     * MethodHandles.publicLookup()
+     *
+     * [A0] has PUBLIC|UNCONDITIONAL access
+     */
+    public void testPublicLookup() throws Exception {
+        Lookup lookup = MethodHandles.publicLookup();
+        assertTrue(lookup.lookupModes() == (PUBLIC|UNCONDITIONAL)); // A0
+
+        // m1
+        findConstructor(lookup, p1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, p2_Type2, void.class);
+
+        // m2
+        findConstructor(lookup, q1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, q2_Type2, void.class);
+
+        // java.base
+        findConstructor(lookup, Object.class, void.class);
+        findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class);
+
+        // unnamed
+        findConstructor(lookup, unnamedClass, void.class);
+    }
+
+    /**
+     * Hop from publicLookup to accessible type in java.base
+     */
+    public void testPublicLookupToBaseModule() throws Exception {
+        Lookup lookup = MethodHandles.publicLookup().in(String.class);
+        assertTrue(lookup.lookupModes() == PUBLIC); // A0
+
+        // m1
+        findConstructorExpectingIAE(lookup, p1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, p2_Type2, void.class);
+
+        // m2
+        findConstructorExpectingIAE(lookup, q1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, q2_Type2, void.class);
+
+        // java.base
+        findConstructor(lookup, Object.class, void.class);
+        findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class);
+
+        // unnamed
+        findConstructorExpectingIAE(lookup, unnamedClass, void.class);
+    }
+
+
+    /**
+     * Hop from publicLookup to accessible type in named module.
+     *
+     * [A0] has PUBLIC access
+     */
+    public void testPublicLookupToAccessibleTypeInNamedModule() throws Exception {
+        Lookup lookup = MethodHandles.publicLookup().in(p1_Type1);
+        assertTrue(lookup.lookupModes() == PUBLIC); // A0
+
+        // m1
+        findConstructor(lookup, p1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, p2_Type2, void.class);
+
+        // m2
+        findConstructor(lookup, q1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, q2_Type2, void.class);
+
+        // java.base
+        findConstructor(lookup, Object.class, void.class);
+        findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class);
+
+        // unnamed
+        findConstructor(lookup, unnamedClass, void.class);
+    }
+
+    /**
+     * Teleport from publicLookup to inaccessible type in named module.
+     *
+     * [A0] has no access
+     */
+    public void testPublicLookupToInaccessibleTypeInNamedModule() throws Exception {
+        Lookup lookup = MethodHandles.publicLookup().in(p2_Type2);
+        assertTrue(lookup.lookupModes() == 0); // A0
+
+        // m1
+        findConstructorExpectingIAE(lookup, p1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, p2_Type2, void.class);
+
+        // m2
+        findConstructorExpectingIAE(lookup, q1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, q2_Type2, void.class);
+
+        // java.base
+        findConstructorExpectingIAE(lookup, Object.class, void.class);
+        findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class);
+
+        // unnamed
+        findConstructorExpectingIAE(lookup, unnamedClass, void.class);
+    }
+
+    /**
+     * Teleport from publicLookup to public type in unnamed module
+     *
+     * [A0] has PUBLIC access
+     */
+    public void testPublicLookupToUnnamedModule() throws Exception {
+        Lookup lookup = MethodHandles.publicLookup().in(unnamedClass);
+        assertTrue(lookup.lookupModes() == PUBLIC); // A0
+
+        // m1
+        findConstructor(lookup, p1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, p2_Type2, void.class);
+
+        // m2
+        findConstructor(lookup, q1_Type1, void.class);
+        findConstructorExpectingIAE(lookup, q2_Type2, void.class);
+
+        // java.base
+        findConstructor(lookup, Object.class, void.class);
+        findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class);
+
+        // unnamed
+        findConstructor(lookup, unnamedClass, void.class);
+    }
+
+    /**
+     * Invokes Lookup findConstructor with a method type constructored from the
+     * given return and parameter types, expecting IllegalAccessException to be
+     * thrown.
+     */
+    static void findConstructorExpectingIAE(Lookup lookup,
+                                            Class<?> clazz,
+                                            Class<?> rtype,
+                                            Class<?>... ptypes) throws Exception {
+        try {
+            findConstructor(lookup, clazz, rtype, ptypes);
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+    }
+
+    /**
+     * Invokes Lookup findConstructor with a method type constructored from the
+     * given return and parameter types.
+     */
+    static MethodHandle findConstructor(Lookup lookup,
+                                        Class<?> clazz,
+                                        Class<?> rtype,
+                                        Class<?>... ptypes) throws Exception {
+        MethodType mt = MethodType.methodType(rtype, ptypes);
+        return lookup.findConstructor(clazz, mt);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/modules/m1/p1/Type1.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 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
+ * 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 p1;
+
+public class Type1 {
+    public Type1() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/modules/m1/p2/Type2.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 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
+ * 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 p2;
+
+public class Type2 {
+    public Type2() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/modules/m2/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 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
+ * 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.
+ */
+module m2 {
+    exports q1;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/modules/m2/q1/Type1.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 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
+ * 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 q1;
+
+public class Type1 {
+    public Type1() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/invoke/modules/m2/q2/Type2.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 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
+ * 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 q2;
+
+public class Type2 {
+    public Type2() { }
+}
--- a/jdk/test/java/lang/invoke/modules/src/m1/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,26 +0,0 @@
-/*
- * Copyright (c) 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
- * 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.
- */
-module m1 {
-    requires m2;
-    exports p1;
-}
--- a/jdk/test/java/lang/invoke/modules/src/m1/p1/Main.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,225 +0,0 @@
-/*
- * Copyright (c) 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
- * 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 p1;
-
-import java.lang.invoke.MethodHandle;
-import java.lang.invoke.MethodHandles;
-import java.lang.invoke.MethodHandles.Lookup;
-import java.lang.invoke.MethodType;
-
-/**
- * Basic test case for module access check, supplements AccessControlTest.
- *
- * The tests consists of two modules:
- *
- * module m1 { requires m2; exports p1; }
- * module m2 { exports q1; }
- *
- * Both modules read java.base (as every module reads java.base)
- *
- * module m1 has public types in packages p1 and p2, p2 is not exported.
- * module m2 has public types in packages q1 and q2, q2 is not exported.
- */
-
-public class Main {
-
-    static final int MODULE = Lookup.MODULE;
-
-    // Use Class.forName to get classes for test because some
-    // are not accessible at compile-time
-
-    static final Class<?> p1_Type1;        // m1, exported
-    static final Class<?> p2_Type2;        // m1, not exported
-    static final Class<?> q1_Type1;        // m2, exported, m1 reads m2
-    static final Class<?> q2_Type2;        // m2, not exported, m1 reads m2
-    static final Class<?> x500NameClass;   // java.base, not exported
-
-    static {
-        try {
-            p1_Type1 = Class.forName("p1.Type1");
-            p2_Type2 = Class.forName("p2.Type2");
-            q1_Type1 = Class.forName("q1.Type1");
-            q2_Type2 = Class.forName("q2.Type2");
-            x500NameClass = Class.forName("sun.security.x509.X500Name");
-        } catch (ClassNotFoundException e) {
-            throw new AssertionError(e);
-        }
-    }
-
-    public static void main(String[] args) throws Exception {
-        Lookup lookup, lookup2;
-
-        /**
-         * MethodHandles.lookup()
-         * has module access [A0]
-         * can access all public types in m1 [A1]
-         * can access public types in packages exported by modules that m1 reads [A2]
-         * cannot access public types in non-exported modules of modules that m1 reads [A3]
-         */
-        lookup = MethodHandles.lookup();
-        assertTrue((lookup.lookupModes() & MODULE) == MODULE); // [A0]
-        findConstructor(lookup, p1_Type1, void.class); // [A1]
-        findConstructor(lookup, p2_Type2, void.class); // [A1]
-        findConstructor(lookup, q1_Type1, void.class); // [A2]
-        findConstructorExpectingIAE(lookup, q2_Type2, void.class); // [A3]
-        findConstructor(lookup, Object.class, void.class); // [A2]
-        findConstructorExpectingIAE(lookup, x500NameClass, void.class, String.class); // [A3]
-
-        /**
-         * Teleport from MethodHandles.lookup() to lookup class in the same module
-         * module access is retained [A0]
-         * can access all public types in m1 [A1]
-         * can access public types in packages exported by modules that m1 reads [A2]
-         * cannot access public types in non-exported modules of modules that m1 reads [A3]
-         */
-        lookup2 = lookup.in(p2_Type2);
-        assertTrue((lookup2.lookupModes() & MODULE) == MODULE); // [A0]
-        findConstructor(lookup2, p1_Type1, void.class); // [A1]
-        findConstructor(lookup2, p2_Type2, void.class); // [A1]
-        findConstructor(lookup2, q1_Type1, void.class); // [A2]
-        findConstructorExpectingIAE(lookup2, q2_Type2, void.class); // [A3]
-        findConstructor(lookup2, Object.class, void.class); // [A2]
-        findConstructorExpectingIAE(lookup2, x500NameClass, void.class, String.class); // [A3]
-
-        /**
-         * Teleport from MethodHandles.lookup() to lookup class in another named module
-         * has no access [A0]
-         */
-        lookup2 = lookup.in(Object.class);
-        assertTrue(lookup2.lookupModes() == 0); // [A0]
-        findConstructorExpectingIAE(lookup2, Object.class, void.class);  // [A0]
-
-        /**
-         * Teleport from MethodHandles.lookup() to lookup class in an unnamed module
-         * has no access [A0]
-         */
-        Class<?> c = MethodHandles.publicLookup().lookupClass();
-        assertTrue(!c.getModule().isNamed());
-        lookup2 = lookup.in(c);
-        assertTrue(lookup2.lookupModes() == 0); // [A0]
-        findConstructorExpectingIAE(lookup2, Object.class, void.class);
-
-        /**
-         * MethodHandles.publicLookup()
-         * has no module access [A0]
-         * can access public types in exported packages [A1]
-         * cannot access public types in non-exported packages [A2]
-         */
-        lookup = MethodHandles.publicLookup();
-        assertTrue((lookup.lookupModes() & MODULE) == 0); // [A0]
-        findConstructor(lookup, p1_Type1, void.class); // [A1]
-        findConstructorExpectingIAE(lookup, p2_Type2, void.class); // [A1]
-        findConstructor(lookup, q1_Type1, void.class); // [A1]
-        findConstructorExpectingIAE(lookup, q2_Type2, void.class); // [A2]
-        findConstructor(lookup, Object.class, void.class); // [A1]
-        findConstructorExpectingIAE(lookup, x500NameClass, void.class); // [A2]
-
-        /**
-         * Teleport from MethodHandles.publicLookup() to lookup class in java.base
-         * has no module access [A0]
-         * can access public types in packages exported by java.base [A1]
-         * cannot access public types in non-exported packages [A2]
-         * no access to types in other named modules [A3]
-         */
-        lookup2 = lookup.in(Object.class);
-        assertTrue((lookup2.lookupModes() & MODULE) == 0); // [A0]
-        findConstructor(lookup2, String.class, void.class); // [A1]
-        findConstructorExpectingIAE(lookup2, x500NameClass, void.class, String.class); // [A2]
-        findConstructorExpectingIAE(lookup2, p1_Type1, void.class); // [A3]
-        findConstructorExpectingIAE(lookup2, q1_Type1, void.class); // [A3]
-
-        /**
-         * Teleport from MethodHandles.publicLookup() to lookup class in m1
-         * has no module access [A0]
-         * can access public types in packages exported by m1, m2 and java.base [A1]
-         * cannot access public types is non-exported packages [A2]
-         */
-        lookup2 = lookup.in(p1_Type1);
-        assertTrue((lookup2.lookupModes() & MODULE) == 0); // [A0]
-        findConstructor(lookup2, p1_Type1, void.class);  // [A1]
-        findConstructor(lookup2, q1_Type1, void.class);  // [A1]
-        findConstructor(lookup2, Object.class, void.class);  // [A1]
-        findConstructorExpectingIAE(lookup, p2_Type2, void.class); // [A2]
-        findConstructorExpectingIAE(lookup, q2_Type2, void.class); // [A2]
-        findConstructorExpectingIAE(lookup2, x500NameClass, void.class, String.class); // [A2]
-
-        /**
-         * Teleport from MethodHandles.publicLookup() to lookup class in m2
-         * has no module access [A0]
-         * can access public types in packages exported by m2 and java.base [A1]
-         * cannot access public types is non-exported packages or modules that m2 does
-         *   not read [A2]
-         */
-        lookup2 = lookup.in(q1_Type1);
-        assertTrue((lookup2.lookupModes() & MODULE) == 0); // [A0]
-        findConstructor(lookup2, q1_Type1, void.class); // [A1]
-        findConstructor(lookup2, Object.class, void.class); // [A1]
-        findConstructorExpectingIAE(lookup2, p1_Type1, void.class); // [A2]
-        findConstructorExpectingIAE(lookup, q2_Type2, void.class); // [A2]
-        findConstructorExpectingIAE(lookup2, x500NameClass, void.class, String.class);  // [A2]
-
-        /**
-         * Teleport from MethodHandles.publicLookup() to lookup class that is not
-         * in an exported package, should get no access [A0]
-         */
-        lookup2 = lookup.in(p2_Type2);
-        assertTrue(lookup2.lookupModes()  == 0); // [A0]
-        findConstructorExpectingIAE(lookup, q2_Type2, void.class); // [A0]
-    }
-
-    /**
-     * Invokes Lookup findConstructor with a method type constructored from the
-     * given return and parameter types, expecting IllegalAccessException to be
-     * thrown.
-     */
-    static MethodHandle findConstructorExpectingIAE(Lookup lookup,
-                                                    Class<?> clazz,
-                                                    Class<?> rtype,
-                                                    Class<?>... ptypes) throws Exception {
-        try {
-            findConstructor(lookup, clazz, rtype, ptypes);
-            throw new RuntimeException("IllegalAccessError expected");
-        } catch (IllegalAccessException expected) {
-            return null;
-        }
-    }
-
-    /**
-     * Invokes Lookup findConstructor with a method type constructored from the
-     * given return and parameter types.
-     */
-    static MethodHandle findConstructor(Lookup lookup,
-                                        Class<?> clazz,
-                                        Class<?> rtype,
-                                        Class<?>... ptypes) throws Exception {
-        MethodType mt = MethodType.methodType(rtype, ptypes);
-        return lookup.findConstructor(clazz, mt);
-    }
-
-    static void assertTrue(boolean condition) {
-        if (!condition)
-            throw new RuntimeException();
-    }
-
-}
--- a/jdk/test/java/lang/invoke/modules/src/m1/p1/Type1.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 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
- * 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 p1;
-
-public class Type1 {
-    public Type1() { }
-}
--- a/jdk/test/java/lang/invoke/modules/src/m1/p2/Type2.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 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
- * 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 p2;
-
-public class Type2 {
-    public Type2() { }
-}
--- a/jdk/test/java/lang/invoke/modules/src/m2/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,25 +0,0 @@
-/*
- * Copyright (c) 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
- * 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.
- */
-module m2 {
-    exports q1;
-}
--- a/jdk/test/java/lang/invoke/modules/src/m2/q1/Type1.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 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
- * 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 q1;
-
-public class Type1 {
-    public Type1() { }
-}
--- a/jdk/test/java/lang/invoke/modules/src/m2/q2/Type2.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 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
- * 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 q2;
-
-public class Type2 {
-    public Type2() { }
-}
--- a/jdk/test/java/lang/management/ManagementFactory/DefaultManagementProviderTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/management/ManagementFactory/DefaultManagementProviderTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -26,6 +26,7 @@
  * @bug 8151099
  * @summary Verify platform MXBeans initialized properly with java.management
  *          module only. No other management provider
+ * @modules java.management
  * @run main/othervm --limit-modules=java.management DefaultManagementProviderTest
  */
 import java.lang.management.ManagementFactory;
--- a/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -36,7 +36,6 @@
  * @run main/timeout=600 LowMemoryTest
  * @requires vm.gc == "null"
  * @requires vm.opt.ExplicitGCInvokesConcurrent != "true"
- * @requires vm.opt.ExplicitGCInvokesConcurrentAndUnloadsClasses != "true"
  * @requires vm.opt.DisableExplicitGC != "true"
  */
 
--- a/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest2.sh	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/management/MemoryMXBean/LowMemoryTest2.sh	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2004, 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2004, 2017, 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
@@ -53,12 +53,12 @@
 # Run test with each GC configuration
 # 
 # Notes: To ensure that metaspace fills up we disable class unloading.
-# Also we set the max metaspace to 8MB - otherwise the test takes too
+# Also we set the max metaspace to 16MB - otherwise the test takes too
 # long to run. 
 
 go -noclassgc -XX:MaxMetaspaceSize=16m -XX:+UseSerialGC LowMemoryTest2
 go -noclassgc -XX:MaxMetaspaceSize=16m -XX:+UseParallelGC LowMemoryTest2
-go -noclassgc -XX:MaxMetaspaceSize=16m -XX:+UseParNewGC -XX:+UseConcMarkSweepGC LowMemoryTest2
+go -noclassgc -XX:MaxMetaspaceSize=16m -XX:+UseConcMarkSweepGC LowMemoryTest2
 
 # Test class metaspace - might hit MaxMetaspaceSize instead if
 # UseCompressedClassPointers is off or if 32 bit.
--- a/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/management/MemoryMXBean/ResetPeakMemoryUsage.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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,7 +37,6 @@
  * @build jdk.testlibrary.* ResetPeakMemoryUsage MemoryUtil RunUtil
  * @run main ResetPeakMemoryUsage
  * @requires vm.opt.ExplicitGCInvokesConcurrent != "true"
- * @requires vm.opt.ExplicitGCInvokesConcurrentAndUnloadsClasses != "true"
  * @requires vm.opt.DisableExplicitGC != "true"
  */
 
--- a/jdk/test/java/lang/module/AutomaticModulesTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/module/AutomaticModulesTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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,10 +33,10 @@
 import java.lang.module.Configuration;
 import java.lang.module.FindException;
 import java.lang.module.ModuleDescriptor;
-import java.lang.module.ModuleDescriptor.Exports;
 import java.lang.module.ModuleDescriptor.Requires.Modifier;
 import java.lang.module.ModuleFinder;
 import java.lang.module.ModuleReference;
+import java.lang.module.ResolutionException;
 import java.lang.module.ResolvedModule;
 import java.lang.reflect.Layer;
 import java.lang.reflect.Module;
@@ -137,6 +137,7 @@
         assertTrue(mref.isPresent(), mn + " not found");
 
         ModuleDescriptor descriptor = mref.get().descriptor();
+        assertTrue(descriptor.isAutomatic());
         assertEquals(descriptor.name(), mn);
         if (vs == null) {
             assertFalse(descriptor.version().isPresent());
@@ -175,17 +176,14 @@
         assertTrue(mref.isPresent(), "m not found");
 
         ModuleDescriptor descriptor = mref.get().descriptor();
+        assertTrue(descriptor.isAutomatic());
 
         assertTrue(descriptor.packages().size() == 2);
         assertTrue(descriptor.packages().contains("p"));
         assertTrue(descriptor.packages().contains("q"));
 
-        Set<String> exports = descriptor.exports().stream()
-                .map(Exports::source)
-                .collect(Collectors.toSet());
-        assertTrue(exports.size() == 2);
-        assertTrue(exports.contains("p"));
-        assertTrue(exports.contains("q"));
+        assertTrue(descriptor.exports().isEmpty());
+        assertTrue(descriptor.opens().isEmpty());
     }
 
     /**
@@ -201,15 +199,13 @@
         assertTrue(mref.isPresent(), "m not found");
 
         ModuleDescriptor descriptor = mref.get().descriptor();
+        assertTrue(descriptor.isAutomatic());
 
         assertTrue(descriptor.packages().size() == 1);
         assertTrue(descriptor.packages().contains("p"));
 
-        Set<String> exports = descriptor.exports().stream()
-                .map(Exports::source)
-                .collect(Collectors.toSet());
-        assertTrue(exports.size() == 1);
-        assertTrue(exports.contains("p"));
+        assertTrue(descriptor.exports().isEmpty());
+        assertTrue(descriptor.opens().isEmpty());
     }
 
     /**
@@ -229,10 +225,10 @@
         assertTrue(mref.isPresent(), "m not found");
 
         ModuleDescriptor descriptor = mref.get().descriptor();
+        assertTrue(descriptor.isAutomatic());
 
-        assertTrue(descriptor.packages().size() == 2);
+        assertTrue(descriptor.packages().size() == 1);
         assertTrue(descriptor.packages().contains("p"));
-        assertTrue(descriptor.packages().contains("p.resources"));
     }
 
     /**
@@ -254,9 +250,17 @@
         String provider = "p.S1";
 
         Path tmpdir = Files.createTempDirectory(USER_DIR, "tmp");
+
+        // provider class
+        Path providerClass = tmpdir.resolve(provider.replace('.', '/') + ".class");
+        Files.createDirectories(providerClass.getParent());
+        Files.createFile(providerClass);
+
+        // services configuration file
         Path services = tmpdir.resolve("META-INF").resolve("services");
         Files.createDirectories(services);
         Files.write(services.resolve(service), Set.of(provider));
+
         Path dir = Files.createTempDirectory(USER_DIR, "mods");
         JarUtils.createJarFile(dir.resolve("m.jar"), tmpdir);
 
@@ -314,7 +318,7 @@
 
                 // service type         provider type
                 { "p.S",                "-" },
-                { "p.S",                ".S1" },
+                { "p.S",                "p..S1" },
                 { "p.S",                "S1." },
         };
     }
@@ -324,13 +328,41 @@
      * values or names.
      */
     @Test(dataProvider = "badproviders", expectedExceptions = FindException.class)
-    public void testBadProvideNames(String service, String provider)
+    public void testBadProviderNames(String service, String provider)
         throws IOException
     {
         Path tmpdir = Files.createTempDirectory(USER_DIR, "tmp");
+
+        // provider class
+        Path providerClass = tmpdir.resolve(provider.replace('.', '/') + ".class");
+        Files.createDirectories(providerClass.getParent());
+        Files.createFile(providerClass);
+
+        // services configuration file
         Path services = tmpdir.resolve("META-INF").resolve("services");
         Files.createDirectories(services);
         Files.write(services.resolve(service), Set.of(provider));
+
+        Path dir = Files.createTempDirectory(USER_DIR, "mods");
+        JarUtils.createJarFile(dir.resolve("m.jar"), tmpdir);
+
+        // should throw FindException
+        ModuleFinder.of(dir).findAll();
+    }
+
+    /**
+     * Test JAR file with META-INF/services configuration file listing a
+     * provider that is not in the module.
+     */
+    @Test(expectedExceptions = FindException.class)
+    public void testMissingProviderPackage() throws IOException {
+        Path tmpdir = Files.createTempDirectory(USER_DIR, "tmp");
+
+        // services configuration file
+        Path services = tmpdir.resolve("META-INF").resolve("services");
+        Files.createDirectories(services);
+        Files.write(services.resolve("p.S"), Set.of("q.P"));
+
         Path dir = Files.createTempDirectory(USER_DIR, "mods");
         JarUtils.createJarFile(dir.resolve("m.jar"), tmpdir);
 
@@ -352,7 +384,8 @@
         attrs.put(Attributes.Name.MAIN_CLASS, mainClass);
 
         Path dir = Files.createTempDirectory(USER_DIR, "mods");
-        createDummyJarFile(dir.resolve("m.jar"), man);
+        String entry = mainClass.replace('.', '/') + ".class";
+        createDummyJarFile(dir.resolve("m.jar"), man, entry);
 
         ModuleFinder finder = ModuleFinder.of(dir);
 
@@ -366,20 +399,21 @@
     }
 
 
-    // Main-Class files that do not map to a legal Java identifier
+    // Main-Class files that do not map to a legal qualified type name
     @DataProvider(name = "badmainclass")
     public Object[][] createBadMainClass() {
         return new Object[][]{
 
+            { "Main",        null },
+            { "p..Main",     null },
             { "p-.Main",     null },
-            { ".Main",       null }
 
         };
     }
 
     /**
-     * Test that a JAR file with a Main-Class attribute that is not a valid
-     * Java identifier
+     * Test that a JAR file with a Main-Class attribute that is not a qualified
+     * type name.
      */
     @Test(dataProvider = "badmainclass", expectedExceptions = FindException.class)
     public void testBadMainClass(String mainClass, String ignore) throws IOException {
@@ -389,6 +423,24 @@
         attrs.put(Attributes.Name.MAIN_CLASS, mainClass);
 
         Path dir = Files.createTempDirectory(USER_DIR, "mods");
+        String entry = mainClass.replace('.', '/') + ".class";
+        createDummyJarFile(dir.resolve("m.jar"), man, entry);
+
+        // should throw FindException
+        ModuleFinder.of(dir).findAll();
+    }
+
+    /**
+     * Test that a JAR file with a Main-Class attribute that is not in the module
+     */
+    @Test(expectedExceptions = FindException.class)
+    public void testMissingMainClassPackage() throws IOException {
+        Manifest man = new Manifest();
+        Attributes attrs = man.getMainAttributes();
+        attrs.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
+        attrs.put(Attributes.Name.MAIN_CLASS, "p.Main");
+
+        Path dir = Files.createTempDirectory(USER_DIR, "mods");
         createDummyJarFile(dir.resolve("m.jar"), man);
 
         // should throw FindException
@@ -405,7 +457,7 @@
      */
     public void testConfiguration1() throws Exception {
         ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("a")
+            = ModuleDescriptor.newModule("a")
                 .requires("b")
                 .requires("c")
                 .requires("java.base")
@@ -465,13 +517,13 @@
      */
     public void testInConfiguration2() throws IOException {
         ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("a")
+            = ModuleDescriptor.newModule("a")
                 .requires("b")
                 .requires("java.base")
                 .build();
 
         ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("b")
+            = ModuleDescriptor.newModule("b")
                 .requires("c")
                 .requires("java.base")
                 .build();
@@ -538,13 +590,13 @@
      */
     public void testInConfiguration3() throws IOException {
         ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("a")
+            = ModuleDescriptor.newModule("a")
                 .requires("b")
                 .requires("java.base")
                 .build();
 
         ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("b")
+            = ModuleDescriptor.newModule("b")
                 .requires(Set.of(Modifier.TRANSITIVE), "c")
                 .requires("java.base")
                 .build();
@@ -609,11 +661,67 @@
 
 
     /**
+     * Basic test of a configuration created with automatic modules
+     *   a requires b* and c*
+     *   b* contains p
+     *   c* contains p
+     */
+    @Test(expectedExceptions = { ResolutionException.class })
+    public void testDuplicateSuppliers1() throws IOException {
+        ModuleDescriptor descriptor
+            = ModuleDescriptor.newModule("a")
+                .requires("b")
+                .requires("c")
+                .build();
+
+        // c and d are automatic modules with the same package
+        Path dir = Files.createTempDirectory(USER_DIR, "mods");
+        createDummyJarFile(dir.resolve("b.jar"), "p/T.class");
+        createDummyJarFile(dir.resolve("c.jar"), "p/T.class");
+
+        // module finder locates 'a' and the modules in the directory
+        ModuleFinder finder
+            = ModuleFinder.compose(ModuleUtils.finderOf(descriptor),
+                                   ModuleFinder.of(dir));
+
+        Configuration parent = Layer.boot().configuration();
+        resolve(parent, finder, "a");
+    }
+
+
+    /**
+     * Basic test of a configuration created with automatic modules
+     *   a contains p, requires b*
+     *   b* contains p
+     */
+    @Test(expectedExceptions = { ResolutionException.class })
+    public void testDuplicateSuppliers2() throws IOException {
+        ModuleDescriptor descriptor
+            = ModuleDescriptor.newModule("a")
+                .packages(Set.of("p"))
+                .requires("b")
+                .build();
+
+        // c and d are automatic modules with the same package
+        Path dir = Files.createTempDirectory(USER_DIR, "mods");
+        createDummyJarFile(dir.resolve("b.jar"), "p/T.class");
+
+        // module finder locates 'a' and the modules in the directory
+        ModuleFinder finder
+            = ModuleFinder.compose(ModuleUtils.finderOf(descriptor),
+                                   ModuleFinder.of(dir));
+
+        Configuration parent = Layer.boot().configuration();
+        resolve(parent, finder, "a");
+    }
+
+
+    /**
      * Basic test of Layer containing automatic modules
      */
     public void testInLayer() throws IOException {
         ModuleDescriptor descriptor
-            = ModuleDescriptor.module("a")
+            = ModuleDescriptor.newModule("a")
                 .requires("b")
                 .requires("c")
                 .build();
@@ -664,7 +772,7 @@
 
         // test miscellaneous methods
         assertTrue(m.isAutomatic());
-        assertFalse(m.isSynthetic());
+        assertFalse(m.modifiers().contains(ModuleDescriptor.Modifier.SYNTHETIC));
         assertFalse(m.osName().isPresent());
         assertFalse(m.osArch().isPresent());
         assertFalse(m.osVersion().isPresent());
@@ -672,12 +780,12 @@
 
 
     /**
-     * Invokes parent.resolveRequires to resolve the given root modules.
+     * Invokes parent.resolve to resolve the given root modules.
      */
     static Configuration resolve(Configuration parent,
                                  ModuleFinder finder,
                                  String... roots) {
-        return parent.resolveRequires(finder, ModuleFinder.of(), Set.of(roots));
+        return parent.resolve(finder, ModuleFinder.of(), Set.of(roots));
     }
 
     /**
--- a/jdk/test/java/lang/module/ConfigurationTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/module/ConfigurationTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -24,23 +24,26 @@
 /**
  * @test
  * @library /lib/testlibrary
+ * @modules java.base/jdk.internal.misc
  * @build ConfigurationTest ModuleUtils
  * @run testng ConfigurationTest
  * @summary Basic tests for java.lang.module.Configuration
  */
 
 import java.lang.module.Configuration;
+import java.lang.module.FindException;
 import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleDescriptor.Builder;
 import java.lang.module.ModuleDescriptor.Requires;
 import java.lang.module.ModuleFinder;
 import java.lang.module.ResolutionException;
 import java.lang.module.ResolvedModule;
 import java.lang.reflect.Layer;
-import java.util.HashSet;
 import java.util.List;
 import java.util.Optional;
 import java.util.Set;
 
+import jdk.internal.misc.SharedSecrets;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 import static org.testng.Assert.*;
@@ -48,30 +51,35 @@
 @Test
 public class ConfigurationTest {
 
+    /**
+     * Creates a "non-strict" builder for building a module. This allows the
+     * test the create ModuleDescriptor objects that do not require java.base.
+     */
+    private static ModuleDescriptor.Builder newBuilder(String mn) {
+        return SharedSecrets.getJavaLangModuleAccess()
+                .newModuleBuilder(mn, false, Set.of());
+    }
 
     /**
      * Basic test of resolver
      *     m1 requires m2, m2 requires m3
      */
     public void testBasic() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires("m2")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("m3")
                 .build();
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .build();
 
         ModuleFinder finder
             = ModuleUtils.finderOf(descriptor1, descriptor2, descriptor3);
 
-        Configuration cf = resolveRequires(finder, "m1");
+        Configuration cf = resolve(finder, "m1");
 
         assertTrue(cf.modules().size() == 3);
 
@@ -110,24 +118,21 @@
      */
     public void testRequiresTransitive1() {
         // m1 requires m2, m2 requires transitive m3
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires("m2")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m3")
                 .build();
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .build();
 
         ModuleFinder finder
             = ModuleUtils.finderOf(descriptor1, descriptor2, descriptor3);
 
-        Configuration cf = resolveRequires(finder, "m1");
+        Configuration cf = resolve(finder, "m1");
 
         assertTrue(cf.modules().size() == 3);
 
@@ -167,18 +172,16 @@
 
         // cf1: m1 and m2, m2 requires transitive m1
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m1")
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf1 = resolveRequires(finder1, "m2");
+        Configuration cf1 = resolve(finder1, "m2");
 
         assertTrue(cf1.modules().size() == 2);
         assertTrue(cf1.findModule("m1").isPresent());
@@ -196,14 +199,13 @@
 
         // cf2: m3, m3 requires m2
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m2")
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor3);
 
-        Configuration cf2 = resolveRequires(cf1, finder2, "m3");
+        Configuration cf2 = resolve(cf1, finder2, "m3");
 
         assertTrue(cf2.modules().size() == 1);
         assertTrue(cf2.findModule("m1").isPresent());  // in parent
@@ -231,13 +233,11 @@
 
         // cf1: m1
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .build();
+        ModuleDescriptor descriptor1 = newBuilder("m1").build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf1 = resolveRequires(finder1, "m1");
+        Configuration cf1 = resolve(finder1, "m1");
 
         assertTrue(cf1.modules().size() == 1);
         assertTrue(cf1.findModule("m1").isPresent());
@@ -250,19 +250,17 @@
 
         // cf2: m2, m3: m2 requires transitive m1, m3 requires m2
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m1")
                 .build();
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m2")
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor2, descriptor3);
 
-        Configuration cf2 = resolveRequires(cf1, finder2, "m3");
+        Configuration cf2 = resolve(cf1, finder2, "m3");
 
         assertTrue(cf2.modules().size() == 2);
         assertTrue(cf2.findModule("m1").isPresent());   // in parent
@@ -297,13 +295,11 @@
 
         // cf1: m1
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .build();
+        ModuleDescriptor descriptor1 = newBuilder("m1").build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf1 = resolveRequires(finder1, "m1");
+        Configuration cf1 = resolve(finder1, "m1");
 
         assertTrue(cf1.modules().size() == 1);
         assertTrue(cf1.findModule("m1").isPresent());
@@ -316,14 +312,13 @@
 
         // cf2: m2 requires transitive m1
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m1")
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor2);
 
-        Configuration cf2 = resolveRequires(cf1, finder2, "m2");
+        Configuration cf2 = resolve(cf1, finder2, "m2");
 
         assertTrue(cf2.modules().size() == 1);
         assertTrue(cf2.findModule("m1").isPresent());  // in parent
@@ -340,14 +335,13 @@
 
         // cf3: m3 requires m2
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m2")
                 .build();
 
         ModuleFinder finder3 = ModuleUtils.finderOf(descriptor3);
 
-        Configuration cf3 = resolveRequires(cf2, finder3, "m3");
+        Configuration cf3 = resolve(cf2, finder3, "m3");
 
         assertTrue(cf3.modules().size() == 1);
         assertTrue(cf3.findModule("m1").isPresent());  // in parent
@@ -376,18 +370,16 @@
 
         // cf1: m1, m2 requires transitive m1
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m1")
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf1 = resolveRequires(finder1, "m2");
+        Configuration cf1 = resolve(finder1, "m2");
 
         assertTrue(cf1.modules().size() == 2);
         assertTrue(cf1.findModule("m1").isPresent());
@@ -408,20 +400,18 @@
 
         // cf2: m3 requires transitive m2, m4 requires m3
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m2")
                 .build();
 
-        ModuleDescriptor descriptor4
-            = ModuleDescriptor.module("m4")
+        ModuleDescriptor descriptor4 = newBuilder("m4")
                 .requires("m3")
                 .build();
 
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor3, descriptor4);
 
-        Configuration cf2 = resolveRequires(cf1, finder2, "m3", "m4");
+        Configuration cf2 = resolve(cf1, finder2, "m3", "m4");
 
         assertTrue(cf2.modules().size() == 2);
         assertTrue(cf2.findModule("m1").isPresent());   // in parent
@@ -456,28 +446,24 @@
      * - Configuration cf3(cf1,cf2): m4 requires m2, m3
      */
     public void testRequiresTransitive6() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m1")
                 .build();
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m1")
                 .build();
 
-        ModuleDescriptor descriptor4
-            = ModuleDescriptor.module("m4")
+        ModuleDescriptor descriptor4 = newBuilder("m4")
                 .requires("m2")
                 .requires("m3")
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1, descriptor2);
-        Configuration cf1 = resolveRequires(finder1, "m2");
+        Configuration cf1 = resolve(finder1, "m2");
         assertTrue(cf1.modules().size() == 2);
         assertTrue(cf1.findModule("m1").isPresent());
         assertTrue(cf1.findModule("m2").isPresent());
@@ -485,7 +471,7 @@
         assertTrue(cf1.parents().get(0) == Configuration.empty());
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor1, descriptor3);
-        Configuration cf2 = resolveRequires(finder2, "m3");
+        Configuration cf2 = resolve(finder2, "m3");
         assertTrue(cf2.modules().size() == 2);
         assertTrue(cf2.findModule("m3").isPresent());
         assertTrue(cf2.findModule("m1").isPresent());
@@ -493,7 +479,7 @@
         assertTrue(cf2.parents().get(0) == Configuration.empty());
 
         ModuleFinder finder3 = ModuleUtils.finderOf(descriptor4);
-        Configuration cf3 = Configuration.resolveRequires(finder3,
+        Configuration cf3 = Configuration.resolve(finder3,
                 List.of(cf1, cf2),
                 ModuleFinder.of(),
                 Set.of("m4"));
@@ -522,14 +508,13 @@
      *     resolve m1
      */
     public void testRequiresStatic1() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires(Set.of(Requires.Modifier.STATIC), "m2")
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf = resolveRequires(finder, "m1");
+        Configuration cf = resolve(finder, "m1");
 
         assertTrue(cf.modules().size() == 1);
 
@@ -545,18 +530,16 @@
      *     resolve m1
      */
     public void testRequiresStatic2() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires(Set.of(Requires.Modifier.STATIC), "m2")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf = resolveRequires(finder, "m1");
+        Configuration cf = resolve(finder, "m1");
 
         assertTrue(cf.modules().size() == 1);
 
@@ -572,18 +555,16 @@
      *     resolve m1, m2
      */
     public void testRequiresStatic3() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires(Set.of(Requires.Modifier.STATIC), "m2")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf = resolveRequires(finder, "m1", "m2");
+        Configuration cf = resolve(finder, "m1", "m2");
 
         assertTrue(cf.modules().size() == 2);
 
@@ -604,25 +585,22 @@
      *     m3
      */
     public void testRequiresStatic4() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires("m2")
                 .requires("m3")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.STATIC), "m3")
                 .build();
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .build();
 
         ModuleFinder finder
-                = ModuleUtils.finderOf(descriptor1, descriptor2, descriptor3);
-
-        Configuration cf = resolveRequires(finder, "m1");
+            = ModuleUtils.finderOf(descriptor1, descriptor2, descriptor3);
+
+        Configuration cf = resolve(finder, "m1");
 
         assertTrue(cf.modules().size() == 3);
 
@@ -648,31 +626,28 @@
      * - Configuration cf2: m3 requires m1, requires static m2
      */
     public void testRequiresStatic5() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf1 = resolveRequires(finder1, "m1", "m2");
+        Configuration cf1 = resolve(finder1, "m1", "m2");
 
         assertTrue(cf1.modules().size() == 2);
         assertTrue(cf1.findModule("m1").isPresent());
         assertTrue(cf1.findModule("m2").isPresent());
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m1")
                 .requires(Set.of(Requires.Modifier.STATIC), "m2")
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor3);
 
-        Configuration cf2 = resolveRequires(cf1, finder2, "m3");
+        Configuration cf2 = resolve(cf1, finder2, "m3");
 
         assertTrue(cf2.modules().size() == 1);
         assertTrue(cf2.findModule("m3").isPresent());
@@ -694,26 +669,24 @@
      * - Configuration cf2: m3 requires m1, requires static m2
      */
     public void testRequiresStatic6() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf1 = resolveRequires(finder1, "m1");
+        Configuration cf1 = resolve(finder1, "m1");
 
         assertTrue(cf1.modules().size() == 1);
         assertTrue(cf1.findModule("m1").isPresent());
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m1")
                 .requires(Set.of(Requires.Modifier.STATIC), "m2")
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor3);
 
-        Configuration cf2 = resolveRequires(cf1, finder2, "m3");
+        Configuration cf2 = resolve(cf1, finder2, "m3");
 
         assertTrue(cf2.modules().size() == 1);
         assertTrue(cf2.findModule("m3").isPresent());
@@ -735,21 +708,19 @@
     public void testRequiresStatic7() {
         ModuleDescriptor descriptor1 = null;  // not observable
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE,
                                 Requires.Modifier.STATIC),
                          "m1")
                 .build();
 
-        ModuleDescriptor descriptor3
-                = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m2")
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor2, descriptor3);
 
-        Configuration cf = resolveRequires(finder, "m3");
+        Configuration cf = resolve(finder, "m3");
 
         assertTrue(cf.modules().size() == 2);
         assertTrue(cf.findModule("m2").isPresent());
@@ -770,8 +741,7 @@
     public void testRequiresStatic8() {
         ModuleDescriptor descriptor1 = null;  // not observable
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE,
                                 Requires.Modifier.STATIC),
                         "m1")
@@ -779,21 +749,20 @@
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor2);
 
-        Configuration cf1 = resolveRequires(finder1, "m2");
+        Configuration cf1 = resolve(finder1, "m2");
 
         assertTrue(cf1.modules().size() == 1);
         assertTrue(cf1.findModule("m2").isPresent());
         ResolvedModule m2 = cf1.findModule("m2").get();
         assertTrue(m2.reads().isEmpty());
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m2")
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor3);
 
-        Configuration cf2 = resolveRequires(cf1, finder2, "m3");
+        Configuration cf2 = resolve(cf1, finder2, "m3");
 
         assertTrue(cf2.modules().size() == 1);
         assertTrue(cf2.findModule("m3").isPresent());
@@ -810,22 +779,19 @@
      */
     public void testServiceBinding1() {
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .exports("p")
                 .uses("p.S")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("m1")
-                .contains("q")
-                .provides("p.S", "q.T")
+                .provides("p.S", List.of("q.T"))
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf = resolveRequiresAndUses(finder, "m1");
+        Configuration cf = resolveAndBind(finder, "m1");
 
         assertTrue(cf.modules().size() == 2);
         assertTrue(cf.findModule("m1").isPresent());
@@ -853,31 +819,26 @@
      */
     public void testServiceBinding2() {
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .exports("p")
                 .uses("p.S1")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("m1")
                 .uses("p.S2")
-                .contains("q")
-                .provides("p.S1", "q.Service1Impl")
+                .provides("p.S1", List.of("q.Service1Impl"))
                 .build();
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m1")
-                .contains("q")
-                .provides("p.S2", "q.Service2Impl")
+                .provides("p.S2", List.of("q.Service2Impl"))
                 .build();
 
         ModuleFinder finder
             = ModuleUtils.finderOf(descriptor1, descriptor2, descriptor3);
 
-        Configuration cf = resolveRequiresAndUses(finder, "m1");
+        Configuration cf = resolveAndBind(finder, "m1");
 
         assertTrue(cf.modules().size() == 3);
         assertTrue(cf.findModule("m1").isPresent());
@@ -912,29 +873,26 @@
      */
     public void testServiceBindingWithConfigurations1() {
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .exports("p")
                 .uses("p.S")
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf1 = resolveRequires(finder1, "m1");
+        Configuration cf1 = resolve(finder1, "m1");
 
         assertTrue(cf1.modules().size() == 1);
         assertTrue(cf1.findModule("m1").isPresent());
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("m1")
-                .contains("q")
-                .provides("p.S", "q.T")
+                .provides("p.S", List.of("q.T"))
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor2);
 
-        Configuration cf2 = resolveRequiresAndUses(cf1, finder2); // no roots
+        Configuration cf2 = resolveAndBind(cf1, finder2); // no roots
 
         assertTrue(cf2.parents().size() == 1);
         assertTrue(cf2.parents().get(0) == cf1);
@@ -961,47 +919,39 @@
      */
     public void testServiceBindingWithConfigurations2() {
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .exports("p")
                 .uses("p.S")
-                .contains("p1")
-                .provides("p.S", "p1.ServiceImpl")
+                .provides("p.S", List.of("p1.ServiceImpl"))
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("m1")
-                .contains("p2")
-                .provides("p.S", "p2.ServiceImpl")
+                .provides("p.S", List.of("p2.ServiceImpl"))
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf1 = resolveRequiresAndUses(finder1, "m1");
+        Configuration cf1 = resolveAndBind(finder1, "m1");
 
         assertTrue(cf1.modules().size() == 2);
         assertTrue(cf1.findModule("m1").isPresent());
         assertTrue(cf1.findModule("m2").isPresent());
 
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m1")
-                .contains("p3")
-                .provides("p.S", "p3.ServiceImpl")
+                .provides("p.S", List.of("p3.ServiceImpl"))
                 .build();
 
-        ModuleDescriptor descriptor4
-            = ModuleDescriptor.module("m4")
+        ModuleDescriptor descriptor4 = newBuilder("m4")
                 .requires("m1")
-                .contains("p4")
-                .provides("p.S", "p4.ServiceImpl")
+                .provides("p.S", List.of("p4.ServiceImpl"))
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor3, descriptor4);
 
-        Configuration cf2 = resolveRequiresAndUses(cf1, finder2); // no roots
+        Configuration cf2 = resolveAndBind(cf1, finder2); // no roots
 
         assertTrue(cf2.parents().size() == 1);
         assertTrue(cf2.parents().get(0) == cf1);
@@ -1037,22 +987,19 @@
      */
     public void testServiceBindingWithConfigurations3() {
 
-        ModuleDescriptor service
-            = ModuleDescriptor.module("s")
+        ModuleDescriptor service = newBuilder("s")
                 .exports("p")
                 .build();
 
-        ModuleDescriptor provider_v1
-            = ModuleDescriptor.module("p")
+        ModuleDescriptor provider_v1 = newBuilder("p")
                 .version("1.0")
                 .requires("s")
-                .contains("q")
-                .provides("p.S", "q.T")
+                .provides("p.S", List.of("q.T"))
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(service, provider_v1);
 
-        Configuration cf1 = resolveRequires(finder1, "p");
+        Configuration cf1 = resolve(finder1, "p");
 
         assertTrue(cf1.modules().size() == 2);
         assertTrue(cf1.findModule("s").isPresent());
@@ -1063,18 +1010,15 @@
         assertEquals(p.reference().descriptor(), provider_v1);
 
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires("s")
                 .uses("p.S")
                 .build();
 
-        ModuleDescriptor provider_v2
-            = ModuleDescriptor.module("p")
+        ModuleDescriptor provider_v2 = newBuilder("p")
                 .version("2.0")
                 .requires("s")
-                .contains("q")
-                .provides("p.S", "q.T")
+                .provides("p.S", List.of("q.T"))
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor1, provider_v2);
@@ -1082,7 +1026,7 @@
 
         // finder2 is the before ModuleFinder and so p@2.0 should be located
 
-        Configuration cf2 = resolveRequiresAndUses(cf1, finder2, "m1");
+        Configuration cf2 = resolveAndBind(cf1, finder2, "m1");
 
         assertTrue(cf2.parents().size() == 1);
         assertTrue(cf2.parents().get(0) == cf1);
@@ -1097,7 +1041,7 @@
         // finder2 is the after ModuleFinder and so p@2.0 should not be located
         // as module p is in parent configuration.
 
-        cf2 = resolveRequiresAndUses(cf1, ModuleFinder.of(), finder2, "m1");
+        cf2 = resolveAndBind(cf1, ModuleFinder.of(), finder2, "m1");
 
         assertTrue(cf2.parents().size() == 1);
         assertTrue(cf2.parents().get(0) == cf1);
@@ -1117,25 +1061,22 @@
      */
     public void testWithTwoFinders1() {
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires("m2")
                 .build();
 
-        ModuleDescriptor descriptor2_v1
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2_v1 = newBuilder("m2")
                 .version("1.0")
                 .build();
 
-        ModuleDescriptor descriptor2_v2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2_v2 = newBuilder("m2")
                 .version("2.0")
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor2_v1);
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor1, descriptor2_v2);
 
-        Configuration cf = resolveRequires(finder1, finder2, "m1");
+        Configuration cf = resolve(finder1, finder2, "m1");
 
         assertTrue(cf.modules().size() == 2);
         assertTrue(cf.findModule("m1").isPresent());
@@ -1157,30 +1098,25 @@
      */
     public void testWithTwoFinders2() {
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .exports("p")
                 .uses("p.S")
                 .build();
 
-        ModuleDescriptor descriptor2_v1
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2_v1 = newBuilder("m2")
                 .requires("m1")
-                .contains("q")
-                .provides("p.S", "q.T")
+                .provides("p.S", List.of("q.T"))
                 .build();
 
-        ModuleDescriptor descriptor2_v2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2_v2 = newBuilder("m2")
                 .requires("m1")
-                .contains("q")
-                .provides("p.S", "q.T")
+                .provides("p.S", List.of("q.T"))
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1, descriptor2_v1);
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor2_v2);
 
-        Configuration cf = resolveRequiresAndUses(finder1, finder2, "m1");
+        Configuration cf = resolveAndBind(finder1, finder2, "m1");
 
         assertTrue(cf.modules().size() == 2);
         assertTrue(cf.findModule("m1").isPresent());
@@ -1200,18 +1136,17 @@
      */
     public void testResolvedInParent1() {
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf1 = resolveRequires(finder, "m1");
+        Configuration cf1 = resolve(finder, "m1");
 
         assertTrue(cf1.modules().size() == 1);
         assertTrue(cf1.findModule("m1").isPresent());
 
-        Configuration cf2 = resolveRequires(cf1, finder, "m1");
+        Configuration cf2 = resolve(cf1, finder, "m1");
 
         assertTrue(cf2.modules().size() == 1);
     }
@@ -1223,26 +1158,23 @@
      */
     public void testResolvedInParent2() {
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .build();
+        ModuleDescriptor descriptor1 = newBuilder("m1").build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf1 = resolveRequires(finder1, "m1");
+        Configuration cf1 = resolve(finder1, "m1");
 
         assertTrue(cf1.modules().size() == 1);
         assertTrue(cf1.findModule("m1").isPresent());
 
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("m1")
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor2);
 
-        Configuration cf2 = resolveRequires(cf1, ModuleFinder.of(), finder2, "m2");
+        Configuration cf2 = resolve(cf1, ModuleFinder.of(), finder2, "m2");
 
         assertTrue(cf2.modules().size() == 1);
         assertTrue(cf2.findModule("m2").isPresent());
@@ -1268,29 +1200,28 @@
     public void testResolvedInMultipleParents1() {
 
         // Configuration cf1: m1
-        ModuleDescriptor descriptor1 = ModuleDescriptor.module("m1").build();
-        Configuration cf1 = resolveRequires(ModuleUtils.finderOf(descriptor1), "m1");
+        ModuleDescriptor descriptor1 = newBuilder("m1").build();
+        Configuration cf1 = resolve(ModuleUtils.finderOf(descriptor1), "m1");
         assertEquals(cf1.parents(), List.of(Configuration.empty()));
         assertTrue(cf1.findModule("m1").isPresent());
         ResolvedModule m1 = cf1.findModule("m1").get();
         assertTrue(m1.configuration() == cf1);
 
         // Configuration cf2: m2
-        ModuleDescriptor descriptor2 = ModuleDescriptor.module("m2").build();
-        Configuration cf2 = resolveRequires(ModuleUtils.finderOf(descriptor2), "m2");
+        ModuleDescriptor descriptor2 = newBuilder("m2").build();
+        Configuration cf2 = resolve(ModuleUtils.finderOf(descriptor2), "m2");
         assertEquals(cf2.parents(), List.of(Configuration.empty()));
         assertTrue(cf2.findModule("m2").isPresent());
         ResolvedModule m2 = cf2.findModule("m2").get();
         assertTrue(m2.configuration() == cf2);
 
         // Configuration cf3(cf1,cf2): m3 requires m1 and m2
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m1")
                 .requires("m2")
                 .build();
         ModuleFinder finder = ModuleUtils.finderOf(descriptor3);
-        Configuration cf3 = Configuration.resolveRequires(
+        Configuration cf3 = Configuration.resolve(
                 finder,
                 List.of(cf1, cf2),  // parents
                 ModuleFinder.of(),
@@ -1319,19 +1250,18 @@
      */
     public void testResolvedInMultipleParents2() {
         // Configuration cf1: m1
-        ModuleDescriptor descriptor1 = ModuleDescriptor.module("m1").build();
-        Configuration cf1 = resolveRequires(ModuleUtils.finderOf(descriptor1), "m1");
+        ModuleDescriptor descriptor1 = newBuilder("m1").build();
+        Configuration cf1 = resolve(ModuleUtils.finderOf(descriptor1), "m1");
         assertEquals(cf1.parents(), List.of(Configuration.empty()));
         assertTrue(cf1.findModule("m1").isPresent());
         ResolvedModule m1 = cf1.findModule("m1").get();
         assertTrue(m1.configuration() == cf1);
 
         // Configuration cf2(cf1): m2 requires m1
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("m1")
                 .build();
-        Configuration cf2 = Configuration.resolveRequires(
+        Configuration cf2 = Configuration.resolve(
                 ModuleUtils.finderOf(descriptor2),
                 List.of(cf1),  // parents
                 ModuleFinder.of(),
@@ -1342,11 +1272,10 @@
         assertTrue(m2.configuration() == cf2);
 
         // Configuration cf3(cf1): m3 requires m1
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m1")
                 .build();
-        Configuration cf3 = Configuration.resolveRequires(
+        Configuration cf3 = Configuration.resolve(
                 ModuleUtils.finderOf(descriptor3),
                 List.of(cf1),  // parents
                 ModuleFinder.of(),
@@ -1357,13 +1286,12 @@
         assertTrue(m3.configuration() == cf3);
 
         // Configuration cf4(cf2,cf3): m4 requires m1,m2,m3
-        ModuleDescriptor descriptor4
-            = ModuleDescriptor.module("m4")
+        ModuleDescriptor descriptor4 = newBuilder("m4")
                 .requires("m1")
                 .requires("m2")
                 .requires("m3")
                 .build();
-        Configuration cf4 = Configuration.resolveRequires(
+        Configuration cf4 = Configuration.resolve(
                 ModuleUtils.finderOf(descriptor4),
                 List.of(cf2, cf3),  // parents
                 ModuleFinder.of(),
@@ -1395,35 +1323,34 @@
         ModuleDescriptor descriptor1, descriptor2, descriptor3;
 
         // Configuration cf1: m1@1
-        descriptor1 = ModuleDescriptor.module("m1").version("1").build();
-        Configuration cf1 = resolveRequires(ModuleUtils.finderOf(descriptor1), "m1");
+        descriptor1 = newBuilder("m1").version("1").build();
+        Configuration cf1 = resolve(ModuleUtils.finderOf(descriptor1), "m1");
         assertEquals(cf1.parents(), List.of(Configuration.empty()));
 
         // Configuration cf2: m1@2, m2@2
-        descriptor1 = ModuleDescriptor.module("m1").version("2").build();
-        descriptor2 = ModuleDescriptor.module("m2").version("2").build();
-        Configuration cf2 = resolveRequires(
+        descriptor1 = newBuilder("m1").version("2").build();
+        descriptor2 = newBuilder("m2").version("2").build();
+        Configuration cf2 = resolve(
                 ModuleUtils.finderOf(descriptor1, descriptor2),
                 "m1", "m2");
         assertEquals(cf2.parents(), List.of(Configuration.empty()));
 
         // Configuration cf3: m1@3, m2@3, m3@3
-        descriptor1 = ModuleDescriptor.module("m1").version("3").build();
-        descriptor2 = ModuleDescriptor.module("m2").version("3").build();
-        descriptor3 = ModuleDescriptor.module("m3").version("3").build();
-        Configuration cf3 = resolveRequires(
+        descriptor1 = newBuilder("m1").version("3").build();
+        descriptor2 = newBuilder("m2").version("3").build();
+        descriptor3 = newBuilder("m3").version("3").build();
+        Configuration cf3 = resolve(
                 ModuleUtils.finderOf(descriptor1, descriptor2, descriptor3),
                 "m1", "m2", "m3");
         assertEquals(cf3.parents(), List.of(Configuration.empty()));
 
         // Configuration cf4(cf1,cf2,cf3): m4 requires m1,m2,m3
-        ModuleDescriptor descriptor4
-                = ModuleDescriptor.module("m4")
+        ModuleDescriptor descriptor4 = newBuilder("m4")
                 .requires("m1")
                 .requires("m2")
                 .requires("m3")
                 .build();
-        Configuration cf4 = Configuration.resolveRequires(
+        Configuration cf4 = Configuration.resolve(
                 ModuleUtils.finderOf(descriptor4),
                 List.of(cf1, cf2, cf3),  // parents
                 ModuleFinder.of(),
@@ -1470,17 +1397,15 @@
      * configuration.
      */
     public void testOverriding1() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .build();
+        ModuleDescriptor descriptor1 = newBuilder("m1").build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf1 = resolveRequires(finder, "m1");
+        Configuration cf1 = resolve(finder, "m1");
         assertTrue(cf1.modules().size() == 1);
         assertTrue(cf1.findModule("m1").isPresent());
 
-        Configuration cf2 = resolveRequires(cf1, finder, "m1");
+        Configuration cf2 = resolve(cf1, finder, "m1");
         assertTrue(cf2.modules().size() == 1);
         assertTrue(cf2.findModule("m1").isPresent());
     }
@@ -1490,24 +1415,24 @@
      * configuration.
      */
     public void testOverriding2() {
-        ModuleDescriptor descriptor1 = ModuleDescriptor.module("m1").build();
-        Configuration cf1 = resolveRequires(ModuleUtils.finderOf(descriptor1), "m1");
+        ModuleDescriptor descriptor1 = newBuilder("m1").build();
+        Configuration cf1 = resolve(ModuleUtils.finderOf(descriptor1), "m1");
         assertTrue(cf1.modules().size() == 1);
         assertTrue(cf1.findModule("m1").isPresent());
 
-        ModuleDescriptor descriptor2 = ModuleDescriptor.module("m2").build();
-        Configuration cf2 = resolveRequires(ModuleUtils.finderOf(descriptor2), "m2");
+        ModuleDescriptor descriptor2 = newBuilder("m2").build();
+        Configuration cf2 = resolve(ModuleUtils.finderOf(descriptor2), "m2");
         assertTrue(cf2.modules().size() == 1);
         assertTrue(cf2.findModule("m2").isPresent());
 
-        ModuleDescriptor descriptor3 = ModuleDescriptor.module("m3").build();
-        Configuration cf3 = resolveRequires(ModuleUtils.finderOf(descriptor3), "m3");
+        ModuleDescriptor descriptor3 = newBuilder("m3").build();
+        Configuration cf3 = resolve(ModuleUtils.finderOf(descriptor3), "m3");
         assertTrue(cf3.modules().size() == 1);
         assertTrue(cf3.findModule("m3").isPresent());
 
         // override m2, m1 and m3 should be found in parent configurations
         ModuleFinder finder = ModuleUtils.finderOf(descriptor2);
-        Configuration cf4 = Configuration.resolveRequires(
+        Configuration cf4 = Configuration.resolve(
                 finder,
                 List.of(cf1, cf2, cf3),
                 ModuleFinder.of(),
@@ -1530,18 +1455,16 @@
      */
     public void testOverriding3() {
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m1")
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf1 = resolveRequires(finder1, "m2");
+        Configuration cf1 = resolve(finder1, "m2");
 
         assertTrue(cf1.modules().size() == 2);
         assertTrue(cf1.findModule("m1").isPresent());
@@ -1549,14 +1472,13 @@
 
         // cf2: m3 requires m2, m1
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m2")
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor1, descriptor3);
 
-        Configuration cf2 = resolveRequires(cf1, finder2, "m1", "m3");
+        Configuration cf2 = resolve(cf1, finder2, "m1", "m3");
 
         assertTrue(cf2.parents().size() == 1);
         assertTrue(cf2.parents().get(0) == cf1);
@@ -1585,64 +1507,58 @@
     /**
      * Root module not found
      */
-    @Test(expectedExceptions = { ResolutionException.class })
+    @Test(expectedExceptions = { FindException.class })
     public void testRootNotFound() {
-        resolveRequires(ModuleFinder.of(), "m1");
+        resolve(ModuleFinder.of(), "m1");
     }
 
 
     /**
      * Direct dependency not found
      */
-    @Test(expectedExceptions = { ResolutionException.class })
+    @Test(expectedExceptions = { FindException.class })
     public void testDirectDependencyNotFound() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1").requires("m2").build();
+        ModuleDescriptor descriptor1 = newBuilder("m1").requires("m2").build();
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1);
-        resolveRequires(finder, "m1");
+        resolve(finder, "m1");
     }
 
 
     /**
      * Transitive dependency not found
      */
-    @Test(expectedExceptions = { ResolutionException.class })
+    @Test(expectedExceptions = { FindException.class })
     public void testTransitiveDependencyNotFound() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1").requires("m2").build();
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2").requires("m3").build();
+        ModuleDescriptor descriptor1 = newBuilder("m1").requires("m2").build();
+        ModuleDescriptor descriptor2 = newBuilder("m2").requires("m3").build();
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
-        resolveRequires(finder, "m1");
+        resolve(finder, "m1");
     }
 
 
     /**
      * Service provider dependency not found
      */
-    @Test(expectedExceptions = { ResolutionException.class })
+    @Test(expectedExceptions = { FindException.class })
     public void testServiceProviderDependencyNotFound() {
 
         // service provider dependency (on m3) not found
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .exports("p")
                 .uses("p.S")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("m1")
                 .requires("m3")
-                .contains("q")
-                .provides("p.S", "q.T")
+                .provides("p.S", List.of("q.T"))
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
 
         // should throw ResolutionException because m3 is not found
-        Configuration cf = resolveRequiresAndUses(finder, "m1");
+        Configuration cf = resolveAndBind(finder, "m1");
     }
 
 
@@ -1651,15 +1567,12 @@
      */
     @Test(expectedExceptions = { ResolutionException.class })
     public void testSimpleCycle() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1").requires("m2").build();
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2").requires("m3").build();
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3").requires("m1").build();
+        ModuleDescriptor descriptor1 = newBuilder("m1").requires("m2").build();
+        ModuleDescriptor descriptor2 = newBuilder("m2").requires("m3").build();
+        ModuleDescriptor descriptor3 = newBuilder("m3").requires("m1").build();
         ModuleFinder finder
             = ModuleUtils.finderOf(descriptor1, descriptor2, descriptor3);
-        resolveRequires(finder, "m1");
+        resolve(finder, "m1");
     }
 
     /**
@@ -1668,20 +1581,16 @@
     @Test(expectedExceptions = { ResolutionException.class })
     public void testCycleInProvider() {
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .exports("p")
                 .uses("p.S")
                 .build();
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("m1")
                 .requires("m3")
-                .contains("q")
-                .provides("p.S", "q.T")
+                .provides("p.S", List.of("q.T"))
                 .build();
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m2")
                 .build();
 
@@ -1689,7 +1598,7 @@
             = ModuleUtils.finderOf(descriptor1, descriptor2, descriptor3);
 
         // should throw ResolutionException because of the m2 <--> m3 cycle
-        resolveRequiresAndUses(finder, "m1");
+        resolveAndBind(finder, "m1");
     }
 
 
@@ -1699,19 +1608,16 @@
     @Test(expectedExceptions = { ResolutionException.class })
     public void testPackageSuppliedByTwoOthers() {
 
-        ModuleDescriptor descriptor1
-            =  ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires("m2")
                 .requires("m3")
                 .build();
 
-        ModuleDescriptor descriptor2
-            =  ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .exports("p")
                 .build();
 
-        ModuleDescriptor descriptor3
-            =  ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .exports("p", Set.of("m1"))
                 .build();
 
@@ -1719,7 +1625,7 @@
             = ModuleUtils.finderOf(descriptor1, descriptor2, descriptor3);
 
         // m2 and m3 export package p to module m1
-        resolveRequires(finder, "m1");
+        resolve(finder, "m1");
     }
 
 
@@ -1730,21 +1636,19 @@
     @Test(expectedExceptions = { ResolutionException.class })
     public void testPackageSuppliedBySelfAndOther() {
 
-        ModuleDescriptor descriptor1
-            =  ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires("m2")
-                .contains("p")
+                .packages(Set.of("p"))
                 .build();
 
-        ModuleDescriptor descriptor2
-            =  ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .exports("p")
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
 
         // m1 contains package p, module m2 exports package p to m1
-        resolveRequires(finder, "m1");
+        resolve(finder, "m1");
     }
 
 
@@ -1753,20 +1657,18 @@
      * a module that also contains a package p.
      */
     public void testContainsPackageInSelfAndOther() {
-        ModuleDescriptor descriptor1
-            =  ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires("m2")
-                .contains("p")
+                .packages(Set.of("p"))
                 .build();
 
-        ModuleDescriptor descriptor2
-            =  ModuleDescriptor.module("m2")
-                .contains("p")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
+                .packages(Set.of("p"))
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf = resolveRequires(finder, "m1");
+        Configuration cf = resolve(finder, "m1");
 
         assertTrue(cf.modules().size() == 2);
         assertTrue(cf.findModule("m1").isPresent());
@@ -1787,8 +1689,7 @@
      */
     @Test(expectedExceptions = { ResolutionException.class })
     public void testExportSamePackageAsBootLayer() {
-        ModuleDescriptor descriptor
-            =  ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor = newBuilder("m1")
                 .requires("java.base")
                 .exports("java.lang")
                 .build();
@@ -1798,7 +1699,7 @@
         Configuration bootConfiguration = Layer.boot().configuration();
 
         // m1 contains package java.lang, java.base exports package java.lang to m1
-        resolveRequires(bootConfiguration, finder, "m1");
+        resolve(bootConfiguration, finder, "m1");
     }
 
 
@@ -1806,15 +1707,14 @@
      * Test "uses p.S" where p is contained in the same module.
      */
     public void testContainsService1() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .contains("p")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
+                .packages(Set.of("p"))
                 .uses("p.S")
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf = resolveRequires(finder, "m1");
+        Configuration cf = resolve(finder, "m1");
 
         assertTrue(cf.modules().size() == 1);
         assertTrue(cf.findModule("m1").isPresent());
@@ -1826,13 +1726,11 @@
      */
     @Test(expectedExceptions = { ResolutionException.class })
     public void testContainsService2() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .contains("p")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
+                .packages(Set.of("p"))
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("m1")
                 .uses("p.S")
                 .build();
@@ -1840,7 +1738,7 @@
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
 
         // m2 does not read a module that exports p
-        resolveRequires(finder, "m2");
+        resolve(finder, "m2");
     }
 
 
@@ -1848,16 +1746,14 @@
      * Test "provides p.S" where p is contained in the same module.
      */
     public void testContainsService3() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .contains("p")
-                .contains("q")
-                .provides("p.S", "q.S1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
+                .packages(Set.of("p", "q"))
+                .provides("p.S", List.of("q.S1"))
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf = resolveRequires(finder, "m1");
+        Configuration cf = resolve(finder, "m1");
 
         assertTrue(cf.modules().size() == 1);
         assertTrue(cf.findModule("m1").isPresent());
@@ -1869,22 +1765,19 @@
      */
     @Test(expectedExceptions = { ResolutionException.class })
     public void testContainsService4() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .contains("p")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
+                .packages(Set.of("p"))
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("m1")
-                .contains("q")
-                .provides("p.S", "q.S1")
+                .provides("p.S", List.of("q.S1"))
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
 
         // m2 does not read a module that exports p
-        resolveRequires(finder, "m2");
+        resolve(finder, "m2");
     }
 
 
@@ -1893,15 +1786,14 @@
      */
     @Test(expectedExceptions = { ResolutionException.class })
     public void testServiceTypePackageNotExported1() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .uses("p.S")
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1);
 
         // m1 does not read a module that exports p
-        resolveRequires(finder, "m1");
+        resolve(finder, "m1");
     }
 
 
@@ -1910,40 +1802,14 @@
      */
     @Test(expectedExceptions = { ResolutionException.class })
     public void testServiceTypePackageNotExported2() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .contains("q")
-                .provides("p.S", "q.T")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
+                .provides("p.S", List.of("q.T"))
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1);
 
         // m1 does not read a module that exports p
-        resolveRequires(finder, "m1");
-    }
-
-
-    /**
-     * Test "provides p.S with q.T" where q.T is not local
-     */
-    @Test(expectedExceptions = { ResolutionException.class })
-    public void testProviderPackageNotLocal() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .exports("p")
-                .exports("q")
-                .build();
-
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
-                .requires("m1")
-                .provides("p.S", "q.T")
-                .build();
-
-        ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
-
-        // q.T not in module m2
-        resolveRequires(finder, "m2");
+        resolve(finder, "m1");
     }
 
 
@@ -2007,34 +1873,17 @@
     @Test(dataProvider = "platformmatch")
     public void testPlatformMatch(String s1, String s2) {
 
-        ModuleDescriptor.Builder builder
-            = ModuleDescriptor.module("m1").requires("m2");
-
-        String[] s = s1.split("-");
-        if (!s[0].equals("*"))
-            builder.osName(s[0]);
-        if (!s[1].equals("*"))
-            builder.osArch(s[1]);
-        if (!s[2].equals("*"))
-            builder.osVersion(s[2]);
-
+        Builder builder = newBuilder("m1").requires("m2");
+        addPlatformConstraints(builder, s1);
         ModuleDescriptor descriptor1 = builder.build();
 
-        builder = ModuleDescriptor.module("m2");
-
-        s = s2.split("-");
-        if (!s[0].equals("*"))
-            builder.osName(s[0]);
-        if (!s[1].equals("*"))
-            builder.osArch(s[1]);
-        if (!s[2].equals("*"))
-            builder.osVersion(s[2]);
-
+        builder = newBuilder("m2");
+        addPlatformConstraints(builder, s2);
         ModuleDescriptor descriptor2 = builder.build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf = resolveRequires(finder, "m1");
+        Configuration cf = resolve(finder, "m1");
 
         assertTrue(cf.modules().size() == 2);
         assertTrue(cf.findModule("m1").isPresent());
@@ -2046,7 +1895,7 @@
      * platforms.
      */
     @Test(dataProvider = "platformmismatch",
-          expectedExceptions = ResolutionException.class )
+          expectedExceptions = FindException.class )
     public void testPlatformMisMatch(String s1, String s2) {
         testPlatformMatch(s1, s2);
     }
@@ -2057,16 +1906,67 @@
     @Test(expectedExceptions = { IllegalArgumentException.class })
     public void testResolveRequiresWithNoParents() {
         ModuleFinder empty = ModuleFinder.of();
-        Configuration.resolveRequires(empty, List.of(), empty, Set.of());
+        Configuration.resolve(empty, List.of(), empty, Set.of());
     }
 
     @Test(expectedExceptions = { IllegalArgumentException.class })
     public void testResolveRequiresAndUsesWithNoParents() {
         ModuleFinder empty = ModuleFinder.of();
-        Configuration.resolveRequiresAndUses(empty, List.of(), empty, Set.of());
+        Configuration.resolveAndBind(empty, List.of(), empty, Set.of());
     }
 
 
+    // parents with modules for specific platforms
+
+    @Test(dataProvider = "platformmatch")
+    public void testResolveRequiresWithCompatibleParents(String s1, String s2) {
+        Builder builder = newBuilder("m1");
+        addPlatformConstraints(builder, s1);
+        ModuleDescriptor descriptor1 = builder.build();
+
+        builder = newBuilder("m2");
+        addPlatformConstraints(builder, s2);
+        ModuleDescriptor descriptor2 = builder.build();
+
+        ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1);
+        Configuration cf1 = resolve(finder1, "m1");
+
+        ModuleFinder finder2 = ModuleUtils.finderOf(descriptor2);
+        Configuration cf2 = resolve(finder2, "m2");
+
+        Configuration cf3 = Configuration.resolve(ModuleFinder.of(),
+                                                  List.of(cf1, cf2),
+                                                  ModuleFinder.of(),
+                                                  Set.of());
+        assertTrue(cf3.parents().size() == 2);
+    }
+
+    @Test(dataProvider = "platformmismatch",
+          expectedExceptions = IllegalArgumentException.class )
+    public void testResolveRequiresWithConflictingParents(String s1, String s2) {
+        Builder builder = newBuilder("m1");
+        addPlatformConstraints(builder, s1);
+        ModuleDescriptor descriptor1 = builder.build();
+
+        builder = newBuilder("m2");
+        addPlatformConstraints(builder, s2);
+        ModuleDescriptor descriptor2 = builder.build();
+
+        ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1);
+        Configuration cf1 = resolve(finder1, "m1");
+
+        ModuleFinder finder2 = ModuleUtils.finderOf(descriptor2);
+        Configuration cf2 = resolve(finder2, "m2");
+
+        // should throw IAE
+        Configuration.resolve(ModuleFinder.of(),
+                              List.of(cf1, cf2),
+                              ModuleFinder.of(),
+                              Set.of());
+    }
+
+
+
     // null handling
 
     // finder1, finder2, roots
@@ -2074,72 +1974,72 @@
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testResolveRequiresWithNull1() {
-        resolveRequires((ModuleFinder)null, ModuleFinder.of());
+        resolve((ModuleFinder)null, ModuleFinder.of());
     }
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testResolveRequiresWithNull2() {
-        resolveRequires(ModuleFinder.of(), (ModuleFinder)null);
+        resolve(ModuleFinder.of(), (ModuleFinder)null);
     }
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testResolveRequiresWithNull3() {
         Configuration empty = Configuration.empty();
-        Configuration.resolveRequires(null, List.of(empty),  ModuleFinder.of(), Set.of());
+        Configuration.resolve(null, List.of(empty),  ModuleFinder.of(), Set.of());
     }
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testResolveRequiresWithNull4() {
         ModuleFinder empty = ModuleFinder.of();
-        Configuration.resolveRequires(empty, null, empty, Set.of());
+        Configuration.resolve(empty, null, empty, Set.of());
     }
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testResolveRequiresWithNull5() {
         Configuration cf = Layer.boot().configuration();
-        Configuration.resolveRequires(ModuleFinder.of(), List.of(cf), null, Set.of());
+        Configuration.resolve(ModuleFinder.of(), List.of(cf), null, Set.of());
     }
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testResolveRequiresWithNull6() {
         ModuleFinder empty = ModuleFinder.of();
         Configuration cf = Layer.boot().configuration();
-        Configuration.resolveRequires(empty, List.of(cf), empty, null);
+        Configuration.resolve(empty, List.of(cf), empty, null);
     }
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testResolveRequiresAndUsesWithNull1() {
-        resolveRequiresAndUses((ModuleFinder) null, ModuleFinder.of());
+        resolveAndBind((ModuleFinder) null, ModuleFinder.of());
     }
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testResolveRequiresAndUsesWithNull2() {
-        resolveRequiresAndUses(ModuleFinder.of(), (ModuleFinder) null);
+        resolveAndBind(ModuleFinder.of(), (ModuleFinder) null);
     }
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testResolveRequiresAndUsesWithNull3() {
         Configuration empty = Configuration.empty();
-        Configuration.resolveRequiresAndUses(null, List.of(empty), ModuleFinder.of(), Set.of());
+        Configuration.resolveAndBind(null, List.of(empty), ModuleFinder.of(), Set.of());
     }
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testResolveRequiresAndUsesWithNull4() {
         ModuleFinder empty = ModuleFinder.of();
-        Configuration.resolveRequiresAndUses(empty, null, empty, Set.of());
+        Configuration.resolveAndBind(empty, null, empty, Set.of());
     }
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testResolveRequiresAndUsesWithNull5() {
         Configuration cf = Layer.boot().configuration();
-        Configuration.resolveRequiresAndUses(ModuleFinder.of(), List.of(cf), null, Set.of());
+        Configuration.resolveAndBind(ModuleFinder.of(), List.of(cf), null, Set.of());
     }
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testResolveRequiresAndUsesWithNull6() {
         ModuleFinder empty = ModuleFinder.of();
         Configuration cf = Layer.boot().configuration();
-        Configuration.resolveRequiresAndUses(empty, List.of(cf), empty, null);
+        Configuration.resolveAndBind(empty, List.of(cf), empty, null);
     }
 
     @Test(expectedExceptions = { NullPointerException.class })
@@ -2165,58 +2065,58 @@
 
 
     /**
-     * Invokes parent.resolveRequires(...)
+     * Invokes parent.resolve(...)
      */
-    private Configuration resolveRequires(Configuration parent,
-                                          ModuleFinder before,
-                                          ModuleFinder after,
-                                          String... roots) {
-        return parent.resolveRequires(before, after, Set.of(roots));
+    private Configuration resolve(Configuration parent,
+                                  ModuleFinder before,
+                                  ModuleFinder after,
+                                  String... roots) {
+        return parent.resolve(before, after, Set.of(roots));
     }
 
-    private Configuration resolveRequires(Configuration parent,
-                                          ModuleFinder before,
-                                          String... roots) {
-        return resolveRequires(parent, before, ModuleFinder.of(), roots);
+    private Configuration resolve(Configuration parent,
+                                  ModuleFinder before,
+                                  String... roots) {
+        return resolve(parent, before, ModuleFinder.of(), roots);
     }
 
-    private Configuration resolveRequires(ModuleFinder before,
-                                          ModuleFinder after,
-                                          String... roots) {
-        return resolveRequires(Configuration.empty(), before, after, roots);
+    private Configuration resolve(ModuleFinder before,
+                                  ModuleFinder after,
+                                  String... roots) {
+        return resolve(Configuration.empty(), before, after, roots);
     }
 
-    private Configuration resolveRequires(ModuleFinder before,
-                                          String... roots) {
-        return resolveRequires(Configuration.empty(), before, roots);
+    private Configuration resolve(ModuleFinder before,
+                                  String... roots) {
+        return resolve(Configuration.empty(), before, roots);
     }
 
 
     /**
-     * Invokes parent.resolveRequiresAndUses(...)
+     * Invokes parent.resolveAndBind(...)
      */
-    private Configuration resolveRequiresAndUses(Configuration parent,
-                                                 ModuleFinder before,
-                                                 ModuleFinder after,
-                                                 String... roots) {
-        return parent.resolveRequiresAndUses(before, after, Set.of(roots));
+    private Configuration resolveAndBind(Configuration parent,
+                                         ModuleFinder before,
+                                         ModuleFinder after,
+                                         String... roots) {
+        return parent.resolveAndBind(before, after, Set.of(roots));
     }
 
-    private Configuration resolveRequiresAndUses(Configuration parent,
-                                                 ModuleFinder before,
-                                                 String... roots) {
-        return resolveRequiresAndUses(parent, before, ModuleFinder.of(), roots);
+    private Configuration resolveAndBind(Configuration parent,
+                                         ModuleFinder before,
+                                         String... roots) {
+        return resolveAndBind(parent, before, ModuleFinder.of(), roots);
     }
 
-    private Configuration resolveRequiresAndUses(ModuleFinder before,
-                                                 ModuleFinder after,
-                                                 String... roots) {
-        return resolveRequiresAndUses(Configuration.empty(), before, after, roots);
+    private Configuration resolveAndBind(ModuleFinder before,
+                                         ModuleFinder after,
+                                         String... roots) {
+        return resolveAndBind(Configuration.empty(), before, after, roots);
     }
 
-    private Configuration resolveRequiresAndUses(ModuleFinder before,
-                                                 String... roots) {
-        return resolveRequiresAndUses(Configuration.empty(), before, roots);
+    private Configuration resolveAndBind(ModuleFinder before,
+                                         String... roots) {
+        return resolveAndBind(Configuration.empty(), before, roots);
     }
 
 
@@ -2234,5 +2134,17 @@
                 .anyMatch(mn2::equals);
     }
 
-
+    /**
+     * Decodes the platform string and calls the builder osName/osArch/osVersion
+     * methods to set the platform constraints.
+     */
+    static void addPlatformConstraints(Builder builder, String platformString) {
+        String[] s = platformString.split("-");
+        if (!s[0].equals("*"))
+            builder.osName(s[0]);
+        if (!s[1].equals("*"))
+            builder.osArch(s[1]);
+        if (!s[2].equals("*"))
+            builder.osVersion(s[2]);
+    }
 }
--- a/jdk/test/java/lang/module/ModuleDescriptorTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/module/ModuleDescriptorTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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
@@ -24,6 +24,7 @@
 /**
  * @test
  * @modules java.base/jdk.internal.module
+ *          java.base/jdk.internal.misc
  * @run testng ModuleDescriptorTest
  * @summary Basic test for java.lang.module.ModuleDescriptor and its builder
  */
@@ -42,14 +43,19 @@
 import java.lang.module.ModuleDescriptor.Version;
 import java.lang.reflect.Module;
 import java.nio.ByteBuffer;
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.EnumSet;
 import java.util.HashSet;
+import java.util.Iterator;
 import java.util.List;
+import java.util.Objects;
 import java.util.Set;
+import java.util.stream.Collectors;
 
 import static java.lang.module.ModuleDescriptor.Requires.Modifier.*;
 
+import jdk.internal.misc.SharedSecrets;
 import jdk.internal.module.ModuleInfoWriter;
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
@@ -84,21 +90,27 @@
     // requires
 
     private Requires requires(Set<Modifier> mods, String mn) {
-        return ModuleDescriptor.module("m")
-            .requires(mods, mn)
-            .build()
-            .requires()
-            .iterator()
-            .next();
+        return requires(mods, mn, null);
     }
 
     private Requires requires(Set<Modifier> mods, String mn, Version v) {
-        return ModuleDescriptor.module("m")
-            .requires(mods, mn, v)
-            .build()
-            .requires()
-            .iterator()
-            .next();
+        Builder builder = ModuleDescriptor.newModule("m");
+        if (v == null) {
+            builder.requires(mods, mn);
+        } else {
+            builder.requires(mods, mn, v);
+        }
+        Set<Requires> requires = builder.build().requires();
+        assertTrue(requires.size() == 2);
+        Iterator<Requires> iterator = requires.iterator();
+        Requires r = iterator.next();
+        if (r.name().equals("java.base")) {
+            r = iterator.next();
+        } else {
+            Requires other = iterator.next();
+            assertEquals(other.name(), "java.base");
+        }
+        return r;
     }
 
     private Requires requires(String mn) {
@@ -107,7 +119,7 @@
 
     public void testRequiresWithRequires() {
         Requires r1 = requires("foo");
-        ModuleDescriptor descriptor = ModuleDescriptor.module("m").requires(r1).build();
+        ModuleDescriptor descriptor = ModuleDescriptor.newModule("m").requires(r1).build();
         Requires r2 = descriptor.requires().iterator().next();
         assertEquals(r1, r2);
     }
@@ -162,28 +174,28 @@
     @Test(expectedExceptions = IllegalStateException.class)
     public void testRequiresWithDuplicatesRequires() {
         Requires r = requires("foo");
-        ModuleDescriptor.module("m").requires(r).requires(r);
+        ModuleDescriptor.newModule("m").requires(r).requires(r);
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class)
     public void testRequiresSelfWithRequires() {
         Requires r = requires("foo");
-        ModuleDescriptor.module("foo").requires(r);
+        ModuleDescriptor.newModule("foo").requires(r);
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class)
     public void testRequiresSelfWithNoModifier() {
-        ModuleDescriptor.module("m").requires("m");
+        ModuleDescriptor.newModule("m").requires("m");
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class)
     public void testRequiresSelfWithOneModifier() {
-        ModuleDescriptor.module("m").requires(Set.of(TRANSITIVE), "m");
+        ModuleDescriptor.newModule("m").requires(Set.of(TRANSITIVE), "m");
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class)
     public void testRequiresSelfWithAllModifiers() {
-        ModuleDescriptor.module("m").requires(EnumSet.allOf(Modifier.class), "m");
+        ModuleDescriptor.newModule("m").requires(EnumSet.allOf(Modifier.class), "m");
     }
 
     @Test(dataProvider = "invalidjavaidentifiers",
@@ -194,17 +206,17 @@
 
     @Test(expectedExceptions = NullPointerException.class)
     public void testRequiresWithNullRequires() {
-        ModuleDescriptor.module("m").requires((Requires) null);
+        ModuleDescriptor.newModule("m").requires((Requires) null);
     }
 
     @Test(expectedExceptions = NullPointerException.class)
     public void testRequiresWithNullModifiers() {
-        ModuleDescriptor.module("m").requires(null, "foo");
+        ModuleDescriptor.newModule("m").requires(null, "foo");
     }
 
     @Test(expectedExceptions = NullPointerException.class)
     public void testRequiresWithNullVersion() {
-        ModuleDescriptor.module("m").requires(Set.of(), "foo", null);
+        ModuleDescriptor.newModule("m").requires(Set.of(), "foo", null);
     }
 
     public void testRequiresCompare() {
@@ -284,7 +296,7 @@
     // exports
 
     private Exports exports(Set<Exports.Modifier> mods, String pn) {
-        return ModuleDescriptor.module("foo")
+        return ModuleDescriptor.newModule("foo")
             .exports(mods, pn)
             .build()
             .exports()
@@ -297,7 +309,7 @@
     }
 
     private Exports exports(Set<Exports.Modifier> mods, String pn, String target) {
-        return ModuleDescriptor.module("foo")
+        return ModuleDescriptor.newModule("foo")
             .exports(mods, pn, Set.of(target))
             .build()
             .exports()
@@ -312,7 +324,7 @@
 
     public void testExportsExports() {
         Exports e1 = exports("p");
-        ModuleDescriptor descriptor = ModuleDescriptor.module("m").exports(e1).build();
+        ModuleDescriptor descriptor = ModuleDescriptor.newModule("m").exports(e1).build();
         Exports e2 = descriptor.exports().iterator().next();
         assertEquals(e1, e2);
     }
@@ -341,7 +353,7 @@
         targets.add("bar");
         targets.add("gus");
         Exports e
-            = ModuleDescriptor.module("foo")
+            = ModuleDescriptor.newModule("foo")
                 .exports("p", targets)
                 .build()
                 .exports()
@@ -380,69 +392,80 @@
     @Test(expectedExceptions = IllegalStateException.class)
     public void testExportsWithDuplicate1() {
         Exports e = exports("p");
-        ModuleDescriptor.module("foo").exports(e).exports(e);
+        ModuleDescriptor.newModule("foo").exports(e).exports(e);
     }
 
     @Test(expectedExceptions = IllegalStateException.class)
     public void testExportsWithDuplicate2() {
-        ModuleDescriptor.module("foo").exports("p").exports("p");
-    }
-
-    @Test(expectedExceptions = IllegalStateException.class)
-    public void testExportsOnContainedPackage() {
-        ModuleDescriptor.module("foo").contains("p").exports("p");
-    }
-
-    @Test(expectedExceptions = IllegalStateException.class)
-    public void testExportsToTargetOnContainedPackage() {
-        ModuleDescriptor.module("foo").contains("p").exports("p", Set.of("bar"));
+        ModuleDescriptor.newModule("foo").exports("p").exports("p");
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class )
     public void testExportsWithEmptySet() {
-        ModuleDescriptor.module("foo").exports("p", Collections.emptySet());
+        ModuleDescriptor.newModule("foo").exports("p", Collections.emptySet());
     }
 
     @Test(dataProvider = "invalidjavaidentifiers",
           expectedExceptions = IllegalArgumentException.class )
     public void testExportsWithBadName(String pn, String ignore) {
-        ModuleDescriptor.module("foo").exports(pn);
+        ModuleDescriptor.newModule("foo").exports(pn);
     }
 
     @Test(expectedExceptions = NullPointerException.class )
     public void testExportsWithNullExports() {
-        ModuleDescriptor.module("foo").exports((Exports) null);
+        ModuleDescriptor.newModule("foo").exports((Exports) null);
     }
 
     @Test(expectedExceptions = NullPointerException.class )
     public void testExportsWithNullTargets() {
-        ModuleDescriptor.module("foo").exports("p", (Set<String>) null);
+        ModuleDescriptor.newModule("foo").exports("p", (Set<String>) null);
     }
 
-    public void testExportsEqualsAndHashCode() {
-        Exports e1, e2;
+    public void testExportsCompare() {
+        Exports e1 = exports("p");
+        Exports e2 = exports("p");
+        assertEquals(e1, e2);
+        assertTrue(e1.hashCode() == e2.hashCode());
+        assertTrue(e1.compareTo(e2) == 0);
+        assertTrue(e2.compareTo(e1) == 0);
+    }
 
-        e1 = exports("p");
-        e2 = exports("p");
+    public void testExportsCompareWithSameModifiers() {
+        Exports e1 = exports(Set.of(Exports.Modifier.SYNTHETIC), "p");
+        Exports e2 = exports(Set.of(Exports.Modifier.SYNTHETIC), "p");
         assertEquals(e1, e2);
         assertTrue(e1.hashCode() == e2.hashCode());
+        assertTrue(e1.compareTo(e2) == 0);
+        assertTrue(e2.compareTo(e1) == 0);
+    }
 
-        e1 = exports(Set.of(Exports.Modifier.SYNTHETIC), "p");
-        e2 = exports(Set.of(Exports.Modifier.SYNTHETIC), "p");
+    public void testExportsCompareWithDifferentModifiers() {
+        Exports e1 = exports(Set.of(Exports.Modifier.SYNTHETIC), "p");
+        Exports e2 = exports("p");
+        assertNotEquals(e1, e2);
+        assertTrue(e1.compareTo(e2) == 1);
+        assertTrue(e2.compareTo(e1) == -1);
+    }
+
+    public void testExportsCompareWithSameTargets() {
+        Exports e1 = exports("p", "x");
+        Exports e2 = exports("p", "x");
         assertEquals(e1, e2);
         assertTrue(e1.hashCode() == e2.hashCode());
+        assertTrue(e1.compareTo(e2) == 0);
+        assertTrue(e2.compareTo(e1) == 0);
+    }
 
-        e1 = exports("p");
-        e2 = exports("q");
+    public void testExportsCompareWithDifferentTargets() {
+        Exports e1 = exports("p", "y");
+        Exports e2 = exports("p", "x");
         assertNotEquals(e1, e2);
-
-        e1 = exports(Set.of(Exports.Modifier.SYNTHETIC), "p");
-        e2 = exports(Set.of(), "p");
-        assertNotEquals(e1, e2);
+        assertTrue(e1.compareTo(e2) == 1);
+        assertTrue(e2.compareTo(e1) == -1);
     }
 
     public void testExportsToString() {
-        String s = ModuleDescriptor.module("foo")
+        String s = ModuleDescriptor.newModule("foo")
             .exports("p1", Set.of("bar"))
             .build()
             .exports()
@@ -457,7 +480,7 @@
     // opens
 
     private Opens opens(Set<Opens.Modifier> mods, String pn) {
-        return ModuleDescriptor.module("foo")
+        return ModuleDescriptor.newModule("foo")
                 .opens(mods, pn)
                 .build()
                 .opens()
@@ -470,7 +493,7 @@
     }
 
     private Opens opens(Set<Opens.Modifier> mods, String pn, String target) {
-        return ModuleDescriptor.module("foo")
+        return ModuleDescriptor.newModule("foo")
                 .opens(mods, pn, Set.of(target))
                 .build()
                 .opens()
@@ -484,7 +507,7 @@
 
     public void testOpensOpens() {
         Opens o1 = opens("p");
-        ModuleDescriptor descriptor = ModuleDescriptor.module("m").opens(o1).build();
+        ModuleDescriptor descriptor = ModuleDescriptor.newModule("m").opens(o1).build();
         Opens o2 = descriptor.opens().iterator().next();
         assertEquals(o1, o2);
     }
@@ -513,7 +536,7 @@
         Set<String> targets = new HashSet<>();
         targets.add("bar");
         targets.add("gus");
-        Opens o = ModuleDescriptor.module("foo")
+        Opens o = ModuleDescriptor.newModule("foo")
                 .opens("p", targets)
                 .build()
                 .opens()
@@ -528,98 +551,83 @@
         assertTrue(o.targets().contains("gus"));
     }
 
-    /*
-
-    public void testOpensToAllWithModifier() {
-        Exports e = exports(Set.of(Exports.Modifier.SYNTHETIC), "p");
-        assertEquals(e, e);
-        assertTrue(e.modifiers().size() == 1);
-        assertTrue(e.modifiers().contains(Exports.Modifier.SYNTHETIC));
-        assertEquals(e.source(), "p");
-        assertFalse(e.isQualified());
-        assertTrue(e.targets().isEmpty());
-    }
-
-    public void testOpensToTargetWithModifier() {
-        Exports e = exports(Set.of(Exports.Modifier.SYNTHETIC), "p", Set.of("bar"));
-        assertEquals(e, e);
-        assertTrue(e.modifiers().size() == 1);
-        assertTrue(e.modifiers().contains(Exports.Modifier.SYNTHETIC));
-        assertEquals(e.source(), "p");
-        assertTrue(e.isQualified());
-        assertTrue(e.targets().size() == 1);
-        assertTrue(e.targets().contains("bar"));
-    }
-
-
-    */
-
     @Test(expectedExceptions = IllegalStateException.class)
     public void testOpensWithDuplicate1() {
         Opens o = opens("p");
-        ModuleDescriptor.module("foo").opens(o).opens(o);
+        ModuleDescriptor.newModule("foo").opens(o).opens(o);
     }
 
     @Test(expectedExceptions = IllegalStateException.class)
     public void testOpensWithDuplicate2() {
-        ModuleDescriptor.module("foo").opens("p").opens("p");
-    }
-
-    @Test(expectedExceptions = IllegalStateException.class)
-    public void testOpensOnContainedPackage() {
-        ModuleDescriptor.module("foo").contains("p").opens("p");
-    }
-
-    @Test(expectedExceptions = IllegalStateException.class)
-    public void testOpensToTargetOnContainedPackage() {
-        ModuleDescriptor.module("foo").contains("p").opens("p", Set.of("bar"));
+        ModuleDescriptor.newModule("foo").opens("p").opens("p");
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class )
     public void testOpensWithEmptySet() {
-        ModuleDescriptor.module("foo").opens("p", Collections.emptySet());
+        ModuleDescriptor.newModule("foo").opens("p", Collections.emptySet());
     }
 
     @Test(dataProvider = "invalidjavaidentifiers",
             expectedExceptions = IllegalArgumentException.class )
     public void testOpensWithBadName(String pn, String ignore) {
-        ModuleDescriptor.module("foo").opens(pn);
+        ModuleDescriptor.newModule("foo").opens(pn);
     }
 
     @Test(expectedExceptions = NullPointerException.class )
     public void testOpensWithNullExports() {
-        ModuleDescriptor.module("foo").opens((Opens) null);
+        ModuleDescriptor.newModule("foo").opens((Opens) null);
     }
 
     @Test(expectedExceptions = NullPointerException.class )
     public void testOpensWithNullTargets() {
-        ModuleDescriptor.module("foo").opens("p", (Set<String>) null);
+        ModuleDescriptor.newModule("foo").opens("p", (Set<String>) null);
+    }
+
+    public void testOpensCompare() {
+        Opens o1 = opens("p");
+        Opens o2 = opens("p");
+        assertEquals(o1, o2);
+        assertTrue(o1.hashCode() == o2.hashCode());
+        assertTrue(o1.compareTo(o2) == 0);
+        assertTrue(o2.compareTo(o1) == 0);
+    }
+
+    public void testOpensCompareWithSameModifiers() {
+        Opens o1 = opens(Set.of(Opens.Modifier.SYNTHETIC), "p");
+        Opens o2 = opens(Set.of(Opens.Modifier.SYNTHETIC), "p");
+        assertEquals(o1, o2);
+        assertTrue(o1.hashCode() == o2.hashCode());
+        assertTrue(o1.compareTo(o2) == 0);
+        assertTrue(o2.compareTo(o1) == 0);
     }
 
-    public void testOpensEqualsAndHashCode() {
-        Opens o1, o2;
+    public void testOpensCompareWithDifferentModifiers() {
+        Opens o1 = opens(Set.of(Opens.Modifier.SYNTHETIC), "p");
+        Opens o2 = opens("p");
+        assertNotEquals(o1, o2);
+        assertTrue(o1.compareTo(o2) == 1);
+        assertTrue(o2.compareTo(o1) == -1);
+    }
 
-        o1 = opens("p");
-        o2 = opens("p");
-        assertEquals(o1, o2);
-        assertTrue(o1.hashCode() == o1.hashCode());
-
-        o1 = opens(Set.of(Opens.Modifier.SYNTHETIC), "p");
-        o2 = opens(Set.of(Opens.Modifier.SYNTHETIC), "p");
+    public void testOpensCompareWithSameTargets() {
+        Opens o1 = opens("p", "x");
+        Opens o2 = opens("p", "x");
         assertEquals(o1, o2);
         assertTrue(o1.hashCode() == o2.hashCode());
+        assertTrue(o1.compareTo(o2) == 0);
+        assertTrue(o2.compareTo(o1) == 0);
+    }
 
-        o1 = opens("p");
-        o2 = opens("q");
+    public void testOpensCompareWithDifferentTargets() {
+        Opens o1 = opens("p", "y");
+        Opens o2 = opens("p", "x");
         assertNotEquals(o1, o2);
-
-        o1 = opens(Set.of(Opens.Modifier.SYNTHETIC), "p");
-        o2 = opens(Set.of(), "p");
-        assertNotEquals(o1, o2);
+        assertTrue(o1.compareTo(o2) == 1);
+        assertTrue(o2.compareTo(o1) == -1);
     }
 
     public void testOpensToString() {
-        String s = ModuleDescriptor.module("foo")
+        String s = ModuleDescriptor.newModule("foo")
                 .opens("p1", Set.of("bar"))
                 .build()
                 .opens()
@@ -635,7 +643,7 @@
 
     public void testUses() {
         Set<String> uses
-            = ModuleDescriptor.module("foo")
+            = ModuleDescriptor.newModule("foo")
                 .uses("p.S")
                 .uses("q.S")
                 .build()
@@ -647,30 +655,44 @@
 
     @Test(expectedExceptions = IllegalStateException.class)
     public void testUsesWithDuplicate() {
-        ModuleDescriptor.module("foo").uses("p.S").uses("p.S");
+        ModuleDescriptor.newModule("foo").uses("p.S").uses("p.S");
+    }
+
+    @Test(expectedExceptions = IllegalArgumentException.class)
+    public void testUsesWithSimpleIdentifier() {
+        ModuleDescriptor.newModule("foo").uses("S");
     }
 
     @Test(dataProvider = "invalidjavaidentifiers",
           expectedExceptions = IllegalArgumentException.class )
     public void testUsesWithBadName(String service, String ignore) {
-        ModuleDescriptor.module("foo").uses(service);
+        ModuleDescriptor.newModule("foo").uses(service);
     }
 
 
     // provides
 
     private Provides provides(String st, String pc) {
-        return ModuleDescriptor.module("foo")
-            .provides(st, pc)
+        return ModuleDescriptor.newModule("foo")
+            .provides(st, List.of(pc))
             .build()
             .provides()
             .iterator()
             .next();
     }
 
+    private Provides provides(String st, List<String> pns) {
+        return ModuleDescriptor.newModule("foo")
+                .provides(st, pns)
+                .build()
+                .provides()
+                .iterator()
+                .next();
+    }
+
     public void testProvidesWithProvides() {
         Provides p1 = provides("p.S", "q.S1");
-        ModuleDescriptor descriptor = ModuleDescriptor.module("m")
+        ModuleDescriptor descriptor = ModuleDescriptor.newModule("m")
                 .provides(p1)
                 .build();
         Provides p2 = descriptor.provides().iterator().next();
@@ -679,7 +701,7 @@
 
 
     public void testProvides() {
-        Set<Provides> set = ModuleDescriptor.module("foo")
+        Set<Provides> set = ModuleDescriptor.newModule("foo")
                 .provides("p.S", List.of("q.P1", "q.P2"))
                 .build()
                 .provides();
@@ -696,59 +718,86 @@
     @Test(expectedExceptions = IllegalStateException.class )
     public void testProvidesWithDuplicateProvides() {
         Provides p = provides("p.S", "q.S2");
-        ModuleDescriptor.module("m").provides("p.S", "q.S1").provides(p);
+        ModuleDescriptor.newModule("m").provides("p.S", List.of("q.S1")).provides(p);
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class )
     public void testProvidesWithEmptySet() {
-        ModuleDescriptor.module("foo").provides("p.Service", Collections.emptyList());
+        ModuleDescriptor.newModule("foo").provides("p.Service", Collections.emptyList());
+    }
+
+    @Test(expectedExceptions = IllegalArgumentException.class )
+    public void testProvidesWithSimpleIdentifier1() {
+        ModuleDescriptor.newModule("foo").provides("S", List.of("q.P"));
+    }
+
+    @Test(expectedExceptions = IllegalArgumentException.class )
+    public void testProvidesWithSimpleIdentifier2() {
+        ModuleDescriptor.newModule("foo").provides("p.S", List.of("P"));
     }
 
     @Test(dataProvider = "invalidjavaidentifiers",
           expectedExceptions = IllegalArgumentException.class )
     public void testProvidesWithBadService(String service, String ignore) {
-        ModuleDescriptor.module("foo").provides(service, "p.Provider");
+        ModuleDescriptor.newModule("foo").provides(service, List.of("p.Provider"));
     }
 
     @Test(dataProvider = "invalidjavaidentifiers",
           expectedExceptions = IllegalArgumentException.class )
     public void testProvidesWithBadProvider(String provider, String ignore) {
-        ModuleDescriptor.module("foo").provides("p.Service", provider);
+        List<String> names = new ArrayList<>(); // allows nulls
+        names.add(provider);
+        ModuleDescriptor.newModule("foo").provides("p.Service", names);
     }
 
     @Test(expectedExceptions = NullPointerException.class )
     public void testProvidesWithNullProvides() {
-        ModuleDescriptor.module("foo").provides((Provides) null);
+        ModuleDescriptor.newModule("foo").provides((Provides) null);
     }
 
     @Test(expectedExceptions = NullPointerException.class )
     public void testProvidesWithNullProviders() {
-        ModuleDescriptor.module("foo").provides("p.S", (List<String>) null);
+        ModuleDescriptor.newModule("foo").provides("p.S", (List<String>) null);
     }
 
-    public void testProvidesEqualsAndHashCode() {
-        Provides p1, p2;
-
-        p1 = provides("p.S", "q.S1");
-        p2 = provides("p.S", "q.S1");
+    public void testProvidesCompare() {
+        Provides p1 = provides("p.S", "q.S1");
+        Provides p2 = provides("p.S", "q.S1");
         assertEquals(p1, p2);
         assertTrue(p1.hashCode() == p2.hashCode());
+        assertTrue(p1.compareTo(p2) == 0);
+        assertTrue(p2.compareTo(p1) == 0);
+    }
 
-        p1 = provides("p.S", "q.S1");
-        p2 = provides("p.S", "q.S2");
+    public void testProvidesCompareWithDifferentService() {
+        Provides p1 = provides("p.S2", "q.S1");
+        Provides p2 = provides("p.S1", "q.S1");
         assertNotEquals(p1, p2);
-
-        p1 = provides("p.S", "q.S1");
-        p2 = provides("p.S2", "q.S1");
-        assertNotEquals(p1, p2);
+        assertTrue(p1.compareTo(p2) == 1);
+        assertTrue(p2.compareTo(p1) == -1);
     }
 
-    // contains
+    public void testProvidesCompareWithDifferentProviders1() {
+        Provides p1 = provides("p.S", "q.S2");
+        Provides p2 = provides("p.S", "q.S1");
+        assertNotEquals(p1, p2);
+        assertTrue(p1.compareTo(p2) == 1);
+        assertTrue(p2.compareTo(p1) == -1);
+    }
 
-    public void testContains() {
-        Set<String> packages = ModuleDescriptor.module("foo")
-                .contains("p")
-                .contains("q")
+    public void testProvidesCompareWithDifferentProviders2() {
+        Provides p1 = provides("p.S", List.of("q.S1", "q.S2"));
+        Provides p2 = provides("p.S", "q.S1");
+        assertNotEquals(p1, p2);
+        assertTrue(p1.compareTo(p2) == 1);
+        assertTrue(p2.compareTo(p1) == -1);
+    }
+
+    // packages
+
+    public void testPackages1() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .packages(Set.of("p", "q"))
                 .build()
                 .packages();
         assertTrue(packages.size() == 2);
@@ -756,37 +805,10 @@
         assertTrue(packages.contains("q"));
     }
 
-    public void testContainsWithEmptySet() {
-        Set<String> packages = ModuleDescriptor.module("foo")
-                .contains(Collections.emptySet())
-                .build()
-                .packages();
-        assertTrue(packages.size() == 0);
-    }
-
-    @Test(expectedExceptions = IllegalStateException.class)
-    public void testContainsWithDuplicate() {
-        ModuleDescriptor.module("foo").contains("p").contains("p");
-    }
-
-    @Test(expectedExceptions = IllegalStateException.class)
-    public void testContainsWithExportedPackage() {
-        ModuleDescriptor.module("foo").exports("p").contains("p");
-    }
-
-    @Test(dataProvider = "invalidjavaidentifiers",
-          expectedExceptions = IllegalArgumentException.class )
-    public void testContainsWithBadName(String pn, String ignore) {
-        ModuleDescriptor.module("foo").contains(pn);
-    }
-
-
-    // packages
-
-    public void testPackages() {
-        Set<String> packages = ModuleDescriptor.module("foo")
-                .exports("p")
-                .contains("q")
+    public void testPackages2() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .packages(Set.of("p"))
+                .packages(Set.of("q"))
                 .build()
                 .packages();
         assertTrue(packages.size() == 2);
@@ -795,17 +817,135 @@
     }
 
 
+    public void testPackagesWithEmptySet() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .packages(Collections.emptySet())
+                .build()
+                .packages();
+        assertTrue(packages.size() == 0);
+    }
+
+    public void testPackagesDuplicate() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .packages(Set.of("p"))
+                .packages(Set.of("p"))
+                .build()
+                .packages();
+        assertTrue(packages.size() == 1);
+        assertTrue(packages.contains("p"));
+    }
+
+    public void testPackagesAndExportsPackage1() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .packages(Set.of("p"))
+                .exports("p")
+                .build()
+                .packages();
+        assertTrue(packages.size() == 1);
+        assertTrue(packages.contains("p"));
+    }
+
+    public void testPackagesAndExportsPackage2() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .exports("p")
+                .packages(Set.of("p"))
+                .build()
+                .packages();
+        assertTrue(packages.size() == 1);
+        assertTrue(packages.contains("p"));
+    }
+
+    public void testPackagesAndOpensPackage1() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .packages(Set.of("p"))
+                .opens("p")
+                .build()
+                .packages();
+        assertTrue(packages.size() == 1);
+        assertTrue(packages.contains("p"));
+    }
+
+    public void testPackagesAndOpensPackage2() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .opens("p")
+                .packages(Set.of("p"))
+                .build()
+                .packages();
+        assertTrue(packages.size() == 1);
+        assertTrue(packages.contains("p"));
+    }
+
+    public void testPackagesAndProvides1() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .packages(Set.of("p"))
+                .provides("q.S", List.of("p.T"))
+                .build()
+                .packages();
+        assertTrue(packages.size() == 1);
+        assertTrue(packages.contains("p"));
+    }
+
+    public void testPackagesAndProvides2() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .provides("q.S", List.of("p.T"))
+                .packages(Set.of("p"))
+                .build()
+                .packages();
+        assertTrue(packages.size() == 1);
+        assertTrue(packages.contains("p"));
+    }
+
+    public void testPackagesAndMainClass1() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .packages(Set.of("p"))
+                .mainClass("p.Main")
+                .build()
+                .packages();
+        assertTrue(packages.size() == 1);
+        assertTrue(packages.contains("p"));
+    }
+
+    public void testPackagesAndMainClass2() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .mainClass("p.Main")
+                .packages(Set.of("p"))
+                .build()
+                .packages();
+        assertTrue(packages.size() == 1);
+        assertTrue(packages.contains("p"));
+    }
+
+    public void testPackagesAndAll() {
+        Set<String> packages = ModuleDescriptor.newModule("foo")
+                .exports("p1")
+                .opens("p2")
+                .packages(Set.of("p3"))
+                .provides("q.S", List.of("p4.T"))
+                .mainClass("p5.Main")
+                .build()
+                .packages();
+        assertTrue(Objects.equals(packages, Set.of("p1", "p2", "p3", "p4", "p5")));
+    }
+
+    @Test(dataProvider = "invalidjavaidentifiers",
+          expectedExceptions = IllegalArgumentException.class )
+    public void testPackagesWithBadName(String pn, String ignore) {
+        Set<String> pkgs = new HashSet<>();  // allows nulls
+        pkgs.add(pn);
+        ModuleDescriptor.newModule("foo").packages(pkgs);
+    }
+
     // name
 
     public void testModuleName() {
-        String mn = ModuleDescriptor.module("foo").build().name();
+        String mn = ModuleDescriptor.newModule("foo").build().name();
         assertEquals(mn, "foo");
     }
 
     @Test(dataProvider = "invalidjavaidentifiers",
           expectedExceptions = IllegalArgumentException.class )
     public void testBadModuleName(String mn, String ignore) {
-        ModuleDescriptor.module(mn);
+        ModuleDescriptor.newModule(mn);
     }
 
 
@@ -813,7 +953,7 @@
 
     public void testVersion1() {
         Version v1 = Version.parse("1.0");
-        Version v2 = ModuleDescriptor.module("foo")
+        Version v2 = ModuleDescriptor.newModule("foo")
                 .version(v1)
                 .build()
                 .version()
@@ -823,7 +963,7 @@
 
     public void testVersion2() {
         String vs = "1.0";
-        Version v1 = ModuleDescriptor.module("foo")
+        Version v1 = ModuleDescriptor.newModule("foo")
                 .version(vs)
                 .build()
                 .version()
@@ -834,86 +974,178 @@
 
     @Test(expectedExceptions = NullPointerException.class )
     public void testNullVersion1() {
-        ModuleDescriptor.module("foo").version((Version) null);
+        ModuleDescriptor.newModule("foo").version((Version) null);
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class )
     public void testNullVersion2() {
-        ModuleDescriptor.module("foo").version((String) null);
+        ModuleDescriptor.newModule("foo").version((String) null);
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class )
     public void testEmptyVersion() {
-        ModuleDescriptor.module("foo").version("");
+        ModuleDescriptor.newModule("foo").version("");
     }
 
 
     // toNameAndVersion
 
     public void testToNameAndVersion() {
-        ModuleDescriptor md1 = ModuleDescriptor.module("foo").build();
+        ModuleDescriptor md1 = ModuleDescriptor.newModule("foo").build();
         assertEquals(md1.toNameAndVersion(), "foo");
 
-        ModuleDescriptor md2 = ModuleDescriptor.module("foo").version("1.0").build();
+        ModuleDescriptor md2 = ModuleDescriptor.newModule("foo").version("1.0").build();
         assertEquals(md2.toNameAndVersion(), "foo@1.0");
     }
 
 
     // open modules
 
-    public void testOpenModules() {
-        ModuleDescriptor descriptor = ModuleDescriptor.openModule("m")
-                .requires("java.base")
-                .contains("p")
+    public void testOpenModule() {
+        ModuleDescriptor descriptor = ModuleDescriptor.newOpenModule("foo")
+                .requires("bar")
+                .exports("p")
+                .provides("p.Service", List.of("q.ServiceImpl"))
                 .build();
+
+        // modifiers
+        assertTrue(descriptor.modifiers().contains(ModuleDescriptor.Modifier.OPEN));
         assertTrue(descriptor.isOpen());
-        assertTrue(descriptor.packages().size() == 1);
-        assertTrue(descriptor.packages().contains("p"));
-        assertTrue(descriptor.exports().isEmpty());
+
+        // requires
+        assertTrue(descriptor.requires().size() == 2);
+        Set<String> names = descriptor.requires()
+                .stream()
+                .map(Requires::name)
+                .collect(Collectors.toSet());
+        assertEquals(names, Set.of("bar", "java.base"));
+
+        // packages
+        assertEquals(descriptor.packages(), Set.of("p", "q"));
+
+        // exports
+        assertTrue(descriptor.exports().size() == 1);
+        names = descriptor.exports()
+                .stream()
+                .map(Exports::source)
+                .collect(Collectors.toSet());
+        assertEquals(names, Set.of("p"));
+
+        // opens
+        assertTrue(descriptor.opens().isEmpty());
     }
 
     @Test(expectedExceptions = IllegalStateException.class)
-    public void testOpensOnWeakModule1() {
-        ModuleDescriptor.openModule("foo").opens("p");
+    public void testOpensOnOpenModule1() {
+        ModuleDescriptor.newOpenModule("foo").opens("p");
     }
 
     @Test(expectedExceptions = IllegalStateException.class)
-    public void testOpensOnWeakModule2() {
-        ModuleDescriptor.openModule("foo").opens("p", Set.of("bar"));
+    public void testOpensOnOpenModule2() {
+        ModuleDescriptor.newOpenModule("foo").opens("p", Set.of("bar"));
     }
 
     public void testIsOpen() {
-        assertFalse(ModuleDescriptor.module("m").build().isOpen());
-        assertFalse(ModuleDescriptor.automaticModule("m").build().isOpen());
-        assertTrue(ModuleDescriptor.openModule("m").build().isOpen());
+        assertFalse(ModuleDescriptor.newModule("m").build().isOpen());
+        assertFalse(ModuleDescriptor.newAutomaticModule("m").build().isOpen());
+        assertTrue(ModuleDescriptor.newOpenModule("m").build().isOpen());
     }
 
 
     // automatic modules
 
+    public void testAutomaticModule() {
+        ModuleDescriptor descriptor = ModuleDescriptor.newAutomaticModule("foo")
+                .packages(Set.of("p"))
+                .provides("p.Service", List.of("q.ServiceImpl"))
+                .build();
+
+        // modifiers
+        assertTrue(descriptor.modifiers().contains(ModuleDescriptor.Modifier.AUTOMATIC));
+        assertTrue(descriptor.isAutomatic());
+
+        // requires
+        assertTrue(descriptor.requires().size() == 1);
+        Set<String> names = descriptor.requires()
+                .stream()
+                .map(Requires::name)
+                .collect(Collectors.toSet());
+        assertEquals(names, Set.of("java.base"));
+
+        // packages
+        assertEquals(descriptor.packages(), Set.of("p", "q"));
+        assertTrue(descriptor.exports().isEmpty());
+        assertTrue(descriptor.opens().isEmpty());
+    }
+
+    @Test(expectedExceptions = IllegalStateException.class)
+    public void testRequiresOnAutomaticModule() {
+        ModuleDescriptor.newAutomaticModule("foo").requires("java.base");
+    }
+
+    @Test(expectedExceptions = IllegalStateException.class)
+    public void testExportsOnAutomaticModule1() {
+        ModuleDescriptor.newAutomaticModule("foo").exports("p");
+    }
+
+    @Test(expectedExceptions = IllegalStateException.class)
+    public void testExportsOnAutomaticModule2() {
+        ModuleDescriptor.newAutomaticModule("foo").exports("p", Set.of("bar"));
+    }
+
+    @Test(expectedExceptions = IllegalStateException.class)
+    public void testOpensOnAutomaticModule1() {
+        ModuleDescriptor.newAutomaticModule("foo").opens("p");
+    }
+
+    @Test(expectedExceptions = IllegalStateException.class)
+    public void testOpensOnAutomaticModule2() {
+        ModuleDescriptor.newAutomaticModule("foo").opens("p", Set.of("bar"));
+    }
+
+    @Test(expectedExceptions = IllegalStateException.class)
+    public void testUsesOnAutomaticModule() {
+        ModuleDescriptor.newAutomaticModule("foo").uses("p.Service");
+    }
+
     public void testIsAutomatic() {
-        ModuleDescriptor descriptor1 = ModuleDescriptor.module("foo").build();
+        ModuleDescriptor descriptor1 = ModuleDescriptor.newModule("foo").build();
         assertFalse(descriptor1.isAutomatic());
 
-        ModuleDescriptor descriptor2 = ModuleDescriptor.openModule("foo").build();
+        ModuleDescriptor descriptor2 = ModuleDescriptor.newOpenModule("foo").build();
         assertFalse(descriptor2.isAutomatic());
 
-        ModuleDescriptor descriptor3 = ModuleDescriptor.automaticModule("foo").build();
+        ModuleDescriptor descriptor3 = ModuleDescriptor.newAutomaticModule("foo").build();
         assertTrue(descriptor3.isAutomatic());
     }
 
-    // isSynthetic
-    public void testIsSynthetic() {
-        assertFalse(Object.class.getModule().getDescriptor().isSynthetic());
+
+    // newModule with modifiers
+
+    public void testNewModuleToBuildAutomaticModule() {
+        Set<ModuleDescriptor.Modifier> ms = Set.of(ModuleDescriptor.Modifier.AUTOMATIC);
+        ModuleDescriptor descriptor = ModuleDescriptor.newModule("foo", ms).build();
+        assertTrue(descriptor.modifiers().equals(ms));
+        assertTrue(descriptor.isAutomatic());
+    }
 
-        ModuleDescriptor descriptor1 = ModuleDescriptor.module("foo").build();
-        assertFalse(descriptor1.isSynthetic());
+    public void testNewModuleToBuildOpenModule() {
+        Set<ModuleDescriptor.Modifier> ms = Set.of(ModuleDescriptor.Modifier.OPEN);
+        ModuleDescriptor descriptor = ModuleDescriptor.newModule("foo", ms).build();
+        assertTrue(descriptor.modifiers().equals(ms));
+        assertTrue(descriptor.isOpen());
 
-        ModuleDescriptor descriptor2 = ModuleDescriptor.openModule("foo").build();
-        assertFalse(descriptor2.isSynthetic());
+        ms = Set.of(ModuleDescriptor.Modifier.OPEN, ModuleDescriptor.Modifier.SYNTHETIC);
+        descriptor = ModuleDescriptor.newModule("foo", ms).build();
+        assertTrue(descriptor.modifiers().equals(ms));
+        assertTrue(descriptor.isOpen());
+    }
 
-        ModuleDescriptor descriptor3 = ModuleDescriptor.automaticModule("foo").build();
-        assertFalse(descriptor3.isSynthetic());
+    @Test(expectedExceptions = IllegalArgumentException.class)
+    public void testNewModuleToBuildAutomaticAndOpenModule() {
+        Set<ModuleDescriptor.Modifier> ms = Set.of(ModuleDescriptor.Modifier.AUTOMATIC,
+                                                   ModuleDescriptor.Modifier.OPEN);
+        ModuleDescriptor.newModule("foo", ms);
     }
 
 
@@ -921,14 +1153,19 @@
 
     public void testMainClass() {
         String mainClass
-            = ModuleDescriptor.module("foo").mainClass("p.Main").build().mainClass().get();
+            = ModuleDescriptor.newModule("foo").mainClass("p.Main").build().mainClass().get();
         assertEquals(mainClass, "p.Main");
     }
 
+    @Test(expectedExceptions = IllegalArgumentException.class)
+    public void testMainClassWithSimpleIdentifier() {
+        ModuleDescriptor.newModule("foo").mainClass("Main");
+    }
+
     @Test(dataProvider = "invalidjavaidentifiers",
           expectedExceptions = IllegalArgumentException.class )
     public void testMainClassWithBadName(String mainClass, String ignore) {
-        Builder builder = ModuleDescriptor.module("foo");
+        Builder builder = ModuleDescriptor.newModule("foo");
         builder.mainClass(mainClass);
     }
 
@@ -936,54 +1173,54 @@
     // osName
 
     public void testOsName() {
-        String osName = ModuleDescriptor.module("foo").osName("Linux").build().osName().get();
+        String osName = ModuleDescriptor.newModule("foo").osName("Linux").build().osName().get();
         assertEquals(osName, "Linux");
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class)
     public void testNullOsName() {
-        ModuleDescriptor.module("foo").osName(null);
+        ModuleDescriptor.newModule("foo").osName(null);
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class)
     public void testEmptyOsName() {
-        ModuleDescriptor.module("foo").osName("");
+        ModuleDescriptor.newModule("foo").osName("");
     }
 
 
     // osArch
 
     public void testOsArch() {
-        String osArch = ModuleDescriptor.module("foo").osName("arm").build().osName().get();
+        String osArch = ModuleDescriptor.newModule("foo").osName("arm").build().osName().get();
         assertEquals(osArch, "arm");
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class)
     public void testNullOsArch() {
-        ModuleDescriptor.module("foo").osArch(null);
+        ModuleDescriptor.newModule("foo").osArch(null);
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class)
     public void testEmptyOsArch() {
-        ModuleDescriptor.module("foo").osArch("");
+        ModuleDescriptor.newModule("foo").osArch("");
     }
 
 
     // osVersion
 
     public void testOsVersion() {
-        String osVersion = ModuleDescriptor.module("foo").osName("11.2").build().osName().get();
+        String osVersion = ModuleDescriptor.newModule("foo").osName("11.2").build().osName().get();
         assertEquals(osVersion, "11.2");
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class)
     public void testNullOsVersion() {
-        ModuleDescriptor.module("foo").osVersion(null);
+        ModuleDescriptor.newModule("foo").osVersion(null);
     }
 
     @Test(expectedExceptions = IllegalArgumentException.class)
     public void testEmptyOsVersion() {
-        ModuleDescriptor.module("foo").osVersion("");
+        ModuleDescriptor.newModule("foo").osVersion("");
     }
 
     // reads
@@ -1023,7 +1260,7 @@
      * Test ModuleDescriptor with a packager finder
      */
     public void testReadsWithPackageFinder() throws Exception {
-        ModuleDescriptor descriptor = ModuleDescriptor.module("foo")
+        ModuleDescriptor descriptor = ModuleDescriptor.newModule("foo")
                 .requires("java.base")
                 .build();
 
@@ -1044,7 +1281,7 @@
      */
     @Test(expectedExceptions = InvalidModuleDescriptorException.class)
     public void testReadsWithBadPackageFinder() throws Exception {
-        ModuleDescriptor descriptor = ModuleDescriptor.module("foo")
+        ModuleDescriptor descriptor = ModuleDescriptor.newModule("foo")
                 .requires("java.base")
                 .exports("p")
                 .build();
@@ -1077,7 +1314,7 @@
     @Test(expectedExceptions = InvalidModuleDescriptorException.class)
     public void testReadOfJavaBaseWithRequires() {
         ModuleDescriptor descriptor
-            = ModuleDescriptor.module("java.base")
+            = ModuleDescriptor.newModule("java.base")
                 .requires("other")
                 .build();
         ByteBuffer bb = ModuleInfoWriter.toByteBuffer(descriptor);
@@ -1087,7 +1324,8 @@
     // The requires table must have an entry for java.base
     @Test(expectedExceptions = InvalidModuleDescriptorException.class)
     public void testReadWithEmptyRequires() {
-        ModuleDescriptor descriptor = ModuleDescriptor.module("m1").build();
+        ModuleDescriptor descriptor = SharedSecrets.getJavaLangModuleAccess()
+                .newModuleBuilder("m1", false, Set.of()).build();
         ByteBuffer bb = ModuleInfoWriter.toByteBuffer(descriptor);
         ModuleDescriptor.read(bb);
     }
@@ -1095,10 +1333,8 @@
     // The requires table must have an entry for java.base
     @Test(expectedExceptions = InvalidModuleDescriptorException.class)
     public void testReadWithNoRequiresBase() {
-        ModuleDescriptor descriptor
-            = ModuleDescriptor.module("m1")
-                .requires("m2")
-                .build();
+        ModuleDescriptor descriptor = SharedSecrets.getJavaLangModuleAccess()
+                .newModuleBuilder("m1", false, Set.of()).requires("m2").build();
         ByteBuffer bb = ModuleInfoWriter.toByteBuffer(descriptor);
         ModuleDescriptor.read(bb);
     }
@@ -1138,22 +1374,50 @@
     // equals/hashCode/compareTo/toString
 
     public void testEqualsAndHashCode() {
-        ModuleDescriptor md1 = ModuleDescriptor.module("foo").build();
-        ModuleDescriptor md2 = ModuleDescriptor.module("foo").build();
+        ModuleDescriptor md1 = ModuleDescriptor.newModule("m").build();
+        ModuleDescriptor md2 = ModuleDescriptor.newModule("m").build();
         assertEquals(md1, md1);
         assertEquals(md1.hashCode(), md2.hashCode());
+        assertTrue(md1.compareTo(md2) == 0);
+        assertTrue(md2.compareTo(md1) == 0);
     }
 
-    public void testCompare() {
-        ModuleDescriptor md1 = ModuleDescriptor.module("foo").build();
-        ModuleDescriptor md2 = ModuleDescriptor.module("bar").build();
-        int n = "foo".compareTo("bar");
-        assertTrue(md1.compareTo(md2) == n);
-        assertTrue(md2.compareTo(md1) == -n);
+    @DataProvider(name = "sortedModuleDescriptors")
+    public Object[][] sortedModuleDescriptors() {
+        return new Object[][]{
+
+            { ModuleDescriptor.newModule("m2").build(),
+              ModuleDescriptor.newModule("m1").build()
+            },
+
+            { ModuleDescriptor.newModule("m").version("2").build(),
+              ModuleDescriptor.newModule("m").version("1").build()
+            },
+
+            { ModuleDescriptor.newModule("m").version("1").build(),
+              ModuleDescriptor.newModule("m").build()
+            },
+
+            { ModuleDescriptor.newOpenModule("m").build(),
+              ModuleDescriptor.newModule("m").build()
+            },
+
+        };
+    }
+
+    @Test(dataProvider = "sortedModuleDescriptors")
+    public void testCompare(ModuleDescriptor md1, ModuleDescriptor md2) {
+        assertNotEquals(md1, md2);
+        assertTrue(md1.compareTo(md2) == 1);
+        assertTrue(md2.compareTo(md1) == -1);
     }
 
     public void testToString() {
-        String s = ModuleDescriptor.module("m1").requires("m2").exports("p1").build().toString();
+        String s = ModuleDescriptor.newModule("m1")
+                .requires("m2")
+                .exports("p1")
+                .build()
+                .toString();
         assertTrue(s.contains("m1"));
         assertTrue(s.contains("m2"));
         assertTrue(s.contains("p1"));
--- a/jdk/test/java/lang/module/ModuleFinderTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/module/ModuleFinderTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -471,37 +471,11 @@
      * Test ModuleFinder.of with a file path to a directory containing a file
      * that will not be recognized as a module.
      */
-    public void testOfWithUnrecognizedEntryInDirectory() throws Exception {
+    public void testOfWithUnrecognizedEntryInDirectory1() throws Exception {
         Path dir = Files.createTempDirectory(USER_DIR, "mods");
         Files.createTempFile(dir, "m", ".junk");
 
         ModuleFinder finder = ModuleFinder.of(dir);
-        try {
-            finder.find("java.rhubarb");
-            assertTrue(false);
-        } catch (FindException e) {
-            // expected
-        }
-
-        finder = ModuleFinder.of(dir);
-        try {
-            finder.findAll();
-            assertTrue(false);
-        } catch (FindException e) {
-            // expected
-        }
-    }
-
-
-    /**
-     * Test ModuleFinder.of with a file path to a directory containing a file
-     * starting with ".", the file should be ignored.
-     */
-    public void testOfWithHiddenEntryInDirectory() throws Exception {
-        Path dir = Files.createTempDirectory(USER_DIR, "mods");
-        Files.createTempFile(dir, ".marker", "");
-
-        ModuleFinder finder = ModuleFinder.of(dir);
         assertFalse(finder.find("java.rhubarb").isPresent());
 
         finder = ModuleFinder.of(dir);
@@ -510,6 +484,24 @@
 
 
     /**
+     * Test ModuleFinder.of with a file path to a directory containing a file
+     * that will not be recognized as a module.
+     */
+    public void testOfWithUnrecognizedEntryInDirectory2() throws Exception {
+        Path dir = Files.createTempDirectory(USER_DIR, "mods");
+        createModularJar(dir.resolve("m1.jar"), "m1");
+        Files.createTempFile(dir, "m2", ".junk");
+
+        ModuleFinder finder = ModuleFinder.of(dir);
+        assertTrue(finder.find("m1").isPresent());
+        assertFalse(finder.find("m2").isPresent());
+
+        finder = ModuleFinder.of(dir);
+        assertTrue(finder.findAll().size() == 1);
+    }
+
+
+    /**
      * Test ModuleFinder.of with a directory that contains two
      * versions of the same module
      */
@@ -748,7 +740,7 @@
             vs = mid.substring(i+1);
         }
         ModuleDescriptor.Builder builder
-            = ModuleDescriptor.module(mn).requires("java.base");
+            = ModuleDescriptor.newModule(mn).requires("java.base");
         if (vs != null)
             builder.version(vs);
         return builder.build();
--- a/jdk/test/java/lang/module/ModuleNamesTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/module/ModuleNamesTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -235,7 +235,7 @@
      */
     private Builder newBuilder(String mn) {
         return SharedSecrets.getJavaLangModuleAccess()
-                            .newModuleBuilder(mn, false, false, false);
+                            .newModuleBuilder(mn, false, Set.of());
     }
 
     /**
--- a/jdk/test/java/lang/module/ModuleReader/ModuleReaderTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/module/ModuleReader/ModuleReaderTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -79,14 +79,52 @@
         "java/lang/Object.class"
     };
 
+    // resource names that should not be found in the base module
+    private static final String[] BAD_BASE_RESOURCES = {
+        "NotFound",
+        "java",
+        "/java",
+        "//java",
+        "java/",
+        "java/lang",
+        "/java/lang",
+        "//java/lang",
+        "java/lang/",
+        "java//lang",
+        "/java/lang/Object.class",
+        "//java/lang/Object.class",
+        "java/lang/Object.class/",
+        "java//lang//Object.class",
+        "./java/lang/Object.class",
+        "java/./lang/Object.class",
+        "java/lang/./Object.class",
+        "../java/lang/Object.class",
+        "java/../lang/Object.class",
+        "java/lang/../Object.class",
+    };
+
     // resources in test module (can't use module-info.class as a test
     // resource as it will be modified by the jmod tool)
     private static final String[] TEST_RESOURCES = {
         "p/Main.class"
     };
 
-    // a resource that is not in the base or test module
-    private static final String NOT_A_RESOURCE = "NotAResource";
+    // resource names that should not be found in the test module
+    private static final String[] BAD_TEST_RESOURCES = {
+        "NotFound",
+        "p",
+        "/p",
+        "//p",
+        "p/",
+        "/p/Main.class",
+        "//p/Main.class",
+        "p/Main.class/",
+        "p//Main.class",
+        "./p/Main.class",
+        "p/./Main.class",
+        "../p/Main.class",
+        "p/../p/Main.class"
+    };
 
 
     @BeforeTest
@@ -126,10 +164,11 @@
             }
 
             // test "not found"
-            assertFalse(reader.find(NOT_A_RESOURCE).isPresent());
-            assertFalse(reader.open(NOT_A_RESOURCE).isPresent());
-            assertFalse(reader.read(NOT_A_RESOURCE).isPresent());
-
+            for (String name : BAD_BASE_RESOURCES) {
+                assertFalse(reader.find(name).isPresent());
+                assertFalse(reader.open(name).isPresent());
+                assertFalse(reader.read(name).isPresent());
+            }
 
             // test nulls
             try {
@@ -216,7 +255,7 @@
      */
     void test(Path mp) throws IOException {
 
-        ModuleFinder finder = new ModulePath(Runtime.version(), true, mp);
+        ModuleFinder finder = ModulePath.of(Runtime.version(), true, mp);
         ModuleReference mref = finder.find(TEST_MODULE).get();
         ModuleReader reader = mref.open();
 
@@ -236,9 +275,11 @@
             }
 
             // test "not found"
-            assertFalse(reader.find(NOT_A_RESOURCE).isPresent());
-            assertFalse(reader.open(NOT_A_RESOURCE).isPresent());
-            assertFalse(reader.read(NOT_A_RESOURCE).isPresent());
+            for (String name : BAD_TEST_RESOURCES) {
+                assertFalse(reader.find(name).isPresent());
+                assertFalse(reader.open(name).isPresent());
+                assertFalse(reader.read(name).isPresent());
+            }
 
             // test nulls
             try {
--- a/jdk/test/java/lang/module/ModuleReferenceTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/module/ModuleReferenceTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -31,6 +31,7 @@
 import java.lang.module.ModuleReader;
 import java.lang.module.ModuleReference;
 import java.net.URI;
+import java.util.Set;
 
 import org.testng.annotations.Test;
 import static org.testng.Assert.*;
@@ -49,10 +50,10 @@
 
     public void testBasic() throws Exception {
         ModuleDescriptor descriptor
-            = ModuleDescriptor.module("m")
+            = ModuleDescriptor.newModule("m")
                 .exports("p")
                 .exports("q")
-                .contains("p.internal")
+                .packages(Set.of("p.internal"))
                 .build();
 
         URI uri = URI.create("module:/m");
@@ -71,7 +72,7 @@
 
     public void testNullLocation() {
         ModuleDescriptor descriptor
-            = ModuleDescriptor.module("m")
+            = ModuleDescriptor.newModule("m")
                 .exports("p")
                 .build();
         ModuleReference mref = newModuleReference(descriptor, null);
--- a/jdk/test/java/lang/module/MultiReleaseJarTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/module/MultiReleaseJarTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,7 +65,7 @@
 
     private static final String MODULE_INFO = "module-info.class";
 
-    private static final int RELEASE = Runtime.version().major();
+    private static final int VERSION = Runtime.version().major();
 
     // are multi-release JARs enabled?
     private static final boolean MULTI_RELEASE;
@@ -80,7 +80,7 @@
     public void testBasic() throws Exception {
         String name = "m1";
 
-        ModuleDescriptor descriptor = ModuleDescriptor.module(name)
+        ModuleDescriptor descriptor = ModuleDescriptor.newModule(name)
                 .requires("java.base")
                 .build();
 
@@ -88,8 +88,8 @@
                 .moduleInfo("module-info.class", descriptor)
                 .resource("p/Main.class")
                 .resource("p/Helper.class")
-                .resource("META-INF/versions/9/p/Helper.class")
-                .resource("META-INF/versions/9/p/internal/Helper9.class")
+                .resource("META-INF/versions/" + VERSION + "/p/Helper.class")
+                .resource("META-INF/versions/" + VERSION + "/p/internal/Helper.class")
                 .build();
 
         // find the module
@@ -117,12 +117,12 @@
     public void testModuleInfoInVersionedSection() throws Exception {
         String name = "m1";
 
-        ModuleDescriptor descriptor1 = ModuleDescriptor.module(name)
+        ModuleDescriptor descriptor1 = ModuleDescriptor.newModule(name)
                 .requires("java.base")
                 .build();
 
         // module descriptor for versioned section
-        ModuleDescriptor descriptor2 = ModuleDescriptor.module(name)
+        ModuleDescriptor descriptor2 = ModuleDescriptor.newModule(name)
                 .requires("java.base")
                 .requires("jdk.unsupported")
                 .build();
@@ -131,9 +131,9 @@
                 .moduleInfo(MODULE_INFO, descriptor1)
                 .resource("p/Main.class")
                 .resource("p/Helper.class")
-                .moduleInfo("META-INF/versions/9/" + MODULE_INFO, descriptor2)
-                .resource("META-INF/versions/9/p/Helper.class")
-                .resource("META-INF/versions/9/p/internal/Helper9.class")
+                .moduleInfo("META-INF/versions/" + VERSION + "/" + MODULE_INFO, descriptor2)
+                .resource("META-INF/versions/" + VERSION + "/p/Helper.class")
+                .resource("META-INF/versions/" + VERSION + "/p/internal/Helper.class")
                 .build();
 
         // find the module
@@ -161,8 +161,8 @@
         Path jar = new JarBuilder(name)
                 .resource("p/Main.class")
                 .resource("p/Helper.class")
-                .resource("META-INF/versions/9/p/Helper.class")
-                .resource("META-INF/versions/9/p/internal/Helper9.class")
+                .resource("META-INF/versions/" + VERSION + "/p/Helper.class")
+                .resource("META-INF/versions/" + VERSION + "/p/internal/Helper.class")
                 .build();
 
         // find the module
@@ -188,19 +188,19 @@
     public void testModuleReader() throws Exception {
         String name = "m1";
 
-        ModuleDescriptor descriptor1 = ModuleDescriptor.module(name)
+        ModuleDescriptor descriptor1 = ModuleDescriptor.newModule(name)
                 .requires("java.base")
                 .build();
 
         // module descriptor for versioned section
-        ModuleDescriptor descriptor2 = ModuleDescriptor.module(name)
+        ModuleDescriptor descriptor2 = ModuleDescriptor.newModule(name)
                 .requires("java.base")
                 .requires("jdk.unsupported")
                 .build();
 
         Path jar = new JarBuilder(name)
                 .moduleInfo(MODULE_INFO, descriptor1)
-                .moduleInfo("META-INF/versions/9/" + MODULE_INFO, descriptor2)
+                .moduleInfo("META-INF/versions/" + VERSION + "/" + MODULE_INFO, descriptor2)
                 .build();
 
         // find the module
@@ -243,7 +243,7 @@
 
             String expectedTail = "!/";
             if (MULTI_RELEASE)
-                expectedTail += "META-INF/versions/" + RELEASE + "/";
+                expectedTail += "META-INF/versions/" + VERSION + "/";
             expectedTail += MODULE_INFO;
             assertTrue(uri.toString().endsWith(expectedTail));
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/AccessibleObject/CanAccessTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,138 @@
+/*
+ * Copyright (c) 2017, 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
+ * @build CanAccessTest
+ * @modules java.base/jdk.internal.misc:+open
+ * @run testng CanAccessTest
+ * @summary Test AccessibleObject::canAccess method
+ */
+
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Method;
+import java.security.SecureClassLoader;
+
+import jdk.internal.misc.Unsafe;
+import org.testng.annotations.Test;
+import static org.testng.Assert.*;
+
+@Test
+public class CanAccessTest {
+    private static Unsafe INSTANCE = Unsafe.getUnsafe();
+
+    /**
+     * null object parameter for Constructor
+     */
+    public void testConstructor() throws Exception {
+        Constructor<?> ctor = Unsafe.class.getDeclaredConstructor();
+        assertFalse(ctor.canAccess(null));
+        assertTrue(ctor.trySetAccessible());
+
+        try {
+            // non-null object parameter
+            ctor.canAccess(INSTANCE);
+            assertTrue(false);
+        } catch (IllegalArgumentException expected) {}
+    }
+
+    /**
+     * Test protected constructors
+     */
+    public void testProtectedConstructor() throws Exception {
+        TestLoader.testProtectedConstructorNonOpenedPackage();
+
+        Constructor<?> ctor = TestLoader.class.getDeclaredConstructor();
+        assertTrue(ctor.canAccess(null));
+    }
+
+    /**
+     * null object parameter  for static members
+     */
+    public void testStaticMember() throws Exception {
+        Method m = Unsafe.class.getDeclaredMethod("throwIllegalAccessError");
+        assertFalse(m.canAccess(null));
+        assertTrue(m.trySetAccessible());
+
+        try {
+            // non-null object parameter
+            m.canAccess(INSTANCE);
+            assertTrue(false);
+        } catch (IllegalArgumentException expected) { }
+    }
+
+    /**
+     * Test protected static
+     */
+    public void testProtectedStatic() throws Exception {
+        Method m = TestLoader.testProtectedStatic();
+        assertFalse(m.canAccess(null));
+    }
+
+    /**
+     * the specified object must be an instance of the declaring class
+     * for instance members
+     */
+    public void testInstanceMethod() throws Exception {
+        Method m = Unsafe.class.getDeclaredMethod("addressSize0");
+        assertFalse(m.canAccess(INSTANCE));
+
+        try {
+            m.canAccess(null);
+            assertTrue(false);
+        } catch (IllegalArgumentException expected) { }
+    }
+
+    /**
+     * the specified object must be an instance of the declaring class
+     * for instance members
+     */
+    public void testInvalidInstanceObject() throws Exception {
+        Class<?> clazz = Class.forName("sun.security.x509.X500Name");
+        Method m = clazz.getDeclaredMethod("size");
+
+        try {
+            m.canAccess(INSTANCE);
+            assertTrue(false);
+        } catch (IllegalArgumentException expected) { }
+    }
+
+
+    static class TestLoader extends SecureClassLoader {
+        public static Method testProtectedStatic() throws Exception {
+            Method m = ClassLoader.class.getDeclaredMethod("registerAsParallelCapable");
+            assertTrue(m.canAccess(null));
+            return m;
+        }
+
+        protected TestLoader() throws Exception {
+            Constructor<?> ctor = SecureClassLoader.class.getDeclaredConstructor();
+            assertFalse(ctor.canAccess(null));
+            assertFalse(ctor.trySetAccessible());
+        }
+
+        public static void testProtectedConstructorNonOpenedPackage() throws Exception {
+            new TestLoader();
+        }
+    }
+}
--- a/jdk/test/java/lang/reflect/AccessibleObject/ModuleSetAccessibleTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/reflect/AccessibleObject/ModuleSetAccessibleTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -30,7 +30,6 @@
  * @summary Test java.lang.reflect.AccessibleObject with modules
  */
 
-import java.lang.module.ModuleDescriptor;
 import java.lang.reflect.AccessibleObject;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.Field;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/AccessibleObject/TrySetAccessibleTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,201 @@
+/*
+ * Copyright (c) 2017, 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
+ * @build TrySetAccessibleTest
+ * @modules java.base/java.lang:open
+ *          java.base/jdk.internal.perf
+ *          java.base/jdk.internal.misc:+open
+ * @run testng TrySetAccessibleTest
+ * @summary Test AccessibleObject::trySetAccessible method
+ */
+
+import java.lang.reflect.AccessibleObject;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+
+import jdk.internal.misc.Unsafe;
+import jdk.internal.perf.Perf;
+
+import org.testng.annotations.Test;
+import static org.testng.Assert.*;
+
+@Test
+public class TrySetAccessibleTest {
+    /**
+     * Invoke a private constructor on a public class in an exported package
+     */
+    public void testPrivateConstructorInExportedPackage() throws Exception {
+        Constructor<?> ctor = Perf.class.getDeclaredConstructor();
+
+        try {
+            ctor.newInstance();
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+        assertFalse(ctor.trySetAccessible());
+        assertFalse(ctor.canAccess(null));
+    }
+
+    /**
+     * Invoke a private constructor on a public class in an open package
+     */
+    public void testPrivateConstructorInOpenedPackage() throws Exception {
+        Constructor<?> ctor = Unsafe.class.getDeclaredConstructor();
+
+        try {
+            ctor.newInstance();
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+        assertTrue(ctor.trySetAccessible());
+        assertTrue(ctor.canAccess(null));
+        Unsafe unsafe = (Unsafe) ctor.newInstance();
+    }
+
+    /**
+     * Invoke a private method on a public class in an exported package
+     */
+    public void testPrivateMethodInExportedPackage() throws Exception {
+        Method m = Perf.class.getDeclaredMethod("getBytes", String.class);
+        try {
+            m.invoke(null);
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+        assertFalse(m.trySetAccessible());
+        assertFalse(m.canAccess(null));
+    }
+
+
+    /**
+     * Invoke a private method on a public class in an open package
+     */
+    public void testPrivateMethodInOpenedPackage() throws Exception {
+        Method m = Unsafe.class.getDeclaredMethod("throwIllegalAccessError");
+        assertFalse(m.canAccess(null));
+
+        try {
+            m.invoke(null);
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+        assertTrue(m.trySetAccessible());
+        assertTrue(m.canAccess(null));
+        try {
+            m.invoke(null);
+            assertTrue(false);
+        } catch (InvocationTargetException e) {
+            // thrown by throwIllegalAccessError
+            assertTrue(e.getCause() instanceof IllegalAccessError);
+        }
+    }
+
+    /**
+     * Invoke a private method on a public class in an exported package
+     */
+    public void testPrivateFieldInExportedPackage() throws Exception {
+        Field f = Perf.class.getDeclaredField("instance");
+        try {
+            f.get(null);
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+        assertFalse(f.trySetAccessible());
+        assertFalse(f.canAccess(null));
+        try {
+            f.get(null);
+            assertTrue(false);
+        } catch (IllegalAccessException expected) {}
+    }
+
+    /**
+     * Access a private field in a public class that is an exported package
+     */
+    public void testPrivateFieldInOpenedPackage() throws Exception {
+        Field f = Unsafe.class.getDeclaredField("theUnsafe");
+
+        try {
+            f.get(null);
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+        assertTrue(f.trySetAccessible());
+        assertTrue(f.canAccess(null));
+        Unsafe unsafe = (Unsafe) f.get(null);
+    }
+
+
+    /**
+     * Invoke a public constructor on a public class in a non-exported package
+     */
+    public void testPublicConstructorInNonExportedPackage() throws Exception {
+        Class<?> clazz = Class.forName("sun.security.x509.X500Name");
+        Constructor<?> ctor = clazz.getConstructor(String.class);
+
+        try {
+            ctor.newInstance("cn=duke");
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+        assertFalse(ctor.trySetAccessible());
+        assertFalse(ctor.canAccess(null));
+        assertTrue(ctor.trySetAccessible() == ctor.isAccessible());
+    }
+
+
+    /**
+     * Access a public field in a public class that in a non-exported package
+     */
+    public void testPublicFieldInNonExportedPackage() throws Exception {
+        Class<?> clazz = Class.forName("sun.security.x509.X500Name");
+        Field f = clazz.getField("SERIALNUMBER_OID");
+
+        try {
+            f.get(null);
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+        assertFalse(f.trySetAccessible());
+        assertFalse(f.canAccess(null));
+    }
+
+
+    /**
+     * Test that the Class constructor cannot be make accessible.
+     */
+    public void testJavaLangClass() throws Exception {
+
+        // non-public constructor
+        Constructor<?> ctor
+            = Class.class.getDeclaredConstructor(ClassLoader.class, Class.class);
+        AccessibleObject[] ctors = { ctor };
+
+        assertFalse(ctor.trySetAccessible());
+        assertFalse(ctor.canAccess(null));
+    }
+
+}
--- a/jdk/test/java/lang/reflect/Layer/BasicLayerTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/reflect/Layer/BasicLayerTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -24,6 +24,7 @@
 /**
  * @test
  * @library /lib/testlibrary
+ * @modules java.base/jdk.internal.misc
  * @build BasicLayerTest ModuleUtils
  * @compile layertest/Test.java
  * @run testng BasicLayerTest
@@ -43,6 +44,7 @@
 import java.util.Set;
 import java.util.stream.Collectors;
 
+import jdk.internal.misc.SharedSecrets;
 import org.testng.annotations.Test;
 import static org.testng.Assert.*;
 
@@ -50,6 +52,15 @@
 public class BasicLayerTest {
 
     /**
+     * Creates a "non-strict" builder for building a module. This allows the
+     * test the create ModuleDescriptor objects that do not require java.base.
+     */
+    private static ModuleDescriptor.Builder newBuilder(String mn) {
+        return SharedSecrets.getJavaLangModuleAccess()
+                .newModuleBuilder(mn, false, Set.of());
+    }
+
+    /**
      * Exercise Layer.empty()
      */
     public void testEmpty() {
@@ -109,25 +120,22 @@
      * Exercise Layer defineModules, created with empty layer as parent
      */
     public void testLayerOnEmpty() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires("m2")
                 .exports("p1")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("m3")
                 .build();
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .build();
 
         ModuleFinder finder
             = ModuleUtils.finderOf(descriptor1, descriptor2, descriptor3);
 
-        Configuration cf = resolveRequires(finder, "m1");
+        Configuration cf = resolve(finder, "m1");
 
         // map each module to its own class loader for this test
         ClassLoader loader1 = new ClassLoader() { };
@@ -191,15 +199,13 @@
      * Exercise Layer defineModules, created with boot layer as parent
      */
     public void testLayerOnBoot() {
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires("m2")
                 .requires("java.base")
                 .exports("p1")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires("java.base")
                 .build();
 
@@ -207,7 +213,7 @@
             = ModuleUtils.finderOf(descriptor1, descriptor2);
 
         Configuration parent = Layer.boot().configuration();
-        Configuration cf = resolveRequires(parent, finder, "m1");
+        Configuration cf = resolve(parent, finder, "m1");
 
         ClassLoader loader = new ClassLoader() { };
 
@@ -256,21 +262,19 @@
      * have the same module-private package.
      */
     public void testPackageContainedInSelfAndOther() {
-        ModuleDescriptor descriptor1
-            =  ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 =  newBuilder("m1")
                 .requires("m2")
-                .contains("p")
+                .packages(Set.of("p"))
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
-                .contains("p")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
+                .packages(Set.of("p"))
                 .build();
 
         ModuleFinder finder
             = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf = resolveRequires(finder, "m1");
+        Configuration cf = resolve(finder, "m1");
         assertTrue(cf.modules().size() == 2);
 
         // one loader per module, should be okay
@@ -292,22 +296,18 @@
     public void testSameExportInPartitionedGraph() {
 
         // m1 reads m2, m2 exports p to m1
-        ModuleDescriptor descriptor1
-            =  ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 =  newBuilder("m1")
                 .requires("m2")
                 .build();
-        ModuleDescriptor descriptor2
-            =  ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 =  newBuilder("m2")
                 .exports("p", Set.of("m1"))
                 .build();
 
         // m3 reads m4, m4 exports p to m3
-        ModuleDescriptor descriptor3
-            =  ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m4")
                 .build();
-        ModuleDescriptor descriptor4
-            =  ModuleDescriptor.module("m4")
+        ModuleDescriptor descriptor4 = newBuilder("m4")
                 .exports("p", Set.of("m3"))
                 .build();
 
@@ -317,7 +317,7 @@
                                    descriptor3,
                                    descriptor4);
 
-        Configuration cf = resolveRequires(finder, "m1", "m3");
+        Configuration cf = resolve(finder, "m1", "m3");
         assertTrue(cf.modules().size() == 4);
 
         // one loader per module
@@ -353,16 +353,15 @@
         ModuleDescriptor base = Object.class.getModule().getDescriptor();
         assertTrue(base.packages().contains("sun.launcher"));
 
-        ModuleDescriptor descriptor
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor = newBuilder("m1")
                .requires("java.base")
-               .contains("sun.launcher")
+               .packages(Set.of("sun.launcher"))
                .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor);
 
         Configuration parent = Layer.boot().configuration();
-        Configuration cf = parent.resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+        Configuration cf = parent.resolve(finder, ModuleFinder.of(), Set.of("m1"));
         assertTrue(cf.modules().size() == 1);
 
         ClassLoader loader = new ClassLoader() { };
@@ -382,18 +381,16 @@
 
         // cf1: m1 and m2, m2 requires transitive m1
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m1")
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf1 = resolveRequires(finder1, "m2");
+        Configuration cf1 = resolve(finder1, "m2");
 
         ClassLoader cl1 = new ClassLoader() { };
         Layer layer1 = Layer.empty().defineModules(cf1, mn -> cl1);
@@ -401,14 +398,13 @@
 
         // cf2: m3, m3 requires m2
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m2")
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor3);
 
-        Configuration cf2 = resolveRequires(cf1, finder2, "m3");
+        Configuration cf2 = resolve(cf1, finder2, "m3");
 
         ClassLoader cl2 = new ClassLoader() { };
         Layer layer2 = layer1.defineModules(cf2, mn -> cl2);
@@ -456,13 +452,11 @@
 
         // cf1: m1
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .build();
+        ModuleDescriptor descriptor1 = newBuilder("m1").build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf1 = resolveRequires(finder1, "m1");
+        Configuration cf1 = resolve(finder1, "m1");
 
         ClassLoader cl1 = new ClassLoader() { };
         Layer layer1 = Layer.empty().defineModules(cf1, mn -> cl1);
@@ -470,19 +464,17 @@
 
         // cf2: m2, m3: m2 requires transitive m1, m3 requires m2
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m1")
                 .build();
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m2")
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor2, descriptor3);
 
-        Configuration cf2 = resolveRequires(cf1, finder2, "m3");
+        Configuration cf2 = resolve(cf1, finder2, "m3");
 
         ClassLoader cl2 = new ClassLoader() { };
         Layer layer2 = layer1.defineModules(cf2, mn -> cl2);
@@ -527,13 +519,11 @@
 
         // cf1: m1
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .build();
+        ModuleDescriptor descriptor1 = newBuilder("m1").build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf1 = resolveRequires(finder1, "m1");
+        Configuration cf1 = resolve(finder1, "m1");
 
         ClassLoader cl1 = new ClassLoader() { };
         Layer layer1 = Layer.empty().defineModules(cf1, mn -> cl1);
@@ -541,14 +531,13 @@
 
         // cf2: m2 requires transitive m1
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m1")
                 .build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor2);
 
-        Configuration cf2 = resolveRequires(cf1, finder2, "m2");
+        Configuration cf2 = resolve(cf1, finder2, "m2");
 
         ClassLoader cl2 = new ClassLoader() { };
         Layer layer2 = layer1.defineModules(cf2, mn -> cl2);
@@ -556,14 +545,13 @@
 
         // cf3: m3 requires m2
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires("m2")
                 .build();
 
         ModuleFinder finder3 = ModuleUtils.finderOf(descriptor3);
 
-        Configuration cf3 = resolveRequires(cf2, finder3, "m3");
+        Configuration cf3 = resolve(cf2, finder3, "m3");
 
         ClassLoader cl3 = new ClassLoader() { };
         Layer layer3 = layer2.defineModules(cf3, mn -> cl3);
@@ -610,18 +598,16 @@
 
         // cf1: m1, m2 requires transitive m1
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .build();
 
-        ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+        ModuleDescriptor descriptor2 = newBuilder("m2")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m1")
                 .build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1, descriptor2);
 
-        Configuration cf1 = resolveRequires(finder1, "m2");
+        Configuration cf1 = resolve(finder1, "m2");
 
         ClassLoader cl1 = new ClassLoader() { };
         Layer layer1 = Layer.empty().defineModules(cf1, mn -> cl1);
@@ -629,20 +615,18 @@
 
         // cf2: m3 requires transitive m2, m4 requires m3
 
-        ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3")
+        ModuleDescriptor descriptor3 = newBuilder("m3")
                 .requires(Set.of(Requires.Modifier.TRANSITIVE), "m2")
                 .build();
 
-        ModuleDescriptor descriptor4
-            = ModuleDescriptor.module("m4")
+        ModuleDescriptor descriptor4 = newBuilder("m4")
                 .requires("m3")
                 .build();
 
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor3, descriptor4);
 
-        Configuration cf2 = resolveRequires(cf1, finder2, "m3", "m4");
+        Configuration cf2 = resolve(cf1, finder2, "m3", "m4");
 
         ClassLoader cl2 = new ClassLoader() { };
         Layer layer2 = layer1.defineModules(cf2, mn -> cl2);
@@ -693,8 +677,7 @@
     @Test(expectedExceptions = { LayerInstantiationException.class })
     public void testModuleAlreadyDefinedToLoader() {
 
-        ModuleDescriptor md
-            = ModuleDescriptor.module("m")
+        ModuleDescriptor md = newBuilder("m")
                 .requires("java.base")
                 .build();
 
@@ -702,7 +685,7 @@
 
         Configuration parent = Layer.boot().configuration();
 
-        Configuration cf = parent.resolveRequires(finder, ModuleFinder.of(), Set.of("m"));
+        Configuration cf = parent.resolve(finder, ModuleFinder.of(), Set.of("m"));
 
         ClassLoader loader = new ClassLoader() { };
 
@@ -722,15 +705,13 @@
     @Test(expectedExceptions = { LayerInstantiationException.class })
     public void testPackageAlreadyInNamedModule() {
 
-        ModuleDescriptor md1
-            = ModuleDescriptor.module("m1")
-                .contains("p")
+        ModuleDescriptor md1 = newBuilder("m1")
+                .packages(Set.of("p"))
                 .requires("java.base")
                 .build();
 
-        ModuleDescriptor md2
-            = ModuleDescriptor.module("m2")
-                .contains("p")
+        ModuleDescriptor md2 = newBuilder("m2")
+                .packages(Set.of("p"))
                 .requires("java.base")
                 .build();
 
@@ -742,13 +723,13 @@
 
         Configuration parent = Layer.boot().configuration();
 
-        Configuration cf1 = parent.resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+        Configuration cf1 = parent.resolve(finder, ModuleFinder.of(), Set.of("m1"));
 
         Layer layer1 = Layer.boot().defineModules(cf1, mn -> loader);
 
         // attempt to define m2 containing package p to class loader
 
-        Configuration cf2 = parent.resolveRequires(finder, ModuleFinder.of(), Set.of("m2"));
+        Configuration cf2 = parent.resolve(finder, ModuleFinder.of(), Set.of("m2"));
 
         // should throw exception because p already in m1
         Layer layer2 = Layer.boot().defineModules(cf2, mn -> loader);
@@ -767,16 +748,15 @@
         Class<?> c = layertest.Test.class;
         assertFalse(c.getModule().isNamed());  // in unnamed module
 
-        ModuleDescriptor md
-            = ModuleDescriptor.module("m")
-                .contains(c.getPackageName())
+        ModuleDescriptor md = newBuilder("m")
+                .packages(Set.of(c.getPackageName()))
                 .requires("java.base")
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(md);
 
         Configuration parent = Layer.boot().configuration();
-        Configuration cf = parent.resolveRequires(finder, ModuleFinder.of(), Set.of("m"));
+        Configuration cf = parent.resolve(finder, ModuleFinder.of(), Set.of("m"));
 
         Layer.boot().defineModules(cf, mn -> c.getClassLoader());
     }
@@ -786,8 +766,7 @@
      * Attempt to create a Layer with a module named "java.base".
      */
     public void testLayerWithJavaBase() {
-        ModuleDescriptor descriptor
-            = ModuleDescriptor.module("java.base")
+        ModuleDescriptor descriptor = newBuilder("java.base")
                 .exports("java.lang")
                 .build();
 
@@ -795,7 +774,7 @@
 
         Configuration cf = Layer.boot()
             .configuration()
-            .resolveRequires(finder, ModuleFinder.of(), Set.of("java.base"));
+            .resolve(finder, ModuleFinder.of(), Set.of("java.base"));
         assertTrue(cf.modules().size() == 1);
 
         ClassLoader scl = ClassLoader.getSystemClassLoader();
@@ -824,16 +803,15 @@
      */
     @Test(enabled = false)
     public void testLayerWithJavaPackage() {
-        ModuleDescriptor descriptor
-            = ModuleDescriptor.module("foo")
-                .contains("java.foo")
+        ModuleDescriptor descriptor = newBuilder("foo")
+                .packages(Set.of("java.foo"))
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor);
 
         Configuration cf = Layer.boot()
                 .configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("foo"));
+                .resolve(finder, ModuleFinder.of(), Set.of("foo"));
         assertTrue(cf.modules().size() == 1);
 
         ClassLoader pcl = ClassLoader.getPlatformClassLoader();
@@ -870,15 +848,14 @@
      */
     @Test(expectedExceptions = { LayerInstantiationException.class })
     public void testLayerWithBootLoader() {
-        ModuleDescriptor descriptor
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor = newBuilder("m1")
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor);
 
         Configuration cf = Layer.boot()
             .configuration()
-            .resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+            .resolve(finder, ModuleFinder.of(), Set.of("m1"));
         assertTrue(cf.modules().size() == 1);
 
         Layer.boot().defineModules(cf, mn -> null );
@@ -891,15 +868,14 @@
     @Test(expectedExceptions = { IllegalArgumentException.class })
     public void testIncorrectParent1() {
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .requires("java.base")
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1);
 
         Configuration parent = Layer.boot().configuration();
-        Configuration cf = parent.resolveRequires(finder, ModuleFinder.of(), Set.of("m1"));
+        Configuration cf = parent.resolve(finder, ModuleFinder.of(), Set.of("m1"));
 
         ClassLoader loader = new ClassLoader() { };
         Layer.empty().defineModules(cf, mn -> loader);
@@ -912,13 +888,12 @@
     @Test(expectedExceptions = { IllegalArgumentException.class })
     public void testIncorrectParent2() {
 
-        ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
+        ModuleDescriptor descriptor1 = newBuilder("m1")
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1);
 
-        Configuration cf = resolveRequires(finder, "m1");
+        Configuration cf = resolve(finder, "m1");
 
         ClassLoader loader = new ClassLoader() { };
         Layer.boot().defineModules(cf, mn -> loader);
@@ -935,7 +910,7 @@
 
     @Test(expectedExceptions = { NullPointerException.class })
     public void testCreateWithNull2() {
-        Configuration cf = resolveRequires(Layer.boot().configuration(), ModuleFinder.of());
+        Configuration cf = resolve(Layer.boot().configuration(), ModuleFinder.of());
         Layer.boot().defineModules(cf, null);
     }
 
@@ -975,14 +950,14 @@
      * Resolve the given modules, by name, and returns the resulting
      * Configuration.
      */
-    private static Configuration resolveRequires(Configuration cf,
-                                                 ModuleFinder finder,
-                                                 String... roots) {
-        return cf.resolveRequires(finder, ModuleFinder.of(), Set.of(roots));
+    private static Configuration resolve(Configuration cf,
+                                         ModuleFinder finder,
+                                         String... roots) {
+        return cf.resolve(finder, ModuleFinder.of(), Set.of(roots));
     }
 
-    private static Configuration resolveRequires(ModuleFinder finder,
-                                                 String... roots) {
-        return resolveRequires(Configuration.empty(), finder, roots);
+    private static Configuration resolve(ModuleFinder finder,
+                                         String... roots) {
+        return resolve(Configuration.empty(), finder, roots);
     }
 }
--- a/jdk/test/java/lang/reflect/Layer/LayerAndLoadersTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/reflect/Layer/LayerAndLoadersTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -81,7 +81,7 @@
      */
     public void testWithOneLoader() throws Exception {
 
-        Configuration cf = resolveRequires("m1");
+        Configuration cf = resolve("m1");
 
         ClassLoader scl = ClassLoader.getSystemClassLoader();
 
@@ -110,7 +110,7 @@
      */
     public void testWithManyLoaders() throws Exception {
 
-        Configuration cf = resolveRequires("m1");
+        Configuration cf = resolve("m1");
 
         ClassLoader scl = ClassLoader.getSystemClassLoader();
 
@@ -145,7 +145,7 @@
      */
     public void testServicesWithOneLoader() throws Exception {
 
-        Configuration cf = resolveRequiresAndUses("m1");
+        Configuration cf = resolveAndBind("m1");
 
         ClassLoader scl = ClassLoader.getSystemClassLoader();
 
@@ -186,7 +186,7 @@
      */
     public void testServicesWithManyLoaders() throws Exception {
 
-        Configuration cf = resolveRequiresAndUses("m1");
+        Configuration cf = resolveAndBind("m1");
 
         ClassLoader scl = ClassLoader.getSystemClassLoader();
 
@@ -233,7 +233,7 @@
      */
     public void testDelegationToParent() throws Exception {
 
-        Configuration cf = resolveRequires("m1");
+        Configuration cf = resolve("m1");
 
         ClassLoader parent = this.getClass().getClassLoader();
         String cn = this.getClass().getName();
@@ -267,16 +267,16 @@
     public void testOverlappingPackages() {
 
         ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1").exports("p").build();
+            = ModuleDescriptor.newModule("m1").exports("p").build();
 
         ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2").exports("p").build();
+            = ModuleDescriptor.newModule("m2").exports("p").build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
 
         Configuration cf = Layer.boot()
             .configuration()
-            .resolveRequires(finder, ModuleFinder.of(), Set.of("m1", "m2"));
+            .resolve(finder, ModuleFinder.of(), Set.of("m1", "m2"));
 
         // cannot define both module m1 and m2 to the same class loader
         try {
@@ -301,29 +301,29 @@
     public void testSplitDelegation() {
 
         ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1").exports("p").build();
+            = ModuleDescriptor.newModule("m1").exports("p").build();
 
         ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2").exports("p").build();
+            = ModuleDescriptor.newModule("m2").exports("p").build();
 
         ModuleFinder finder1 = ModuleUtils.finderOf(descriptor1, descriptor2);
 
         Configuration cf1 = Layer.boot()
             .configuration()
-            .resolveRequires(finder1, ModuleFinder.of(), Set.of("m1", "m2"));
+            .resolve(finder1, ModuleFinder.of(), Set.of("m1", "m2"));
 
         Layer layer1 = Layer.boot().defineModulesWithManyLoaders(cf1, null);
         checkLayer(layer1, "m1", "m2");
 
         ModuleDescriptor descriptor3
-            = ModuleDescriptor.module("m3").requires("m1").build();
+            = ModuleDescriptor.newModule("m3").requires("m1").build();
 
         ModuleDescriptor descriptor4
-            = ModuleDescriptor.module("m4").requires("m2").build();
+            = ModuleDescriptor.newModule("m4").requires("m2").build();
 
         ModuleFinder finder2 = ModuleUtils.finderOf(descriptor3, descriptor4);
 
-        Configuration cf2 = cf1.resolveRequires(finder2, ModuleFinder.of(),
+        Configuration cf2 = cf1.resolve(finder2, ModuleFinder.of(),
                                                 Set.of("m3", "m4"));
 
         // package p cannot be supplied by two class loaders
@@ -349,13 +349,13 @@
      */
     public void testOverriding1() throws Exception {
 
-        Configuration cf1 = resolveRequires("m1");
+        Configuration cf1 = resolve("m1");
 
         Layer layer1 = Layer.boot().defineModulesWithOneLoader(cf1, null);
         checkLayer(layer1, "m1", "m2", "m3");
 
         ModuleFinder finder = ModuleFinder.of(MODS_DIR);
-        Configuration cf2 = cf1.resolveRequires(finder, ModuleFinder.of(),
+        Configuration cf2 = cf1.resolve(finder, ModuleFinder.of(),
                                                 Set.of("m1"));
 
         Layer layer2 = layer1.defineModulesWithOneLoader(cf2, null);
@@ -398,13 +398,13 @@
      */
     public void testOverriding2() throws Exception {
 
-        Configuration cf1 = resolveRequires("m1");
+        Configuration cf1 = resolve("m1");
 
         Layer layer1 = Layer.boot().defineModulesWithManyLoaders(cf1, null);
         checkLayer(layer1, "m1", "m2", "m3");
 
         ModuleFinder finder = ModuleFinder.of(MODS_DIR);
-        Configuration cf2 = cf1.resolveRequires(finder, ModuleFinder.of(),
+        Configuration cf2 = cf1.resolve(finder, ModuleFinder.of(),
                                                 Set.of("m1"));
 
         Layer layer2 = layer1.defineModulesWithManyLoaders(cf2, null);
@@ -492,14 +492,14 @@
      */
     public void testOverriding3() throws Exception {
 
-        Configuration cf1 = resolveRequires("m1");
+        Configuration cf1 = resolve("m1");
 
         Layer layer1 = Layer.boot().defineModulesWithOneLoader(cf1, null);
         checkLayer(layer1, "m1", "m2", "m3");
 
         ModuleFinder finder = finderFor("m1", "m3");
 
-        Configuration cf2 = cf1.resolveRequires(finder, ModuleFinder.of(),
+        Configuration cf2 = cf1.resolve(finder, ModuleFinder.of(),
                                                 Set.of("m1"));
 
         Layer layer2 = layer1.defineModulesWithOneLoader(cf2, null);
@@ -529,14 +529,14 @@
      */
     public void testOverriding4() throws Exception {
 
-        Configuration cf1 = resolveRequires("m1");
+        Configuration cf1 = resolve("m1");
 
         Layer layer1 = Layer.boot().defineModulesWithManyLoaders(cf1, null);
         checkLayer(layer1, "m1", "m2", "m3");
 
         ModuleFinder finder = finderFor("m1", "m3");
 
-        Configuration cf2 = cf1.resolveRequires(finder, ModuleFinder.of(),
+        Configuration cf2 = cf1.resolve(finder, ModuleFinder.of(),
                                                 Set.of("m1"));
 
         Layer layer2 = layer1.defineModulesWithManyLoaders(cf2, null);
@@ -577,7 +577,7 @@
      * Layer.defineModulesWithOneLoader.
      */
     public void testResourcesOneLoader() throws Exception {
-        Configuration cf = resolveRequires("m1");
+        Configuration cf = resolve("m1");
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer = Layer.boot().defineModulesWithOneLoader(cf, scl);
         ClassLoader loader = layer.findLoader("m1");
@@ -589,7 +589,7 @@
      * Layer.defineModulesWithOneLoader.
      */
     public void testResourcesManyLoaders() throws Exception {
-        Configuration cf = resolveRequires("m1");
+        Configuration cf = resolve("m1");
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer = Layer.boot().defineModulesWithManyLoaders(cf, scl);
         ClassLoader loader = layer.findLoader("m1");
@@ -621,22 +621,22 @@
      * Resolve the given modules, by name, and returns the resulting
      * Configuration.
      */
-    private static Configuration resolveRequires(String... roots) {
+    private static Configuration resolve(String... roots) {
         ModuleFinder finder = ModuleFinder.of(MODS_DIR);
         return Layer.boot()
             .configuration()
-            .resolveRequires(finder, ModuleFinder.of(), Set.of(roots));
+            .resolve(finder, ModuleFinder.of(), Set.of(roots));
     }
 
     /**
      * Resolve the given modules, by name, and returns the resulting
      * Configuration.
      */
-    private static Configuration resolveRequiresAndUses(String... roots) {
+    private static Configuration resolveAndBind(String... roots) {
         ModuleFinder finder = ModuleFinder.of(MODS_DIR);
         return Layer.boot()
             .configuration()
-            .resolveRequiresAndUses(finder, ModuleFinder.of(), Set.of(roots));
+            .resolveAndBind(finder, ModuleFinder.of(), Set.of(roots));
     }
 
 
--- a/jdk/test/java/lang/reflect/Layer/LayerControllerTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/reflect/Layer/LayerControllerTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -50,22 +50,22 @@
      */
     private Layer.Controller createTestLayer() {
         ModuleDescriptor descriptor1
-            = ModuleDescriptor.module("m1")
-                .contains("p1")
+            = ModuleDescriptor.newModule("m1")
+                .packages(Set.of("p1"))
                 .requires("java.base")
                 .build();
 
         ModuleDescriptor descriptor2
-            = ModuleDescriptor.module("m2")
+            = ModuleDescriptor.newModule("m2")
                 .requires("java.base")
-                .contains("p2")
+                .packages(Set.of("p2"))
                 .build();
 
         ModuleFinder finder = ModuleUtils.finderOf(descriptor1, descriptor2);
         Layer bootLayer = Layer.boot();
 
         Configuration cf = bootLayer.configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of("m1", "m2"));
+                .resolve(finder, ModuleFinder.of(), Set.of("m1", "m2"));
 
         ClassLoader scl = ClassLoader.getSystemClassLoader();
 
@@ -193,4 +193,4 @@
             assertTrue(false);
         } catch (NullPointerException expected) { }
     }
-}
\ No newline at end of file
+}
--- a/jdk/test/java/lang/reflect/Module/AnnotationsTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/reflect/Module/AnnotationsTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -144,7 +144,7 @@
         Layer bootLayer = Layer.boot();
 
         Configuration cf = bootLayer.configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of(name));
+                .resolve(finder, ModuleFinder.of(), Set.of(name));
 
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer = bootLayer.defineModulesWithOneLoader(cf, scl);
--- a/jdk/test/java/lang/reflect/Module/BasicModuleTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/reflect/Module/BasicModuleTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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,8 +25,10 @@
 import java.lang.module.ResolvedModule;
 import java.lang.reflect.Layer;
 import java.lang.reflect.Module;
+import java.nio.file.spi.FileSystemProvider;  // service type in java.base
 import java.util.function.Predicate;
 import java.util.stream.Stream;
+import javax.print.PrintServiceLookup;        // service type in java.desktop
 
 import org.testng.annotations.Test;
 import static org.testng.Assert.*;
@@ -170,6 +172,14 @@
 
         // canRead
         assertTrue(base.canRead(base));
+        assertFalse(base.canRead(thisModule));
+
+        // addReads
+        try {
+            base.addReads(thisModule);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+        assertFalse(base.canRead(thisModule));
 
         // isExported
         assertTrue(base.isExported("java.lang"));
@@ -182,6 +192,18 @@
         assertFalse(base.isExported("java.wombat", thisModule));
         assertFalse(base.isExported("java.wombat", base));
 
+        // addExports
+        try {
+            base.addExports("java.lang", thisModule);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+        try {
+            base.addExports("jdk.internal.misc", thisModule);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+        assertFalse(base.isExported("jdk.internal.misc"));
+        assertFalse(base.isExported("jdk.internal.misc", thisModule));
+
         // isOpen
         assertFalse(base.isOpen("java.lang"));
         assertFalse(base.isOpen("java.lang", thisModule));
@@ -192,6 +214,29 @@
         assertFalse(base.isOpen("java.wombat"));
         assertFalse(base.isOpen("java.wombat", thisModule));
         assertFalse(base.isOpen("java.wombat", base));
+
+        // addOpens
+        try {
+            base.addOpens("jdk.internal.misc", thisModule);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+        assertFalse(base.isOpen("jdk.internal.misc"));
+        assertFalse(base.isOpen("jdk.internal.misc", thisModule));
+
+        // canUse
+        assertTrue(base.canUse(FileSystemProvider.class));
+        assertFalse(base.canUse(Thread.class));
+
+        // addUses
+        try {
+            base.addUses(FileSystemProvider.class);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+        try {
+            base.addUses(Thread.class);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+        assertFalse(base.canUse(Thread.class));
     }
 
 
@@ -226,26 +271,68 @@
         assertTrue(desktop.canRead(base));
         assertTrue(desktop.canRead(xml));
 
+        // addReads
+        try {
+            desktop.addReads(thisModule);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+        assertFalse(desktop.canRead(thisModule));
+
         // isExported
         assertTrue(desktop.isExported("java.awt"));
         assertTrue(desktop.isExported("java.awt", thisModule));
+        assertFalse(desktop.isExported("sun.awt"));
+        assertFalse(desktop.isExported("sun.awt", thisModule));
+        assertTrue(desktop.isExported("sun.awt", desktop));
         assertFalse(desktop.isExported("java.wombat"));
         assertFalse(desktop.isExported("java.wombat", thisModule));
+        assertFalse(desktop.isExported("java.wombat", base));
+
+        // addExports
+        try {
+            desktop.addExports("java.awt", thisModule);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+        try {
+            desktop.addExports("sun.awt", thisModule);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+        assertFalse(desktop.isExported("sun.awt"));
+        assertFalse(desktop.isExported("sun.awt", thisModule));
+
+        // isOpen
+        assertFalse(desktop.isOpen("java.awt"));
+        assertFalse(desktop.isOpen("java.awt", thisModule));
+        assertTrue(desktop.isOpen("java.awt", desktop));
+        assertFalse(desktop.isOpen("sun.awt"));
+        assertFalse(desktop.isOpen("sun.awt", thisModule));
+        assertTrue(desktop.isOpen("sun.awt", desktop));
+        assertFalse(desktop.isOpen("java.wombat"));
+        assertFalse(desktop.isOpen("java.wombat", thisModule));
+        assertFalse(desktop.isOpen("java.wombat", desktop));
+
+        // addOpens
+        try {
+            base.addOpens("sun.awt", thisModule);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+        assertFalse(desktop.isOpen("sun.awt"));
+        assertFalse(desktop.isOpen("sun.awt", thisModule));
+
+        // canUse
+        assertTrue(base.canUse(FileSystemProvider.class));
+        assertFalse(base.canUse(Thread.class));
+
+        // addUses
+        try {
+            desktop.addUses(PrintServiceLookup.class);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+        try {
+            desktop.addUses(Thread.class);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+        assertFalse(desktop.canUse(Thread.class));
     }
 
-
-    @Test(expectedExceptions = { NullPointerException.class })
-    public void testIsExportedNull() {
-        Module thisModule = this.getClass().getModule();
-        thisModule.isExported(null, thisModule);
-    }
-
-
-    @Test(expectedExceptions = { NullPointerException.class })
-    public void testIsExportedToNull() {
-        Module thisModule = this.getClass().getModule();
-        thisModule.isExported("", null);
-    }
-
-
 }
--- a/jdk/test/java/lang/reflect/Module/WithSecurityManager.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/reflect/Module/WithSecurityManager.java	Thu Mar 16 20:47:03 2017 +0000
@@ -126,7 +126,7 @@
         Layer bootLayer = Layer.boot();
         Configuration cf = bootLayer
             .configuration()
-            .resolveRequires(finder, ModuleFinder.of(), Set.of(ANOTHER_MODULE));
+            .resolve(finder, ModuleFinder.of(), Set.of(ANOTHER_MODULE));
         Layer layer = bootLayer.defineModulesWithOneLoader(cf, null);
 
         Optional<Module> om = layer.findModule(mn);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/Driver.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2017, 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
+ * @build test/* m1/* m2/* m3/* m4/*
+ * @run testng/othervm test/test.Main
+ * @summary Basic test case for Module::addXXX methods
+ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/m1/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+module m1 {
+    exports p1;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/m1/p1/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2017, 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 p1;
+
+public class C {
+    public C() { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/m2/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+module m2 {
+    exports p2;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/m2/p2/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2017, 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 p2;
+
+import java.lang.reflect.Module;
+
+public class C {
+
+    public static void export(String pn, Module m) {
+        C.class.getModule().addExports(pn, m);
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/m2/p2/internal/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2017, 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 p2.internal;
+
+public class C {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/m3/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+module m3 {
+    exports p3 to test;
+    opens p3 to test;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/m3/p3/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2017, 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 p3;
+
+public class C {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/m4/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+module m4 {
+    exports p4;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/m4/p4/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2017, 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 p4;
+
+import java.lang.reflect.Constructor;
+
+public class C {
+    public static Object tryNewInstance(Class<?> clazz) throws Exception {
+        Constructor<?> ctor = clazz.getDeclaredConstructor();
+        return ctor.newInstance();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/test/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+module test {
+    exports test to testng;
+
+    requires m2;
+    requires m3;
+    requires m4;
+    requires testng;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/test/test/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2017, 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 test;
+
+public class C { }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/test/test/Main.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,196 @@
+/*
+ * Copyright (c) 2017, 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 test;
+
+import java.lang.invoke.MethodHandle;
+import java.lang.invoke.MethodHandles;
+import java.lang.invoke.MethodType;
+import java.lang.reflect.Constructor;
+import java.lang.reflect.Module;
+import java.util.ServiceConfigurationError;
+import java.util.ServiceLoader;
+
+import org.testng.annotations.Test;
+import static org.testng.Assert.*;
+
+/**
+ * Basic test case for Module::addXXXX methods
+ */
+
+@Test
+public class Main {
+
+    /**
+     * Test Module::addReads
+     *
+     *     module test { }
+     *
+     *     module m1 {
+     *         exports p1;
+     *     }
+     */
+    public void testAddReads() throws Throwable {
+        Module thisModule = Main.class.getModule();
+        Class<?> clazz = Class.forName("p1.C");
+        Module m1 = clazz.getModule();
+
+        // test does not read m1
+        assertFalse(thisModule.canRead(m1));
+        MethodHandles.Lookup lookup = MethodHandles.lookup();
+        MethodType mt = MethodType.methodType(void.class);
+        try {
+            lookup.findConstructor(clazz, mt);
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+        // update test to read m1
+        Module result = thisModule.addReads(m1);
+        assertTrue(result== thisModule);
+        assertTrue(thisModule.canRead(m1));
+        MethodHandle mh = lookup.findConstructor(clazz, mt);
+        Object obj = mh.invoke();
+
+        // attempt to update m1 to read test
+        try {
+            m1.addReads(thisModule);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+    }
+
+
+    /**
+     * Test Module::addExports
+     *
+     *     module test {
+     *         requires m2;
+     *     }
+     *     module m2 {
+     *         exports p2;
+     *         contains package p2.internal;
+     *     }
+     */
+    public void testAddExports() throws Exception {
+        Module thisModule = Main.class.getModule();
+        Module m2 = p2.C.class.getModule();
+        Class<?> targetClass = Class.forName("p2.internal.C");
+        String p2Internal = targetClass.getPackageName();
+        assertTrue(targetClass.getModule() == m2);
+
+        // m2 does not export p2.internal to test
+        assertFalse(m2.isExported(p2Internal, thisModule));
+        Constructor<?> ctor = targetClass.getDeclaredConstructor();
+        try {
+            ctor.newInstance();
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+        // update m2 to export p2.internal to test
+        p2.C.export(p2Internal, thisModule);
+        assertTrue(m2.isExported(p2Internal, thisModule));
+        ctor.newInstance(); // should succeed
+
+        // attempt to update m2 to export a package to test
+        try {
+            m2.addExports("p2.other", thisModule);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+    }
+
+    /**
+     * Test Module::addOpens
+     *
+     *     module test {
+     *         requires m3;
+     *         requires m4;
+     *     }
+     *
+     *     module m3 {
+     *         exports p3 to test;
+     *         opens p3 to test;
+     *     }
+     *
+     *     module m4 {
+     *         exports p4;
+     *     }
+     */
+    public void testAddOpens() throws Exception {
+        Module thisModule = Main.class.getModule();
+        Module m3 = p3.C.class.getModule();
+        Module m4 = p4.C.class.getModule();
+
+        // test does not open package test to m4
+        assertFalse(thisModule.isOpen("test", m4));
+        try {
+            p4.C.tryNewInstance(test.C.class);
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+        // open test to m4
+        thisModule.addOpens("test", m4);
+        p4.C.tryNewInstance(test.C.class);  // should succeed
+
+
+        // m3 does not open p3 to m4
+        assertFalse(m3.isOpen("p3", m4));
+        try {
+            p4.C.tryNewInstance(p3.C.class);
+            assertTrue(false);
+        } catch (IllegalAccessException expected) { }
+
+
+        // m3 opens p3 to test => test allowed to open m3/p3 to m4
+        assertTrue(m3.isOpen("p3", thisModule));
+        m3.addOpens("p3", m4);
+        assertTrue(m3.isOpen("p3", m4));
+        p4.C.tryNewInstance(p3.C.class);   // should succeed
+
+
+        // attempt to update m4 to open package to m3
+        try {
+            m4.addOpens("p4", m3);
+            assertTrue(false);
+        } catch (IllegalCallerException expected) { }
+    }
+
+
+    /**
+     * Test Module::addUses
+     */
+    public void testAddUses() {
+        Module thisModule = Main.class.getModule();
+
+        assertFalse(thisModule.canUse(Service.class));
+        try {
+            ServiceLoader.load(Service.class);
+            assertTrue(false);
+        } catch (ServiceConfigurationError expected) { }
+
+        Module result = thisModule.addUses(Service.class);
+        assertTrue(result== thisModule);
+
+        assertTrue(thisModule.canUse(Service.class));
+        ServiceLoader.load(Service.class); // no exception
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/lang/reflect/Module/addXXX/test/test/Service.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2017, 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 test;
+
+/**
+ * Simple service type
+ */
+public interface Service { }
--- a/jdk/test/java/lang/reflect/Proxy/ProxyClassAccessTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/reflect/Proxy/ProxyClassAccessTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -91,7 +91,7 @@
         Layer bootLayer = Layer.boot();
         Configuration cf = bootLayer
                 .configuration()
-                .resolveRequiresAndUses(ModuleFinder.of(), finder, modules);
+                .resolveAndBind(ModuleFinder.of(), finder, modules);
         ClassLoader parentLoader = this.getClass().getClassLoader();
         Layer layer = bootLayer.defineModulesWithOneLoader(cf, parentLoader);
 
--- a/jdk/test/java/lang/reflect/Proxy/ProxyLayerTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/reflect/Proxy/ProxyLayerTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -79,7 +79,7 @@
         Layer bootLayer = Layer.boot();
         Configuration cf = bootLayer
                 .configuration()
-                .resolveRequiresAndUses(ModuleFinder.of(), finder, Arrays.asList(modules));
+                .resolveAndBind(ModuleFinder.of(), finder, Arrays.asList(modules));
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer = bootLayer.defineModulesWithOneLoader(cf, scl);
 
@@ -113,7 +113,7 @@
         Layer bootLayer = Layer.boot();
         Configuration cf = bootLayer
                 .configuration()
-                .resolveRequiresAndUses(ModuleFinder.of(), finder, Arrays.asList(modules));
+                .resolveAndBind(ModuleFinder.of(), finder, Arrays.asList(modules));
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer = bootLayer.defineModulesWithOneLoader(cf, scl);
 
@@ -143,7 +143,7 @@
         Layer bootLayer = Layer.boot();
         Configuration cf = bootLayer
                 .configuration()
-                .resolveRequiresAndUses(ModuleFinder.of(), finder, Arrays.asList(modules));
+                .resolveAndBind(ModuleFinder.of(), finder, Arrays.asList(modules));
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer = bootLayer.defineModulesWithOneLoader(cf, scl);
 
--- a/jdk/test/java/lang/reflect/PublicMethods/PublicMethodsTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/lang/reflect/PublicMethods/PublicMethodsTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -57,6 +57,9 @@
 /*
  * @test
  * @bug 8062389
+ * @modules java.compiler
+ *          jdk.compiler
+ *          jdk.zipfs
  * @summary Nearly exhaustive test of Class.getMethod() and Class.getMethods()
  * @run main PublicMethodsTest
  */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/net/URL/JarHandlerPkgPrefix/JarHandlerPkgPrefix.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,65 @@
+/*
+ * Copyright (c) 2017, 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 handlers.jar.Handler;
+
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+
+/*
+ * @test
+ * @bug 8174151
+ * @summary Test for java.protocol.handler.pkgs with jar protocol handler
+ * @library /lib/testlibrary/java/util/jar
+ * @compile handlers/jar/Handler.java
+ * @run main/othervm -Djava.protocol.handler.pkgs=handlers JarHandlerPkgPrefix
+ */
+public class JarHandlerPkgPrefix {
+
+    static void createJar(Path p) throws Exception {
+        JarBuilder jb = new JarBuilder(p.toString());
+        jb.addEntry("resource.txt", "CONTENTS".getBytes());
+        jb.build();
+    }
+
+    public static void main(String[] args) throws Exception {
+        Path jarPath = Paths.get(System.getProperty("user.dir", "."), "test.jar");
+        try {
+            createJar(jarPath);
+
+            URL j = new URL("jar:file:" + jarPath.toString() + "!/");
+            URLClassLoader ucl = new URLClassLoader(new URL[]{j});
+            ucl.findResource("resource.txt");
+
+            URL r = new URL("jar:file:" + jarPath.toString() + "!/resource.txt");
+            if (!Handler.URLS.contains(r))
+                throw new AssertionError("jar: URL handler not invoked");
+        }
+        finally {
+            Files.delete(jarPath);
+        }
+    }
+}
\ No newline at end of file
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/net/URL/JarHandlerPkgPrefix/handlers/jar/Handler.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,42 @@
+/*
+ * Copyright (c) 2017, 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 handlers.jar;
+
+import java.io.IOException;
+import java.net.URL;
+import java.net.URLConnection;
+import java.net.URLStreamHandler;
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
+
+public class Handler extends URLStreamHandler {
+    public static Set<URL> URLS = Collections.synchronizedSet(new HashSet<>());
+
+    @Override
+    protected URLConnection openConnection(URL u) throws IOException {
+        URLS.add(u);
+        return null;
+    }
+}
--- a/jdk/test/java/net/httpclient/http2/BasicTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/net/httpclient/http2/BasicTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -94,6 +94,7 @@
         } catch (Throwable tt) {
             System.err.println("tt caught");
             tt.printStackTrace();
+            throw tt;
         } finally {
             httpServer.stop();
             httpsServer.stop();
@@ -223,7 +224,7 @@
         CompletableFuture[] responses = new CompletableFuture[LOOPS];
         final Path source = TestUtil.getAFile(FILESIZE);
         HttpRequest request = HttpRequest.newBuilder(uri)
-                                         .POST(fromFile(tempFile()))
+                                         .POST(fromFile(source))
                                          .build();
         for (int i = 0; i < LOOPS; i++) {
             responses[i] = client.sendAsync(request, asFile(tempFile()))
--- a/jdk/test/java/net/httpclient/http2/server/Http2TestServerConnection.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/net/httpclient/http2/server/Http2TestServerConnection.java	Thu Mar 16 20:47:03 2017 +0000
@@ -392,9 +392,11 @@
         //System.err.println ("Stream window size = " + winsize);
 
         final InputStream bis;
-        if (endStreamReceived) {
+        if (endStreamReceived && queue.size() == 0) {
+            System.err.println("Server: got END_STREAM for stream " + streamid);
             bis = NullInputStream.INSTANCE;
         } else {
+            System.err.println("Server: creating input stream for stream " + streamid);
             bis = new BodyInputStream(queue, streamid, this);
         }
         try (bis;
--- a/jdk/test/java/net/httpclient/security/Driver.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/net/httpclient/security/Driver.java	Thu Mar 16 20:47:03 2017 +0000
@@ -127,6 +127,7 @@
             cmd.add("-Dtest.src=" + testSrc);
             cmd.add("-Dtest.classes=" + testClasses);
             cmd.add("-Djava.security.manager");
+            cmd.add("--add-modules=jdk.incubator.httpclient");
             cmd.add("-Djava.security.policy=" + testSrc + sep + policy);
             cmd.add("-Dport.number=" + Integer.toString(Utils.getFreePort()));
             cmd.add("-Dport.number1=" + Integer.toString(Utils.getFreePort()));
--- a/jdk/test/java/nio/channels/AsyncCloseAndInterrupt.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/nio/channels/AsyncCloseAndInterrupt.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,7 @@
  * @bug 4460583 4470470 4840199 6419424 6710579 6596323 6824135 6395224 7142919
  *      8151582 8068693 8153209
  * @run main/othervm AsyncCloseAndInterrupt
+ * @key intermittent
  * @summary Comprehensive test of asynchronous closing and interruption
  * @author Mark Reinhold
  */
--- a/jdk/test/java/nio/channels/FileChannel/LoopingTruncate.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/nio/channels/FileChannel/LoopingTruncate.java	Thu Mar 16 20:47:03 2017 +0000
@@ -76,5 +76,8 @@
         } finally {
             Files.deleteIfExists(path);
         }
+
+        System.out.println("Test succeeded.");
+        System.out.flush();
     }
 }
--- a/jdk/test/java/nio/channels/FileChannel/Transfer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/nio/channels/FileChannel/Transfer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2012, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2017, 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
@@ -24,43 +24,53 @@
 /* @test
  * @bug 4434723 4482726 4559072 4638365 4795550 5081340 5103988 6253145
  *   6984545
- * @summary Test FileChannel.transferFrom and transferTo
+ * @summary Test FileChannel.transferFrom and transferTo (use -Dseed=X to set PRNG seed)
  * @library ..
+ * @library /lib/testlibrary/
+ * @build jdk.testlibrary.*
+ * @run testng Transfer
  * @key randomness
  */
 
-import java.io.*;
-import java.net.*;
-import java.nio.*;
-import java.nio.channels.*;
+import java.io.BufferedReader;
+import java.io.BufferedWriter;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.FileOutputStream;
+import java.io.InputStreamReader;
+import java.io.IOException;
+import java.io.OutputStreamWriter;
+import java.io.PrintStream;
+import java.io.RandomAccessFile;
+import java.io.Reader;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.net.InetAddress;
+import java.net.InetSocketAddress;
+import java.nio.ByteBuffer;
+import java.nio.channels.FileChannel;
+import java.nio.channels.NonReadableChannelException;
+import java.nio.channels.Pipe;
+import java.nio.channels.ServerSocketChannel;
+import java.nio.channels.SocketChannel;
 import java.nio.channels.spi.SelectorProvider;
 import java.nio.file.StandardOpenOption;
 import java.nio.file.FileAlreadyExistsException;
 import java.util.Random;
+import java.util.concurrent.TimeUnit;
 
+import jdk.testlibrary.RandomFactory;
+
+import org.testng.annotations.Test;
 
 public class Transfer {
 
-    private static Random generator = new Random();
-
-    private static int[] testSizes = {
-        0, 10, 1023, 1024, 1025, 2047, 2048, 2049 };
+    private static Random generator = RandomFactory.getRandom();
+    private static PrintStream err = System.err;
+    private static PrintStream out = System.out;
 
-    public static void main(String[] args) throws Exception {
-        testFileChannel();
-        for (int i=0; i<testSizes.length; i++)
-            testReadableByteChannel(testSizes[i]);
-        xferTest02(); // for bug 4482726
-        xferTest03(); // for bug 4559072
-        xferTest04(); // for bug 4638365
-        xferTest05(); // for bug 4638365
-        xferTest06(); // for bug 5081340
-        xferTest07(); // for bug 5103988
-        xferTest08(); // for bug 6253145
-        xferTest09(); // for bug 6984545
-    }
-
-    private static void testFileChannel() throws Exception {
+    @Test
+    public void testFileChannel() throws Exception {
         File source = File.createTempFile("source", null);
         source.deleteOnExit();
         File sink = File.createTempFile("sink", null);
@@ -105,52 +115,58 @@
         sink.delete();
     }
 
-    private static void testReadableByteChannel(int size) throws Exception {
-        SelectorProvider sp = SelectorProvider.provider();
-        Pipe p = sp.openPipe();
-        Pipe.SinkChannel sink = p.sink();
-        Pipe.SourceChannel source = p.source();
-        sink.configureBlocking(false);
+    @Test
+    public void testReadableByteChannel() throws Exception {
+        int[] testSizes = { 0, 10, 1023, 1024, 1025, 2047, 2048, 2049 };
 
-        ByteBuffer outgoingdata = ByteBuffer.allocateDirect(size + 10);
-        byte[] someBytes = new byte[size + 10];
-        generator.nextBytes(someBytes);
-        outgoingdata.put(someBytes);
-        outgoingdata.flip();
+        for (int size : testSizes) {
+            SelectorProvider sp = SelectorProvider.provider();
+            Pipe p = sp.openPipe();
+            Pipe.SinkChannel sink = p.sink();
+            Pipe.SourceChannel source = p.source();
+            sink.configureBlocking(false);
 
-        int totalWritten = 0;
-        while (totalWritten < size + 10) {
-            int written = sink.write(outgoingdata);
-            if (written < 0)
-                throw new Exception("Write failed");
-            totalWritten += written;
-        }
+            ByteBuffer outgoingdata = ByteBuffer.allocateDirect(size + 10);
+            byte[] someBytes = new byte[size + 10];
+            generator.nextBytes(someBytes);
+            outgoingdata.put(someBytes);
+            outgoingdata.flip();
 
-        File f = File.createTempFile("blah"+size, null);
-        f.deleteOnExit();
-        RandomAccessFile raf = new RandomAccessFile(f, "rw");
-        FileChannel fc = raf.getChannel();
-        long oldPosition = fc.position();
+            int totalWritten = 0;
+            while (totalWritten < size + 10) {
+                int written = sink.write(outgoingdata);
+                if (written < 0)
+                    throw new Exception("Write failed");
+                totalWritten += written;
+            }
 
-        long bytesWritten = fc.transferFrom(source, 0, size);
-        fc.force(true);
-        if (bytesWritten != size)
-            throw new RuntimeException("Transfer failed");
+            File f = File.createTempFile("blah"+size, null);
+            f.deleteOnExit();
+            RandomAccessFile raf = new RandomAccessFile(f, "rw");
+            FileChannel fc = raf.getChannel();
+            long oldPosition = fc.position();
 
-        if (fc.position() != oldPosition)
-            throw new RuntimeException("Position changed");
+            long bytesWritten = fc.transferFrom(source, 0, size);
+            fc.force(true);
+            if (bytesWritten != size)
+                throw new RuntimeException("Transfer failed");
 
-        if (fc.size() != size)
-            throw new RuntimeException("Unexpected sink size "+ fc.size());
+            if (fc.position() != oldPosition)
+                throw new RuntimeException("Position changed");
 
-        fc.close();
-        sink.close();
-        source.close();
+            if (fc.size() != size)
+                throw new RuntimeException("Unexpected sink size "+ fc.size());
 
-        f.delete();
+            fc.close();
+            sink.close();
+            source.close();
+
+            f.delete();
+        }
     }
 
-    public static void xferTest02() throws Exception {
+    @Test
+    public void xferTest02() throws Exception { // for bug 4482726
         byte[] srcData = new byte[5000];
         for (int i=0; i<5000; i++)
             srcData[i] = (byte)generator.nextInt();
@@ -187,7 +203,8 @@
         dest.delete();
     }
 
-    public static void xferTest03() throws Exception {
+    @Test
+    public void xferTest03() throws Exception { // for bug 4559072
         byte[] srcData = new byte[] {1,2,3,4} ;
 
         // get filechannel for the source file.
@@ -225,7 +242,8 @@
     }
 
     // Test transferTo with large file
-    public static void xferTest04() throws Exception {
+    @Test
+    public void xferTest04() throws Exception { // for bug 4638365
         // Windows and Linux can't handle the really large file sizes for a
         // truncate or a positional write required by the test for 4563125
         String osName = System.getProperty("os.name");
@@ -264,7 +282,8 @@
     }
 
     // Test transferFrom with large file
-    public static void xferTest05() throws Exception {
+    @Test
+    public void xferTest05() throws Exception { // for bug 4638365
         // Create a source file & large sink file for the test
         File source = File.createTempFile("blech", null);
         source.deleteOnExit();
@@ -294,7 +313,7 @@
                      testSize - 40);
         } catch (IOException e) {
             // Can't set up the test, abort it
-            System.err.println("xferTest05 was aborted.");
+            err.println("xferTest05 was aborted.");
             return;
         } finally {
             fc.close();
@@ -337,7 +356,8 @@
     }
 
     // Test transferFrom asking for more bytes than remain in source
-    public static void xferTest06() throws Exception {
+    @Test
+    public void xferTest06() throws Exception { // for bug 5081340
         String data = "Use the source, Luke!";
 
         File source = File.createTempFile("source", null);
@@ -370,7 +390,8 @@
     }
 
     // Test transferTo to non-blocking socket channel
-    public static void xferTest07() throws Exception {
+    @Test
+    public void xferTest07() throws Exception { // for bug 5103988
         File source = File.createTempFile("source", null);
         source.deleteOnExit();
 
@@ -405,7 +426,8 @@
 
 
     // Test transferTo with file positions larger than 2 and 4GB
-    public static void xferTest08() throws Exception {
+    @Test
+    public void xferTest08() throws Exception { // for bug 6253145
         // Creating a sparse 6GB file on Windows takes too long
         String osName = System.getProperty("os.name");
         if (osName.startsWith("Windows"))
@@ -421,10 +443,15 @@
         RandomAccessFile raf = new RandomAccessFile(file, "rw");
         FileChannel fc = raf.getChannel();
 
+        out.println("  Creating large file...");
+        long t0 = System.nanoTime();
         try {
             fc.write(ByteBuffer.wrap("0123456789012345".getBytes("UTF-8")), 6*G);
+            long t1 = System.nanoTime();
+            out.printf("  Created large file in %d ns (%d ms) %n",
+            t1 - t0, TimeUnit.NANOSECONDS.toMillis(t1 - t0));
         } catch (IOException x) {
-            System.err.println("Unable to create test file:" + x);
+            err.println("  Unable to create test file:" + x);
             fc.close();
             return;
         }
@@ -480,7 +507,10 @@
 
                 // write to file and transfer to echo server
                 fc.write(sendbuf, position);
+                t0 = System.nanoTime();
                 fc.transferTo(position, count, source);
+                out.printf("  transferTo(%d, %2d, source): %d ns%n",
+                    position, count, System.nanoTime() - t0);
 
                 // read from echo server
                 long nread = 0;
@@ -495,7 +525,7 @@
                 readbuf.flip();
                 sendbuf.flip();
                 if (!readbuf.equals(sendbuf))
-                    throw new RuntimeException("Echo'ed bytes do not match!");
+                    throw new RuntimeException("Echoed bytes do not match!");
                 readbuf.clear();
                 sendbuf.clear();
             }
@@ -509,7 +539,8 @@
 
     // Test that transferFrom with FileChannel source that is not readable
     // throws NonReadableChannelException
-    static void xferTest09() throws Exception {
+    @Test
+    public void xferTest09() throws Exception { // for bug 6984545
         File source = File.createTempFile("source", null);
         source.deleteOnExit();
 
--- a/jdk/test/java/nio/channels/Selector/SelectTimeout.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/nio/channels/Selector/SelectTimeout.java	Thu Mar 16 20:47:03 2017 +0000
@@ -30,14 +30,13 @@
  */
 import java.io.IOException;
 import java.nio.channels.Selector;
+import java.util.concurrent.atomic.AtomicBoolean;
+import java.util.concurrent.atomic.AtomicReference;
 
 public class SelectTimeout {
     private static final long BIG_TIMEOUT    = 100_000_001_000L; // 8165000
     private static final long BIGGER_TIMEOUT = 850_000_000_000_000L; // 8172547
-    private static final long SLEEP_MILLIS   = 10000;
-
-    private static volatile Exception theException;
-    private static volatile boolean isTimedOut;
+    private static final long SLEEP_MILLIS   = 10_000;
 
     public static void main(String[] args)
         throws IOException, InterruptedException {
@@ -59,17 +58,18 @@
 
     private static boolean test(final long timeout)
         throws InterruptedException, IOException {
-        theException = null;
+        AtomicReference<Exception> theException =
+            new AtomicReference<>();
+        AtomicBoolean isTimedOut = new AtomicBoolean();
 
         Selector selector = Selector.open();
 
         Thread t = new Thread(() -> {
             try {
-                isTimedOut = false;
                 selector.select(timeout);
-                isTimedOut = true;
+                isTimedOut.set(true);
             } catch (IOException ioe) {
-                theException = ioe;
+                theException.set(ioe);
             }
         });
         t.start();
@@ -77,8 +77,8 @@
         t.join(SLEEP_MILLIS);
 
         boolean result;
-        if (theException == null) {
-            if (timeout > SLEEP_MILLIS && isTimedOut) {
+        if (theException.get() == null) {
+            if (timeout > SLEEP_MILLIS && isTimedOut.get()) {
                 System.err.printf("Test timed out early with timeout %d%n",
                     timeout);
                 result = false;
@@ -88,11 +88,12 @@
             }
         } else {
             System.err.printf("Test failed with timeout %d%n", timeout);
-            theException.printStackTrace();
+            theException.get().printStackTrace();
             result = false;
         }
 
         t.interrupt();
+        selector.close();
 
         return result;
     }
--- a/jdk/test/java/nio/channels/Selector/WakeupAfterClose.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/nio/channels/Selector/WakeupAfterClose.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2017, 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
@@ -24,10 +24,12 @@
 /* @test
  * @bug 6524172
  * @summary Invoking wakeup on closed Selector can throw NPE if close resets interrupt status
+ * @key intermittent
  */
 
+import java.io.IOException;
+import java.nio.channels.ClosedSelectorException;
 import java.nio.channels.Selector;
-import java.io.IOException;
 
 public class WakeupAfterClose {
 
@@ -40,6 +42,9 @@
                     sel.select();
                 } catch (IOException x) {
                     x.printStackTrace();
+                } catch (ClosedSelectorException y) {
+                    System.err.println
+                        ("Caught expected ClosedSelectorException");
                 }
             }
         };
--- a/jdk/test/java/nio/file/FileSystem/Basic.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/nio/file/FileSystem/Basic.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 2017, 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
@@ -30,11 +30,18 @@
  */
 
 import java.io.File;
-import java.nio.file.*;
 import java.io.IOException;
 import java.net.URI;
 import java.net.URISyntaxException;
+import java.nio.file.Files;
+import java.nio.file.FileStore;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.ProviderNotFoundException;
 import java.util.HashMap;
+import java.util.concurrent.TimeUnit;
 import jdk.testlibrary.FileUtils;
 
 /**
@@ -47,6 +54,44 @@
             throw new RuntimeException(msg);
     }
 
+    static void checkFileStores(String os, FileSystem fs) throws IOException {
+        boolean checkFileStores = true;
+        if (!os.equals("Windows")) {
+            // try to check whether 'df' hangs
+            System.out.println("\n--- Begin df output ---");
+            System.out.flush();
+            Process proc = new ProcessBuilder("df").inheritIO().start();
+            try {
+                proc.waitFor(90, TimeUnit.SECONDS);
+            } catch (InterruptedException ignored) {
+            }
+            System.out.println("--- End df output ---\n");
+            System.out.flush();
+            try {
+                int exitValue = proc.exitValue();
+                if (exitValue != 0) {
+                    System.err.printf("df process exited with %d != 0%n",
+                        exitValue);
+                    checkFileStores = false;
+                }
+            } catch (IllegalThreadStateException ignored) {
+                System.err.println("df command apparently hung");
+                checkFileStores = false;
+            }
+        }
+
+        // sanity check method
+        if (checkFileStores) {
+            System.out.println("\n--- Begin FileStores ---");
+            for (FileStore store: fs.getFileStores()) {
+                System.out.println(store);
+            }
+            System.out.println("--- EndFileStores ---\n");
+        } else {
+            System.err.println("Skipping FileStore check due to df failure");
+        }
+    }
+
     static void checkSupported(FileSystem fs, String... views) {
         for (String view: views) {
             check(fs.supportedFileAttributeViews().contains(view),
@@ -70,7 +115,9 @@
         }
     }
 
-    public static void main(String[] args) throws IOException, URISyntaxException {
+    public static void main(String[] args)
+        throws IOException, URISyntaxException {
+        String os = System.getProperty("os.name");
         FileSystem fs = FileSystems.getDefault();
 
         // close should throw UOE
@@ -85,15 +132,11 @@
         check(fs.provider().getScheme().equals("file"),
             "should use 'file' scheme");
 
-        // santity check method - need to re-visit this in future as I/O errors
-        // are possible
-        for (FileStore store: fs.getFileStores()) {
-            System.out.println(store);
-        }
+        // sanity check FileStores
+        checkFileStores(os, fs);
 
         // sanity check supportedFileAttributeViews
         checkSupported(fs, "basic");
-        String os = System.getProperty("os.name");
         if (os.equals("SunOS"))
             checkSupported(fs, "posix", "unix", "owner", "acl", "user");
         if (os.equals("Linux"))
--- a/jdk/test/java/security/Provider/ProviderVersionCheck.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/security/Provider/ProviderVersionCheck.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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
@@ -42,7 +42,7 @@
 
         for (Provider p: Security.getProviders()) {
             System.out.print(p.getName() + " ");
-            if (p.getVersion() != 9.0d) {
+            if (p.getVersion() != 10.0d) {
                 System.out.println("failed. " + "Version received was " +
                         p.getVersion());
                 failure = true;
--- a/jdk/test/java/security/modules/ModularTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/security/modules/ModularTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -164,9 +164,9 @@
         final Builder builder;
         if (moduleType == MODULE_TYPE.EXPLICIT) {
             System.out.format(" %nGenerating ModuleDescriptor object");
-            builder = ModuleDescriptor.module(moduleName).exports(pkg);
+            builder = ModuleDescriptor.newModule(moduleName).exports(pkg);
             if (isService && serviceInterface != null && serviceImpl != null) {
-                builder.provides(serviceInterface, serviceImpl);
+                builder.provides(serviceInterface, List.of(serviceImpl));
             } else {
                 if (serviceInterface != null) {
                     builder.uses(serviceInterface);
--- a/jdk/test/java/security/testlibrary/Proc.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/security/testlibrary/Proc.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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
@@ -176,6 +176,14 @@
         prop.put(a, b);
         return this;
     }
+    // Inherit the value of a system property
+    public Proc inheritProp(String k) {
+        String v = System.getProperty(k);
+        if (v != null) {
+            prop.put(k, v);
+        }
+        return this;
+    }
     // Sets classpath. If not called, Proc will choose a classpath. If called
     // with no arg, no classpath will be used. Can be called multiple times.
     public Proc cp(String... s) {
--- a/jdk/test/java/time/TEST.properties	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/time/TEST.properties	Thu Mar 16 20:47:03 2017 +0000
@@ -1,6 +1,5 @@
-# Threeten test uses TestNG
+# java.time tests use TestNG
 TestNG.dirs = .
 othervm.dirs = tck/java/time/chrono test/java/time/chrono test/java/time/format
 lib.dirs = ../../lib/testlibrary
 lib.build = jdk.testlibrary.RandomFactory
-modules = java.base/java.time:open java.base/java.time.chrono:open java.base/java.time.zone:open
--- a/jdk/test/java/time/tck/java/time/AbstractTCKTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/time/tck/java/time/AbstractTCKTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -69,14 +69,35 @@
 import java.io.ObjectOutputStream;
 import java.io.ObjectStreamConstants;
 import java.io.Serializable;
-import java.lang.reflect.Field;
 import java.util.Formatter;
+import java.util.Map;
 
 /**
  * Base test class.
  */
 public abstract class AbstractTCKTest {
 
+    /**
+     * Map from package name to the serialVersionUID of the .Ser class for the package.
+     */
+    private static Map<String, Long> serialVersionUIDs = Map.of(
+                "java.time",        -7683839454370182990L,
+                "java.time.chrono", -6103370247208168577L,
+                "java.time.zone",   -8885321777449118786L
+                );
+
+    /**
+     * Returns the serialVersionUID for the class.
+     * The SUIDs are defined by the specification for each class.
+     * @param serClass the class to return the SUID of
+     * @return returns the serialVersionUID for the class
+     */
+    public final static long getSUID(Class<?> serClass) {
+        String pkgName = serClass.getPackageName();
+        return serialVersionUIDs.get(pkgName);
+    }
+
+
     protected static boolean isIsoLeap(long year) {
         if (year % 4 != 0) {
             return false;
@@ -111,10 +132,8 @@
 
     protected static void assertSerializedBySer(Object object, byte[] expectedBytes, byte[]... matches) throws Exception {
         String serClass = object.getClass().getPackage().getName() + ".Ser";
-        Class<?> serCls = Class.forName(serClass);
-        Field field = serCls.getDeclaredField("serialVersionUID");
-        field.setAccessible(true);
-        long serVer = (Long) field.get(null);
+        long serVer = getSUID(object.getClass());
+
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         try (ObjectOutputStream oos = new ObjectOutputStream(baos) ) {
             oos.writeObject(object);
@@ -172,9 +191,8 @@
      * @throws Exception if an unexpected condition occurs
      */
     protected static void assertNotSerializable(Class<?> serClass) throws Exception {
-        Field field = serClass.getDeclaredField("serialVersionUID");
-        field.setAccessible(true);
-        long serVer = (Long) field.get(null);
+        long serVer = getSUID(serClass);
+
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         try (DataOutputStream out = new DataOutputStream(baos)) {
             out.writeShort(ObjectStreamConstants.STREAM_MAGIC);
@@ -201,7 +219,6 @@
         fail("Class should not be deserializable " + serClass.getName());
     }
 
-
     /**
      * Utility method to dump a byte array in a java syntax.
      * @param bytes and array of bytes
--- a/jdk/test/java/time/tck/java/time/TCKOffsetDateTime.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/time/tck/java/time/TCKOffsetDateTime.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -104,8 +104,6 @@
 import static org.testng.Assert.assertTrue;
 import static org.testng.Assert.fail;
 
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
 import java.time.Clock;
 import java.time.DateTimeException;
 import java.time.Duration;
@@ -470,24 +468,12 @@
     //-----------------------------------------------------------------------
     @Test(expectedExceptions=NullPointerException.class)
     public void constructor_nullTime() throws Throwable  {
-        Constructor<OffsetDateTime> con = OffsetDateTime.class.getDeclaredConstructor(LocalDateTime.class, ZoneOffset.class);
-        con.setAccessible(true);
-        try {
-            con.newInstance(null, OFFSET_PONE);
-        } catch (InvocationTargetException ex) {
-            throw ex.getCause();
-        }
+        OffsetDateTime.of(null, OFFSET_PONE);
     }
 
     @Test(expectedExceptions=NullPointerException.class)
     public void constructor_nullOffset() throws Throwable  {
-        Constructor<OffsetDateTime> con = OffsetDateTime.class.getDeclaredConstructor(LocalDateTime.class, ZoneOffset.class);
-        con.setAccessible(true);
-        try {
-            con.newInstance(LocalDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30)), null);
-        } catch (InvocationTargetException ex) {
-            throw ex.getCause();
-        }
+        OffsetDateTime.of(LocalDateTime.of(LocalDate.of(2008, 6, 30), LocalTime.of(11, 30)), null);
     }
 
     //-----------------------------------------------------------------------
--- a/jdk/test/java/time/tck/java/time/TCKOffsetTime.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/time/tck/java/time/TCKOffsetTime.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -89,8 +89,6 @@
 import static org.testng.Assert.assertTrue;
 import static org.testng.Assert.fail;
 
-import java.lang.reflect.Constructor;
-import java.lang.reflect.InvocationTargetException;
 import java.time.Clock;
 import java.time.DateTimeException;
 import java.time.Instant;
@@ -465,28 +463,16 @@
     }
 
     //-----------------------------------------------------------------------
-    // constructor
+    // constructor via factory
     //-----------------------------------------------------------------------
     @Test(expectedExceptions=NullPointerException.class)
     public void constructor_nullTime() throws Throwable  {
-        Constructor<OffsetTime> con = OffsetTime.class.getDeclaredConstructor(LocalTime.class, ZoneOffset.class);
-        con.setAccessible(true);
-        try {
-            con.newInstance(null, OFFSET_PONE);
-        } catch (InvocationTargetException ex) {
-            throw ex.getCause();
-        }
+        OffsetTime.of(null, OFFSET_PONE);
     }
 
     @Test(expectedExceptions=NullPointerException.class)
     public void constructor_nullOffset() throws Throwable  {
-        Constructor<OffsetTime> con = OffsetTime.class.getDeclaredConstructor(LocalTime.class, ZoneOffset.class);
-        con.setAccessible(true);
-        try {
-            con.newInstance(LocalTime.of(11, 30, 0, 0), null);
-        } catch (InvocationTargetException ex) {
-            throw ex.getCause();
-        }
+       OffsetTime.of(LocalTime.of(11, 30, 0, 0), null);
     }
 
     //-----------------------------------------------------------------------
--- a/jdk/test/java/time/tck/java/time/serial/TCKZoneIdSerialization.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/time/tck/java/time/serial/TCKZoneIdSerialization.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -63,8 +63,11 @@
 import org.testng.annotations.Test;
 import tck.java.time.AbstractTCKTest;
 
-import java.io.*;
-import java.lang.reflect.Field;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.DataOutputStream;
+import java.io.ObjectInputStream;
+import java.io.ObjectStreamConstants;
 import java.time.DateTimeException;
 import java.time.ZoneId;
 import java.time.zone.ZoneRulesException;
@@ -153,10 +156,8 @@
 
     private ZoneId deserialize(String id) throws Exception {
         String serClass = ZoneId.class.getPackage().getName() + ".Ser";
-        Class<?> serCls = Class.forName(serClass);
-        Field field = serCls.getDeclaredField("serialVersionUID");
-        field.setAccessible(true);
-        long serVer = (Long) field.get(null);
+        long serVer = getSUID(ZoneId.class);
+
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
         try (DataOutputStream dos = new DataOutputStream(baos)) {
             dos.writeShort(ObjectStreamConstants.STREAM_MAGIC);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/time/test/java/time/TEST.properties	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,2 @@
+# java.time test system clock
+modules = java.base/java.time:open
--- a/jdk/test/java/util/ServiceLoader/modules/BadProvidersTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/ServiceLoader/modules/BadProvidersTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -90,7 +90,7 @@
         Layer bootLayer = Layer.boot();
 
         Configuration cf = bootLayer.configuration()
-                .resolveRequiresAndUses(finder, ModuleFinder.of(), Set.of(moduleName));
+                .resolveAndBind(finder, ModuleFinder.of(), Set.of(moduleName));
 
         ClassLoader scl = ClassLoader.getSystemClassLoader();
 
--- a/jdk/test/java/util/ServiceLoader/modules/Basic.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/ServiceLoader/modules/Basic.java	Thu Mar 16 20:47:03 2017 +0000
@@ -311,17 +311,17 @@
         ModuleFinder finder = ModuleFinder.of(dir);
 
         // layer1
-        Configuration cf1 = cf0.resolveRequiresAndUses(finder, ModuleFinder.of(), Set.of());
+        Configuration cf1 = cf0.resolveAndBind(finder, ModuleFinder.of(), Set.of());
         Layer layer1 = bootLayer.defineModulesWithOneLoader(cf1, scl);
         assertTrue(layer1.modules().size() == 1);
 
         // layer2
-        Configuration cf2 = cf0.resolveRequiresAndUses(finder, ModuleFinder.of(), Set.of());
+        Configuration cf2 = cf0.resolveAndBind(finder, ModuleFinder.of(), Set.of());
         Layer layer2 = bootLayer.defineModulesWithOneLoader(cf2, scl);
         assertTrue(layer2.modules().size() == 1);
 
         // layer3 with layer1 and layer2 as parents
-        Configuration cf3 = Configuration.resolveRequiresAndUses(finder,
+        Configuration cf3 = Configuration.resolveAndBind(finder,
                 List.of(cf1, cf2),
                 ModuleFinder.of(),
                 Set.of());
@@ -413,7 +413,7 @@
         Collections.addAll(roots, modules);
         Layer bootLayer = Layer.boot();
         Configuration parent = bootLayer.configuration();
-        Configuration cf = parent.resolveRequires(finder, ModuleFinder.of(), roots);
+        Configuration cf = parent.resolve(finder, ModuleFinder.of(), roots);
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer = bootLayer.defineModulesWithOneLoader(cf, scl);
         assertTrue(layer.modules().size() == 1);
--- a/jdk/test/java/util/Spliterator/SpliteratorCollisions.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/Spliterator/SpliteratorCollisions.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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
@@ -24,20 +24,19 @@
 /**
  * @test
  * @bug 8005698
+ * @library ../stream/bootlib
+ * @build java.base/java.util.SpliteratorTestHelper
  * @run testng SpliteratorCollisions
  * @summary Spliterator traversing and splitting hash maps containing colliding hashes
- * @author Brent Christian
  */
 
 import org.testng.annotations.DataProvider;
 import org.testng.annotations.Test;
 
-import java.util.ArrayDeque;
 import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Collections;
-import java.util.Deque;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.LinkedHashMap;
@@ -45,19 +44,15 @@
 import java.util.List;
 import java.util.Map;
 import java.util.Spliterator;
+import java.util.SpliteratorTestHelper;
 import java.util.TreeSet;
-import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.function.Supplier;
 import java.util.function.UnaryOperator;
 
-import static org.testng.Assert.*;
-import static org.testng.Assert.assertEquals;
+public class SpliteratorCollisions extends SpliteratorTestHelper {
 
-@Test
-public class SpliteratorCollisions {
-
-    private static List<Integer> SIZES = Arrays.asList(0, 1, 10, 100, 1000);
+    private static final List<Integer> SIZES = Arrays.asList(0, 1, 10, 100, 1000);
 
     private static class SpliteratorDataBuilder<T> {
         List<Object[]> data;
@@ -214,492 +209,134 @@
     }
 
     @Test(dataProvider = "HashableIntSpliterator")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testNullPointerException(String description, Collection exp, Supplier<Spliterator> s) {
+    void testNullPointerException(String description,
+                                  Collection<HashableInteger> exp,
+                                  Supplier<Spliterator<HashableInteger>> s) {
         executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining(null));
         executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance(null));
     }
 
     @Test(dataProvider = "HashableIntSpliteratorWithNull")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testNullPointerExceptionWithNull(String description, Collection exp, Supplier<Spliterator> s) {
+    void testNullPointerExceptionWithNull(String description,
+                                          Collection<HashableInteger> exp,
+                                          Supplier<Spliterator<HashableInteger>> s) {
         executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining(null));
         executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance(null));
     }
 
 
     @Test(dataProvider = "HashableIntSpliterator")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testForEach(String description, Collection exp, Supplier<Spliterator> s) {
-        testForEach(exp, s, (Consumer<Object> b) -> b);
-    }
-
-    @Test(dataProvider = "HashableIntSpliteratorWithNull")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testForEachWithNull(String description, Collection exp, Supplier<Spliterator> s) {
-        testForEach(exp, s, (Consumer<Object> b) -> b);
-    }
-
-
-    @Test(dataProvider = "HashableIntSpliterator")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testTryAdvance(String description, Collection exp, Supplier<Spliterator> s) {
-        testTryAdvance(exp, s, (Consumer<Object> b) -> b);
+    void testForEach(String description,
+                     Collection<HashableInteger> exp,
+                     Supplier<Spliterator<HashableInteger>> s) {
+        testForEach(exp, s, UnaryOperator.identity());
     }
 
     @Test(dataProvider = "HashableIntSpliteratorWithNull")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testTryAdvanceWithNull(String description, Collection exp, Supplier<Spliterator> s) {
-        testTryAdvance(exp, s, (Consumer<Object> b) -> b);
-    }
-
-/* skip this test until 8013649 is fixed
-    @Test(dataProvider = "HashableIntSpliterator")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testMixedTryAdvanceForEach(String description, Collection exp, Supplier<Spliterator> s) {
-        testMixedTryAdvanceForEach(exp, s, (Consumer<Object> b) -> b);
-    }
-
-    @Test(dataProvider = "HashableIntSpliteratorWithNull")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testMixedTryAdvanceForEachWithNull(String description, Collection exp, Supplier<Spliterator> s) {
-        testMixedTryAdvanceForEach(exp, s, (Consumer<Object> b) -> b);
-    }
-*/
-
-    @Test(dataProvider = "HashableIntSpliterator")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testSplitAfterFullTraversal(String description, Collection exp, Supplier<Spliterator> s) {
-        testSplitAfterFullTraversal(s, (Consumer<Object> b) -> b);
-    }
-
-    @Test(dataProvider = "HashableIntSpliteratorWithNull")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testSplitAfterFullTraversalWithNull(String description, Collection exp, Supplier<Spliterator> s) {
-        testSplitAfterFullTraversal(s, (Consumer<Object> b) -> b);
+    void testForEachWithNull(String description,
+                             Collection<HashableInteger> exp,
+                             Supplier<Spliterator<HashableInteger>> s) {
+        testForEach(exp, s, UnaryOperator.identity());
     }
 
 
     @Test(dataProvider = "HashableIntSpliterator")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testSplitOnce(String description, Collection exp, Supplier<Spliterator> s) {
-        testSplitOnce(exp, s, (Consumer<Object> b) -> b);
+    void testTryAdvance(String description,
+                        Collection<HashableInteger> exp,
+                        Supplier<Spliterator<HashableInteger>> s) {
+        testTryAdvance(exp, s, UnaryOperator.identity());
     }
 
     @Test(dataProvider = "HashableIntSpliteratorWithNull")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testSplitOnceWithNull(String description, Collection exp, Supplier<Spliterator> s) {
-        testSplitOnce(exp, s, (Consumer<Object> b) -> b);
+    void testTryAdvanceWithNull(String description,
+                                Collection<HashableInteger> exp,
+                                Supplier<Spliterator<HashableInteger>> s) {
+        testTryAdvance(exp, s, UnaryOperator.identity());
     }
 
     @Test(dataProvider = "HashableIntSpliterator")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testSplitSixDeep(String description, Collection exp, Supplier<Spliterator> s) {
-        testSplitSixDeep(exp, s, (Consumer<Object> b) -> b);
+    void testMixedTryAdvanceForEach(String description,
+                                    Collection<HashableInteger> exp,
+                                    Supplier<Spliterator<HashableInteger>> s) {
+        testMixedTryAdvanceForEach(exp, s, UnaryOperator.identity());
     }
 
     @Test(dataProvider = "HashableIntSpliteratorWithNull")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testSplitSixDeepWithNull(String description, Collection exp, Supplier<Spliterator> s) {
-        testSplitSixDeep(exp, s, (Consumer<Object> b) -> b);
+    void testMixedTryAdvanceForEachWithNull(String description,
+                                            Collection<HashableInteger> exp,
+                                            Supplier<Spliterator<HashableInteger>> s) {
+        testMixedTryAdvanceForEach(exp, s, UnaryOperator.identity());
     }
 
     @Test(dataProvider = "HashableIntSpliterator")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testSplitUntilNull(String description, Collection exp, Supplier<Spliterator> s) {
-        testSplitUntilNull(exp, s, (Consumer<Object> b) -> b);
+    void testMixedTraverseAndSplit(String description,
+                                   Collection<HashableInteger> exp,
+                                   Supplier<Spliterator<HashableInteger>> s) {
+        testMixedTraverseAndSplit(exp, s, UnaryOperator.identity());
+    }
+
+    @Test(dataProvider = "HashableIntSpliteratorWithNull")
+    void testMixedTraverseAndSplitWithNull(String description,
+                                           Collection<HashableInteger> exp,
+                                           Supplier<Spliterator<HashableInteger>> s) {
+        testMixedTraverseAndSplit(exp, s, UnaryOperator.identity());
+    }
+
+    @Test(dataProvider = "HashableIntSpliterator")
+    void testSplitAfterFullTraversal(String description,
+                                     Collection<HashableInteger> exp,
+                                     Supplier<Spliterator<HashableInteger>> s) {
+        testSplitAfterFullTraversal(s, UnaryOperator.identity());
     }
 
     @Test(dataProvider = "HashableIntSpliteratorWithNull")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testSplitUntilNullWithNull(String description, Collection exp, Supplier<Spliterator> s) {
-        testSplitUntilNull(exp, s, (Consumer<Object> b) -> b);
-    }
-
-    private static <T, S extends Spliterator<T>> void testForEach(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        ArrayList<T> fromForEach = new ArrayList<>();
-        spliterator = supplier.get();
-        Consumer<T> addToFromForEach = boxingAdapter.apply(fromForEach::add);
-        spliterator.forEachRemaining(addToFromForEach);
-
-        // Assert that forEach now produces no elements
-        spliterator.forEachRemaining(boxingAdapter.apply(e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
-        // Assert that tryAdvance now produce no elements
-        spliterator.tryAdvance(boxingAdapter.apply(e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
-
-        // assert that size, tryAdvance, and forEach are consistent
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, exp.size());
-        }
-        if (exp.contains(null)) {
-            assertTrue(fromForEach.contains(null));
-        }
-        assertEquals(fromForEach.size(), exp.size());
-
-        assertContents(fromForEach, exp, isOrdered);
-    }
-
-    private static <T, S extends Spliterator<T>> void testTryAdvance(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        spliterator = supplier.get();
-        ArrayList<T> fromTryAdvance = new ArrayList<>();
-        Consumer<T> addToFromTryAdvance = boxingAdapter.apply(fromTryAdvance::add);
-        while (spliterator.tryAdvance(addToFromTryAdvance)) { }
-
-        // Assert that forEach now produces no elements
-        spliterator.forEachRemaining(boxingAdapter.apply(e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
-        // Assert that tryAdvance now produce no elements
-        spliterator.tryAdvance(boxingAdapter.apply(e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
-
-        // assert that size, tryAdvance, and forEach are consistent
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, exp.size());
-        }
-        assertEquals(fromTryAdvance.size(), exp.size());
-
-        assertContents(fromTryAdvance, exp, isOrdered);
+    void testSplitAfterFullTraversalWithNull(String description,
+                                             Collection<HashableInteger> exp,
+                                             Supplier<Spliterator<HashableInteger>> s) {
+        testSplitAfterFullTraversal(s, UnaryOperator.identity());
     }
 
-    private static <T, S extends Spliterator<T>> void testMixedTryAdvanceForEach(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
 
-        // tryAdvance first few elements, then forEach rest
-        ArrayList<T> dest = new ArrayList<>();
-        spliterator = supplier.get();
-        Consumer<T> addToDest = boxingAdapter.apply(dest::add);
-        for (int i = 0; i < 10 && spliterator.tryAdvance(addToDest); i++) { }
-        spliterator.forEachRemaining(addToDest);
-
-        // Assert that forEach now produces no elements
-        spliterator.forEachRemaining(boxingAdapter.apply(e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
-        // Assert that tryAdvance now produce no elements
-        spliterator.tryAdvance(boxingAdapter.apply(e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
-
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, dest.size());
-        }
-        assertEquals(dest.size(), exp.size());
-
-        if (isOrdered) {
-            assertEquals(dest, exp);
-        }
-        else {
-            assertContentsUnordered(dest, exp);
-        }
+    @Test(dataProvider = "HashableIntSpliterator")
+    void testSplitOnce(String description,
+                       Collection<HashableInteger> exp,
+                       Supplier<Spliterator<HashableInteger>> s) {
+        testSplitOnce(exp, s, UnaryOperator.identity());
     }
 
-    private static <T, S extends Spliterator<T>> void testSplitAfterFullTraversal(
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        // Full traversal using tryAdvance
-        Spliterator<T> spliterator = supplier.get();
-        while (spliterator.tryAdvance(boxingAdapter.apply(e -> { }))) { }
-        Spliterator<T> split = spliterator.trySplit();
-        assertNull(split);
-
-        // Full traversal using forEach
-        spliterator = supplier.get();
-        spliterator.forEachRemaining(boxingAdapter.apply(e -> {
-        }));
-        split = spliterator.trySplit();
-        assertNull(split);
-
-        // Full traversal using tryAdvance then forEach
-        spliterator = supplier.get();
-        spliterator.tryAdvance(boxingAdapter.apply(e -> { }));
-        spliterator.forEachRemaining(boxingAdapter.apply(e -> {
-        }));
-        split = spliterator.trySplit();
-        assertNull(split);
-    }
-
-    private static <T, S extends Spliterator<T>> void testSplitOnce(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        ArrayList<T> fromSplit = new ArrayList<>();
-        Spliterator<T> s1 = supplier.get();
-        Spliterator<T> s2 = s1.trySplit();
-        long s1Size = s1.getExactSizeIfKnown();
-        long s2Size = (s2 != null) ? s2.getExactSizeIfKnown() : 0;
-
-        Consumer<T> addToFromSplit = boxingAdapter.apply(fromSplit::add);
-        if (s2 != null)
-            s2.forEachRemaining(addToFromSplit);
-        s1.forEachRemaining(addToFromSplit);
-
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, fromSplit.size());
-            if (s1Size >= 0 && s2Size >= 0)
-                assertEquals(sizeIfKnown, s1Size + s2Size);
-        }
-        assertContents(fromSplit, exp, isOrdered);
-    }
-
-    private static <T, S extends Spliterator<T>> void testSplitSixDeep(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        S spliterator = supplier.get();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        for (int depth=0; depth < 6; depth++) {
-            List<T> dest = new ArrayList<>();
-            spliterator = supplier.get();
-
-            assertSpliterator(spliterator);
-
-            // verify splitting with forEach
-            visit(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), false);
-            assertContents(dest, exp, isOrdered);
-
-            // verify splitting with tryAdvance
-            dest.clear();
-            spliterator = supplier.get();
-            visit(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), true);
-            assertContents(dest, exp, isOrdered);
-        }
+    @Test(dataProvider = "HashableIntSpliteratorWithNull")
+    void testSplitOnceWithNull(String description,
+                               Collection<HashableInteger> exp,
+                               Supplier<Spliterator<HashableInteger>> s) {
+        testSplitOnce(exp, s, UnaryOperator.identity());
     }
 
-    private static <T, S extends Spliterator<T>> void visit(int depth, int curLevel,
-                                                            List<T> dest, S spliterator, UnaryOperator<Consumer<T>> boxingAdapter,
-                                                            int rootCharacteristics, boolean useTryAdvance) {
-        if (curLevel < depth) {
-            long beforeSize = spliterator.getExactSizeIfKnown();
-            Spliterator<T> split = spliterator.trySplit();
-            if (split != null) {
-                assertSpliterator(split, rootCharacteristics);
-                assertSpliterator(spliterator, rootCharacteristics);
-
-                if ((rootCharacteristics & Spliterator.SUBSIZED) != 0 &&
-                    (rootCharacteristics & Spliterator.SIZED) != 0) {
-                    assertEquals(beforeSize, split.estimateSize() + spliterator.estimateSize());
-                }
-                visit(depth, curLevel + 1, dest, split, boxingAdapter, rootCharacteristics, useTryAdvance);
-            }
-            visit(depth, curLevel + 1, dest, spliterator, boxingAdapter, rootCharacteristics, useTryAdvance);
-        }
-        else {
-            long sizeIfKnown = spliterator.getExactSizeIfKnown();
-            if (useTryAdvance) {
-                Consumer<T> addToDest = boxingAdapter.apply(dest::add);
-                int count = 0;
-                while (spliterator.tryAdvance(addToDest)) {
-                    ++count;
-                }
-
-                if (sizeIfKnown >= 0)
-                    assertEquals(sizeIfKnown, count);
-
-                // Assert that forEach now produces no elements
-                spliterator.forEachRemaining(boxingAdapter.apply(e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
-
-                Spliterator<T> split = spliterator.trySplit();
-                assertNull(split);
-            }
-            else {
-                List<T> leafDest = new ArrayList<>();
-                Consumer<T> addToLeafDest = boxingAdapter.apply(leafDest::add);
-                spliterator.forEachRemaining(addToLeafDest);
-
-                if (sizeIfKnown >= 0)
-                    assertEquals(sizeIfKnown, leafDest.size());
-
-                // Assert that forEach now produces no elements
-                spliterator.tryAdvance(boxingAdapter.apply(e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
-
-                Spliterator<T> split = spliterator.trySplit();
-                assertNull(split);
-
-                dest.addAll(leafDest);
-            }
-        }
-    }
-
-    private static <T, S extends Spliterator<T>> void testSplitUntilNull(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        Spliterator<T> s = supplier.get();
-        boolean isOrdered = s.hasCharacteristics(Spliterator.ORDERED);
-        assertSpliterator(s);
-
-        List<T> splits = new ArrayList<>();
-        Consumer<T> c = boxingAdapter.apply(splits::add);
-
-        testSplitUntilNull(new SplitNode<T>(c, s));
-        assertContents(splits, exp, isOrdered);
-    }
-
-    private static class SplitNode<T> {
-        // Constant for every node
-        final Consumer<T> c;
-        final int rootCharacteristics;
-
-        final Spliterator<T> s;
-
-        SplitNode(Consumer<T> c, Spliterator<T> s) {
-            this(c, s.characteristics(), s);
-        }
-
-        private SplitNode(Consumer<T> c, int rootCharacteristics, Spliterator<T> s) {
-            this.c = c;
-            this.rootCharacteristics = rootCharacteristics;
-            this.s = s;
-        }
-
-        SplitNode<T> fromSplit(Spliterator<T> split) {
-            return new SplitNode<>(c, rootCharacteristics, split);
-        }
+    @Test(dataProvider = "HashableIntSpliterator")
+    void testSplitSixDeep(String description,
+                          Collection<HashableInteger> exp,
+                          Supplier<Spliterator<HashableInteger>> s) {
+        testSplitSixDeep(exp, s, UnaryOperator.identity());
     }
 
-    /**
-     * Set the maximum stack capacity to 0.25MB. This should be more than enough to detect a bad spliterator
-     * while not unduly disrupting test infrastructure given the test data sizes that are used are small.
-     * Note that j.u.c.ForkJoinPool sets the max queue size to 64M (1 << 26).
-     */
-    private static final int MAXIMUM_STACK_CAPACITY = 1 << 18; // 0.25MB
-
-    private static <T> void testSplitUntilNull(SplitNode<T> e) {
-        // Use an explicit stack to avoid a StackOverflowException when testing a Spliterator
-        // that when repeatedly split produces a right-balanced (and maybe degenerate) tree, or
-        // for a spliterator that is badly behaved.
-        Deque<SplitNode<T>> stack = new ArrayDeque<>();
-        stack.push(e);
-
-        int iteration = 0;
-        while (!stack.isEmpty()) {
-            assertTrue(iteration++ < MAXIMUM_STACK_CAPACITY, "Exceeded maximum stack modification count of 1 << 18");
-
-            e = stack.pop();
-            Spliterator<T> parentAndRightSplit = e.s;
-
-            long parentEstimateSize = parentAndRightSplit.estimateSize();
-            assertTrue(parentEstimateSize >= 0,
-                       String.format("Split size estimate %d < 0", parentEstimateSize));
-
-            long parentSize = parentAndRightSplit.getExactSizeIfKnown();
-            Spliterator<T> leftSplit = parentAndRightSplit.trySplit();
-            if (leftSplit == null) {
-                parentAndRightSplit.forEachRemaining(e.c);
-                continue;
-            }
-
-            assertSpliterator(leftSplit, e.rootCharacteristics);
-            assertSpliterator(parentAndRightSplit, e.rootCharacteristics);
-
-            if (parentEstimateSize != Long.MAX_VALUE && leftSplit.estimateSize() > 0 && parentAndRightSplit.estimateSize() > 0) {
-                assertTrue(leftSplit.estimateSize() < parentEstimateSize,
-                           String.format("Left split size estimate %d >= parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize));
-                assertTrue(parentAndRightSplit.estimateSize() < parentEstimateSize,
-                           String.format("Right split size estimate %d >= parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize));
-            }
-            else {
-                assertTrue(leftSplit.estimateSize() <= parentEstimateSize,
-                           String.format("Left split size estimate %d > parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize));
-                assertTrue(parentAndRightSplit.estimateSize() <= parentEstimateSize,
-                           String.format("Right split size estimate %d > parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize));
-            }
-
-            long leftSize = leftSplit.getExactSizeIfKnown();
-            long rightSize = parentAndRightSplit.getExactSizeIfKnown();
-            if (parentSize >= 0 && leftSize >= 0 && rightSize >= 0)
-                assertEquals(parentSize, leftSize + rightSize,
-                             String.format("exact left split size %d + exact right split size %d != parent exact split size %d",
-                                           leftSize, rightSize, parentSize));
-
-            // Add right side to stack first so left side is popped off first
-            stack.push(e.fromSplit(parentAndRightSplit));
-            stack.push(e.fromSplit(leftSplit));
-        }
+    @Test(dataProvider = "HashableIntSpliteratorWithNull")
+    void testSplitSixDeepWithNull(String description,
+                                  Collection<HashableInteger> exp,
+                                  Supplier<Spliterator<HashableInteger>> s) {
+        testSplitSixDeep(exp, s, UnaryOperator.identity());
     }
 
-    private static void assertSpliterator(Spliterator<?> s, int rootCharacteristics) {
-        if ((rootCharacteristics & Spliterator.SUBSIZED) != 0) {
-            assertTrue(s.hasCharacteristics(Spliterator.SUBSIZED),
-                       "Child split is not SUBSIZED when root split is SUBSIZED");
-        }
-        assertSpliterator(s);
-    }
-
-    private static void assertSpliterator(Spliterator<?> s) {
-        if (s.hasCharacteristics(Spliterator.SUBSIZED)) {
-            assertTrue(s.hasCharacteristics(Spliterator.SIZED));
-        }
-        if (s.hasCharacteristics(Spliterator.SIZED)) {
-            assertTrue(s.estimateSize() != Long.MAX_VALUE);
-            assertTrue(s.getExactSizeIfKnown() >= 0);
-        }
-        try {
-            s.getComparator();
-            assertTrue(s.hasCharacteristics(Spliterator.SORTED));
-        } catch (IllegalStateException e) {
-            assertFalse(s.hasCharacteristics(Spliterator.SORTED));
-        }
+    @Test(dataProvider = "HashableIntSpliterator")
+    void testSplitUntilNull(String description,
+                            Collection<HashableInteger> exp,
+                            Supplier<Spliterator<HashableInteger>> s) {
+        testSplitUntilNull(exp, s, UnaryOperator.identity());
     }
 
-    private static<T> void assertContents(Collection<T> actual, Collection<T> expected, boolean isOrdered) {
-        if (isOrdered) {
-            assertEquals(actual, expected);
-        }
-        else {
-            assertContentsUnordered(actual, expected);
-        }
-    }
-
-    private static<T> void assertContentsUnordered(Iterable<T> actual, Iterable<T> expected) {
-        assertEquals(toBoxedMultiset(actual), toBoxedMultiset(expected));
-    }
-
-    private static <T> Map<T, HashableInteger> toBoxedMultiset(Iterable<T> c) {
-        Map<T, HashableInteger> result = new HashMap<>();
-        c.forEach(e -> {
-            if (result.containsKey(e)) {
-                result.put(e, new HashableInteger(result.get(e).value + 1, 10));
-            } else {
-                result.put(e, new HashableInteger(1, 10));
-            }
-        });
-        return result;
-    }
-
-    private void executeAndCatch(Class<? extends Exception> expected, Runnable r) {
-        Exception caught = null;
-        try {
-            r.run();
-        }
-        catch (Exception e) {
-            caught = e;
-        }
-
-        assertNotNull(caught,
-                      String.format("No Exception was thrown, expected an Exception of %s to be thrown",
-                                    expected.getName()));
-        assertTrue(expected.isInstance(caught),
-                   String.format("Exception thrown %s not an instance of %s",
-                                 caught.getClass().getName(), expected.getName()));
+    @Test(dataProvider = "HashableIntSpliteratorWithNull")
+    void testSplitUntilNullWithNull(String description,
+                                    Collection<HashableInteger> exp,
+                                    Supplier<Spliterator<HashableInteger>> s) {
+        testSplitUntilNull(exp, s, UnaryOperator.identity());
     }
 
 }
--- a/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/Spliterator/SpliteratorTraversingAndSplittingTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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
@@ -24,6 +24,8 @@
 /**
  * @test
  * @summary Spliterator traversing and splitting tests
+ * @library ../stream/bootlib
+ * @build java.base/java.util.SpliteratorTestHelper
  * @run testng SpliteratorTraversingAndSplittingTest
  * @bug 8020016 8071477 8072784 8169838
  */
@@ -42,7 +44,6 @@
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Comparator;
-import java.util.Deque;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.IdentityHashMap;
@@ -58,6 +59,7 @@
 import java.util.Set;
 import java.util.SortedSet;
 import java.util.Spliterator;
+import java.util.SpliteratorTestHelper;
 import java.util.Spliterators;
 import java.util.Stack;
 import java.util.TreeMap;
@@ -85,11 +87,8 @@
 import java.util.stream.IntStream;
 
 import static java.util.stream.Collectors.toList;
-import static org.testng.Assert.*;
-import static org.testng.Assert.assertEquals;
 
-@Test
-public class SpliteratorTraversingAndSplittingTest {
+public class SpliteratorTraversingAndSplittingTest extends SpliteratorTestHelper {
 
     private static final List<Integer> SIZES = Arrays.asList(0, 1, 10, 42);
 
@@ -668,52 +667,49 @@
     }
 
     @Test(dataProvider = "Spliterator<Integer>")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testNullPointerException(String description, Collection exp, Supplier<Spliterator> s) {
+    public void testNullPointerException(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
         executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining(null));
         executeAndCatch(NullPointerException.class, () -> s.get().tryAdvance(null));
     }
 
     @Test(dataProvider = "Spliterator<Integer>")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testForEach(String description, Collection exp, Supplier<Spliterator> s) {
-        testForEach(exp, s, (Consumer<Object> b) -> b);
+    public void testForEach(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
+        testForEach(exp, s, UnaryOperator.identity());
     }
 
     @Test(dataProvider = "Spliterator<Integer>")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testTryAdvance(String description, Collection exp, Supplier<Spliterator> s) {
-        testTryAdvance(exp, s, (Consumer<Object> b) -> b);
+    public void testTryAdvance(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
+        testTryAdvance(exp, s, UnaryOperator.identity());
     }
 
     @Test(dataProvider = "Spliterator<Integer>")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testMixedTryAdvanceForEach(String description, Collection exp, Supplier<Spliterator> s) {
-        testMixedTryAdvanceForEach(exp, s, (Consumer<Object> b) -> b);
+    public void testMixedTryAdvanceForEach(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
+        testMixedTryAdvanceForEach(exp, s, UnaryOperator.identity());
     }
 
     @Test(dataProvider = "Spliterator<Integer>")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testSplitAfterFullTraversal(String description, Collection exp, Supplier<Spliterator> s) {
-        testSplitAfterFullTraversal(s, (Consumer<Object> b) -> b);
+    public void testMixedTraverseAndSplit(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
+        testMixedTraverseAndSplit(exp, s, UnaryOperator.identity());
+    }
+
+    @Test(dataProvider = "Spliterator<Integer>")
+    public void testSplitAfterFullTraversal(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
+        testSplitAfterFullTraversal(s, UnaryOperator.identity());
     }
 
     @Test(dataProvider = "Spliterator<Integer>")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testSplitOnce(String description, Collection exp, Supplier<Spliterator> s) {
-        testSplitOnce(exp, s, (Consumer<Object> b) -> b);
+    public void testSplitOnce(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
+        testSplitOnce(exp, s, UnaryOperator.identity());
     }
 
     @Test(dataProvider = "Spliterator<Integer>")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testSplitSixDeep(String description, Collection exp, Supplier<Spliterator> s) {
-        testSplitSixDeep(exp, s, (Consumer<Object> b) -> b);
+    public void testSplitSixDeep(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
+        testSplitSixDeep(exp, s, UnaryOperator.identity());
     }
 
     @Test(dataProvider = "Spliterator<Integer>")
-    @SuppressWarnings({"unchecked", "rawtypes"})
-    public void testSplitUntilNull(String description, Collection exp, Supplier<Spliterator> s) {
-        testSplitUntilNull(exp, s, (Consumer<Object> b) -> b);
+    public void testSplitUntilNull(String description, Collection<Integer> exp, Supplier<Spliterator<Integer>> s) {
+        testSplitUntilNull(exp, s, UnaryOperator.identity());
     }
 
     //
@@ -922,28 +918,6 @@
         return exp;
     }
 
-    private static UnaryOperator<Consumer<Integer>> intBoxingConsumer() {
-        class BoxingAdapter implements Consumer<Integer>, IntConsumer {
-            private final Consumer<Integer> b;
-
-            BoxingAdapter(Consumer<Integer> b) {
-                this.b = b;
-            }
-
-            @Override
-            public void accept(Integer value) {
-                throw new IllegalStateException();
-            }
-
-            @Override
-            public void accept(int value) {
-                b.accept(value);
-            }
-        }
-
-        return b -> new BoxingAdapter(b);
-    }
-
     @Test(dataProvider = "Spliterator.OfInt")
     public void testIntNullPointerException(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
         executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((IntConsumer) null));
@@ -966,6 +940,11 @@
     }
 
     @Test(dataProvider = "Spliterator.OfInt")
+    public void testIntMixedTraverseAndSplit(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
+        testMixedTraverseAndSplit(exp, s, intBoxingConsumer());
+    }
+
+    @Test(dataProvider = "Spliterator.OfInt")
     public void testIntSplitAfterFullTraversal(String description, Collection<Integer> exp, Supplier<Spliterator.OfInt> s) {
         testSplitAfterFullTraversal(s, intBoxingConsumer());
     }
@@ -1082,28 +1061,6 @@
         return exp;
     }
 
-    private static UnaryOperator<Consumer<Long>> longBoxingConsumer() {
-        class BoxingAdapter implements Consumer<Long>, LongConsumer {
-            private final Consumer<Long> b;
-
-            BoxingAdapter(Consumer<Long> b) {
-                this.b = b;
-            }
-
-            @Override
-            public void accept(Long value) {
-                throw new IllegalStateException();
-            }
-
-            @Override
-            public void accept(long value) {
-                b.accept(value);
-            }
-        }
-
-        return b -> new BoxingAdapter(b);
-    }
-
     @Test(dataProvider = "Spliterator.OfLong")
     public void testLongNullPointerException(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
         executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((LongConsumer) null));
@@ -1126,6 +1083,11 @@
     }
 
     @Test(dataProvider = "Spliterator.OfLong")
+    public void testLongMixedTraverseAndSplit(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
+        testMixedTraverseAndSplit(exp, s, longBoxingConsumer());
+    }
+
+    @Test(dataProvider = "Spliterator.OfLong")
     public void testLongSplitAfterFullTraversal(String description, Collection<Long> exp, Supplier<Spliterator.OfLong> s) {
         testSplitAfterFullTraversal(s, longBoxingConsumer());
     }
@@ -1242,28 +1204,6 @@
         return exp;
     }
 
-    private static UnaryOperator<Consumer<Double>> doubleBoxingConsumer() {
-        class BoxingAdapter implements Consumer<Double>, DoubleConsumer {
-            private final Consumer<Double> b;
-
-            BoxingAdapter(Consumer<Double> b) {
-                this.b = b;
-            }
-
-            @Override
-            public void accept(Double value) {
-                throw new IllegalStateException();
-            }
-
-            @Override
-            public void accept(double value) {
-                b.accept(value);
-            }
-        }
-
-        return b -> new BoxingAdapter(b);
-    }
-
     @Test(dataProvider = "Spliterator.OfDouble")
     public void testDoubleNullPointerException(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
         executeAndCatch(NullPointerException.class, () -> s.get().forEachRemaining((DoubleConsumer) null));
@@ -1286,6 +1226,11 @@
     }
 
     @Test(dataProvider = "Spliterator.OfDouble")
+    public void testDoubleMixedTraverseAndSplit(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
+        testMixedTraverseAndSplit(exp, s, doubleBoxingConsumer());
+    }
+
+    @Test(dataProvider = "Spliterator.OfDouble")
     public void testDoubleSplitAfterFullTraversal(String description, Collection<Double> exp, Supplier<Spliterator.OfDouble> s) {
         testSplitAfterFullTraversal(s, doubleBoxingConsumer());
     }
@@ -1305,392 +1250,4 @@
         testSplitUntilNull(exp, s, doubleBoxingConsumer());
     }
 
-    //
-
-    private static <T, S extends Spliterator<T>> void testForEach(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        ArrayList<T> fromForEach = new ArrayList<>();
-        spliterator = supplier.get();
-        Consumer<T> addToFromForEach = boxingAdapter.apply(fromForEach::add);
-        spliterator.forEachRemaining(addToFromForEach);
-
-        // Assert that forEach now produces no elements
-        spliterator.forEachRemaining(boxingAdapter.apply(e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
-        // Assert that tryAdvance now produce no elements
-        spliterator.tryAdvance(boxingAdapter.apply(e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
-
-        // assert that size, tryAdvance, and forEach are consistent
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, exp.size());
-        }
-        assertEquals(fromForEach.size(), exp.size());
-
-        assertContents(fromForEach, exp, isOrdered);
-    }
-
-    private static <T, S extends Spliterator<T>> void testTryAdvance(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        spliterator = supplier.get();
-        ArrayList<T> fromTryAdvance = new ArrayList<>();
-        Consumer<T> addToFromTryAdvance = boxingAdapter.apply(fromTryAdvance::add);
-        while (spliterator.tryAdvance(addToFromTryAdvance)) { }
-
-        // Assert that forEach now produces no elements
-        spliterator.forEachRemaining(boxingAdapter.apply(e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
-        // Assert that tryAdvance now produce no elements
-        spliterator.tryAdvance(boxingAdapter.apply(e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
-
-        // assert that size, tryAdvance, and forEach are consistent
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, exp.size());
-        }
-        assertEquals(fromTryAdvance.size(), exp.size());
-
-        assertContents(fromTryAdvance, exp, isOrdered);
-    }
-
-    private static <T, S extends Spliterator<T>> void testMixedTryAdvanceForEach(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        // tryAdvance first few elements, then forEach rest
-        ArrayList<T> dest = new ArrayList<>();
-        spliterator = supplier.get();
-        Consumer<T> addToDest = boxingAdapter.apply(dest::add);
-        for (int i = 0; i < 10 && spliterator.tryAdvance(addToDest); i++) { }
-        spliterator.forEachRemaining(addToDest);
-
-        // Assert that forEach now produces no elements
-        spliterator.forEachRemaining(boxingAdapter.apply(e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
-        // Assert that tryAdvance now produce no elements
-        spliterator.tryAdvance(boxingAdapter.apply(e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
-
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, dest.size());
-        }
-        assertEquals(dest.size(), exp.size());
-
-        if (isOrdered) {
-            assertEquals(dest, exp);
-        }
-        else {
-            assertContentsUnordered(dest, exp);
-        }
-    }
-
-    private static <T, S extends Spliterator<T>> void testSplitAfterFullTraversal(
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        // Full traversal using tryAdvance
-        Spliterator<T> spliterator = supplier.get();
-        while (spliterator.tryAdvance(boxingAdapter.apply(e -> { }))) { }
-        Spliterator<T> split = spliterator.trySplit();
-        assertNull(split);
-
-        // Full traversal using forEach
-        spliterator = supplier.get();
-        spliterator.forEachRemaining(boxingAdapter.apply(e -> {
-        }));
-        split = spliterator.trySplit();
-        assertNull(split);
-
-        // Full traversal using tryAdvance then forEach
-        spliterator = supplier.get();
-        spliterator.tryAdvance(boxingAdapter.apply(e -> { }));
-        spliterator.forEachRemaining(boxingAdapter.apply(e -> {
-        }));
-        split = spliterator.trySplit();
-        assertNull(split);
-    }
-
-    private static <T, S extends Spliterator<T>> void testSplitOnce(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        ArrayList<T> fromSplit = new ArrayList<>();
-        Spliterator<T> s1 = supplier.get();
-        Spliterator<T> s2 = s1.trySplit();
-        long s1Size = s1.getExactSizeIfKnown();
-        long s2Size = (s2 != null) ? s2.getExactSizeIfKnown() : 0;
-        Consumer<T> addToFromSplit = boxingAdapter.apply(fromSplit::add);
-        if (s2 != null)
-            s2.forEachRemaining(addToFromSplit);
-        s1.forEachRemaining(addToFromSplit);
-
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, fromSplit.size());
-            if (s1Size >= 0 && s2Size >= 0)
-                assertEquals(sizeIfKnown, s1Size + s2Size);
-        }
-        assertContents(fromSplit, exp, isOrdered);
-    }
-
-    private static <T, S extends Spliterator<T>> void testSplitSixDeep(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        S spliterator = supplier.get();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        for (int depth=0; depth < 6; depth++) {
-            List<T> dest = new ArrayList<>();
-            spliterator = supplier.get();
-
-            assertRootSpliterator(spliterator);
-
-            // verify splitting with forEach
-            visit(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), false);
-            assertContents(dest, exp, isOrdered);
-
-            // verify splitting with tryAdvance
-            dest.clear();
-            spliterator = supplier.get();
-            visit(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), true);
-            assertContents(dest, exp, isOrdered);
-        }
-    }
-
-    private static <T, S extends Spliterator<T>> void visit(int depth, int curLevel,
-                                                            List<T> dest, S spliterator, UnaryOperator<Consumer<T>> boxingAdapter,
-                                                            int rootCharacteristics, boolean useTryAdvance) {
-        if (curLevel < depth) {
-            long beforeSize = spliterator.getExactSizeIfKnown();
-            Spliterator<T> split = spliterator.trySplit();
-            if (split != null) {
-                assertSpliterator(split, rootCharacteristics);
-                assertSpliterator(spliterator, rootCharacteristics);
-
-                if ((rootCharacteristics & Spliterator.SUBSIZED) != 0 &&
-                    (rootCharacteristics & Spliterator.SIZED) != 0) {
-                    assertEquals(beforeSize, split.estimateSize() + spliterator.estimateSize());
-                }
-                visit(depth, curLevel + 1, dest, split, boxingAdapter, rootCharacteristics, useTryAdvance);
-            }
-            visit(depth, curLevel + 1, dest, spliterator, boxingAdapter, rootCharacteristics, useTryAdvance);
-        }
-        else {
-            long sizeIfKnown = spliterator.getExactSizeIfKnown();
-            if (useTryAdvance) {
-                Consumer<T> addToDest = boxingAdapter.apply(dest::add);
-                int count = 0;
-                while (spliterator.tryAdvance(addToDest)) {
-                    ++count;
-                }
-
-                if (sizeIfKnown >= 0)
-                    assertEquals(sizeIfKnown, count);
-
-                // Assert that forEach now produces no elements
-                spliterator.forEachRemaining(boxingAdapter.apply(e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
-
-                Spliterator<T> split = spliterator.trySplit();
-                assertNull(split);
-            }
-            else {
-                List<T> leafDest = new ArrayList<>();
-                Consumer<T> addToLeafDest = boxingAdapter.apply(leafDest::add);
-                spliterator.forEachRemaining(addToLeafDest);
-
-                if (sizeIfKnown >= 0)
-                    assertEquals(sizeIfKnown, leafDest.size());
-
-                // Assert that forEach now produces no elements
-                spliterator.tryAdvance(boxingAdapter.apply(e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
-
-                Spliterator<T> split = spliterator.trySplit();
-                assertNull(split);
-
-                dest.addAll(leafDest);
-            }
-        }
-    }
-
-    private static <T, S extends Spliterator<T>> void testSplitUntilNull(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        Spliterator<T> s = supplier.get();
-        boolean isOrdered = s.hasCharacteristics(Spliterator.ORDERED);
-        assertRootSpliterator(s);
-
-        List<T> splits = new ArrayList<>();
-        Consumer<T> c = boxingAdapter.apply(splits::add);
-
-        testSplitUntilNull(new SplitNode<T>(c, s));
-        assertContents(splits, exp, isOrdered);
-    }
-
-    private static class SplitNode<T> {
-        // Constant for every node
-        final Consumer<T> c;
-        final int rootCharacteristics;
-
-        final Spliterator<T> s;
-
-        SplitNode(Consumer<T> c, Spliterator<T> s) {
-            this(c, s.characteristics(), s);
-        }
-
-        private SplitNode(Consumer<T> c, int rootCharacteristics, Spliterator<T> s) {
-            this.c = c;
-            this.rootCharacteristics = rootCharacteristics;
-            this.s = s;
-        }
-
-        SplitNode<T> fromSplit(Spliterator<T> split) {
-            return new SplitNode<>(c, rootCharacteristics, split);
-        }
-    }
-
-    /**
-     * Set the maximum stack capacity to 0.25MB. This should be more than enough to detect a bad spliterator
-     * while not unduly disrupting test infrastructure given the test data sizes that are used are small.
-     * Note that j.u.c.ForkJoinPool sets the max queue size to 64M (1 << 26).
-     */
-    private static final int MAXIMUM_STACK_CAPACITY = 1 << 18; // 0.25MB
-
-    private static <T> void testSplitUntilNull(SplitNode<T> e) {
-        // Use an explicit stack to avoid a StackOverflowException when testing a Spliterator
-        // that when repeatedly split produces a right-balanced (and maybe degenerate) tree, or
-        // for a spliterator that is badly behaved.
-        Deque<SplitNode<T>> stack = new ArrayDeque<>();
-        stack.push(e);
-
-        int iteration = 0;
-        while (!stack.isEmpty()) {
-            assertTrue(iteration++ < MAXIMUM_STACK_CAPACITY, "Exceeded maximum stack modification count of 1 << 18");
-
-            e = stack.pop();
-            Spliterator<T> parentAndRightSplit = e.s;
-
-            long parentEstimateSize = parentAndRightSplit.estimateSize();
-            assertTrue(parentEstimateSize >= 0,
-                       String.format("Split size estimate %d < 0", parentEstimateSize));
-
-            long parentSize = parentAndRightSplit.getExactSizeIfKnown();
-            Spliterator<T> leftSplit = parentAndRightSplit.trySplit();
-            if (leftSplit == null) {
-                parentAndRightSplit.forEachRemaining(e.c);
-                continue;
-            }
-
-            assertSpliterator(leftSplit, e.rootCharacteristics);
-            assertSpliterator(parentAndRightSplit, e.rootCharacteristics);
-
-            if (parentEstimateSize != Long.MAX_VALUE && leftSplit.estimateSize() > 0 && parentAndRightSplit.estimateSize() > 0) {
-                assertTrue(leftSplit.estimateSize() < parentEstimateSize,
-                           String.format("Left split size estimate %d >= parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize));
-                assertTrue(parentAndRightSplit.estimateSize() < parentEstimateSize,
-                           String.format("Right split size estimate %d >= parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize));
-            }
-            else {
-                assertTrue(leftSplit.estimateSize() <= parentEstimateSize,
-                           String.format("Left split size estimate %d > parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize));
-                assertTrue(parentAndRightSplit.estimateSize() <= parentEstimateSize,
-                           String.format("Right split size estimate %d > parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize));
-            }
-
-            long leftSize = leftSplit.getExactSizeIfKnown();
-            long rightSize = parentAndRightSplit.getExactSizeIfKnown();
-            if (parentSize >= 0 && leftSize >= 0 && rightSize >= 0)
-                assertEquals(parentSize, leftSize + rightSize,
-                             String.format("exact left split size %d + exact right split size %d != parent exact split size %d",
-                                           leftSize, rightSize, parentSize));
-
-            // Add right side to stack first so left side is popped off first
-            stack.push(e.fromSplit(parentAndRightSplit));
-            stack.push(e.fromSplit(leftSplit));
-        }
-    }
-
-    private static void assertRootSpliterator(Spliterator<?> s) {
-        assertFalse(s.hasCharacteristics(Spliterator.SIZED | Spliterator.CONCURRENT),
-                    "Root spliterator should not be SIZED and CONCURRENT");
-
-        assertSpliterator(s);
-    }
-
-    private static void assertSpliterator(Spliterator<?> s, int rootCharacteristics) {
-        if ((rootCharacteristics & Spliterator.SUBSIZED) != 0) {
-            assertTrue(s.hasCharacteristics(Spliterator.SUBSIZED),
-                       "Child split is not SUBSIZED when root split is SUBSIZED");
-        }
-        assertSpliterator(s);
-    }
-
-    private static void assertSpliterator(Spliterator<?> s) {
-        if (s.hasCharacteristics(Spliterator.SUBSIZED)) {
-            assertTrue(s.hasCharacteristics(Spliterator.SIZED));
-        }
-        if (s.hasCharacteristics(Spliterator.SIZED)) {
-            assertTrue(s.estimateSize() != Long.MAX_VALUE);
-            assertTrue(s.getExactSizeIfKnown() >= 0);
-        }
-        try {
-            s.getComparator();
-            assertTrue(s.hasCharacteristics(Spliterator.SORTED));
-        } catch (IllegalStateException e) {
-            assertFalse(s.hasCharacteristics(Spliterator.SORTED));
-        }
-    }
-
-    private static<T> void assertContents(Collection<T> actual, Collection<T> expected, boolean isOrdered) {
-        if (isOrdered) {
-            assertEquals(actual, expected);
-        }
-        else {
-            assertContentsUnordered(actual, expected);
-        }
-    }
-
-    private static<T> void assertContentsUnordered(Iterable<T> actual, Iterable<T> expected) {
-        assertEquals(toBoxedMultiset(actual), toBoxedMultiset(expected));
-    }
-
-    private static <T> Map<T, Integer> toBoxedMultiset(Iterable<T> c) {
-        Map<T, Integer> result = new HashMap<>();
-        c.forEach(e -> {
-            if (result.containsKey(e)) result.put(e, result.get(e) + 1);
-            else result.put(e, 1);
-        });
-        return result;
-    }
-
-    private void executeAndCatch(Class<? extends Exception> expected, Runnable r) {
-        Exception caught = null;
-        try {
-            r.run();
-        }
-        catch (Exception e) {
-            caught = e;
-        }
-
-        assertNotNull(caught,
-                      String.format("No Exception was thrown, expected an Exception of %s to be thrown",
-                                    expected.getName()));
-        assertTrue(expected.isInstance(caught),
-                   String.format("Exception thrown %s not an instance of %s",
-                                 caught.getClass().getName(), expected.getName()));
-    }
-
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/java/util/stream/bootlib/java.base/java/util/SpliteratorTestHelper.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,769 @@
+/*
+ * Copyright (c) 2012, 2017, 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 java.util;
+
+import java.util.function.*;
+import java.util.stream.LambdaTestHelpers;
+
+import static org.testng.Assert.*;
+import static org.testng.Assert.assertEquals;
+import static org.testng.Assert.fail;
+
+/**
+ * Assertion methods for spliterators, to be called from other tests
+ */
+public class SpliteratorTestHelper {
+
+    public interface ContentAsserter<T> {
+        void assertContents(Collection<T> actual, Collection<T> expected, boolean isOrdered);
+    }
+
+    private static ContentAsserter<Object> DEFAULT_CONTENT_ASSERTER
+            = SpliteratorTestHelper::assertContents;
+
+    @SuppressWarnings("unchecked")
+    private static <T> ContentAsserter<T> defaultContentAsserter() {
+        return (ContentAsserter<T>) DEFAULT_CONTENT_ASSERTER;
+    }
+
+    public static void testSpliterator(Supplier<Spliterator<Integer>> supplier) {
+        testSpliterator(supplier, defaultContentAsserter());
+    }
+
+    public static void testSpliterator(Supplier<Spliterator<Integer>> supplier,
+                                       ContentAsserter<Integer> asserter) {
+        testSpliterator(supplier, (Consumer<Integer> b) -> b, asserter);
+    }
+
+    public static void testIntSpliterator(Supplier<Spliterator.OfInt> supplier) {
+        testIntSpliterator(supplier, defaultContentAsserter());
+    }
+
+    public static void testIntSpliterator(Supplier<Spliterator.OfInt> supplier,
+                                          ContentAsserter<Integer> asserter) {
+        testSpliterator(supplier, intBoxingConsumer(), asserter);
+    }
+
+    public static void testLongSpliterator(Supplier<Spliterator.OfLong> supplier) {
+        testLongSpliterator(supplier, defaultContentAsserter());
+    }
+
+    public static void testLongSpliterator(Supplier<Spliterator.OfLong> supplier,
+                                           ContentAsserter<Long> asserter) {
+        testSpliterator(supplier, longBoxingConsumer(), asserter);
+    }
+
+    public static void testDoubleSpliterator(Supplier<Spliterator.OfDouble> supplier) {
+        testDoubleSpliterator(supplier, defaultContentAsserter());
+    }
+
+    public static void testDoubleSpliterator(Supplier<Spliterator.OfDouble> supplier,
+                                             ContentAsserter<Double> asserter) {
+        testSpliterator(supplier, doubleBoxingConsumer(), asserter);
+    }
+
+    public static UnaryOperator<Consumer<Integer>> intBoxingConsumer() {
+        class BoxingAdapter implements Consumer<Integer>, IntConsumer {
+            private final Consumer<Integer> b;
+
+            BoxingAdapter(Consumer<Integer> b) {
+                this.b = b;
+            }
+
+            @Override
+            public void accept(Integer value) {
+                throw new IllegalStateException();
+            }
+
+            @Override
+            public void accept(int value) {
+                b.accept(value);
+            }
+        }
+
+        return b -> new BoxingAdapter(b);
+    }
+
+    public static UnaryOperator<Consumer<Long>> longBoxingConsumer() {
+        class BoxingAdapter implements Consumer<Long>, LongConsumer {
+            private final Consumer<Long> b;
+
+            BoxingAdapter(Consumer<Long> b) {
+                this.b = b;
+            }
+
+            @Override
+            public void accept(Long value) {
+                throw new IllegalStateException();
+            }
+
+            @Override
+            public void accept(long value) {
+                b.accept(value);
+            }
+        }
+
+        return b -> new BoxingAdapter(b);
+    }
+
+    public static UnaryOperator<Consumer<Double>> doubleBoxingConsumer() {
+        class BoxingAdapter implements Consumer<Double>, DoubleConsumer {
+            private final Consumer<Double> b;
+
+            BoxingAdapter(Consumer<Double> b) {
+                this.b = b;
+            }
+
+            @Override
+            public void accept(Double value) {
+                throw new IllegalStateException();
+            }
+
+            @Override
+            public void accept(double value) {
+                b.accept(value);
+            }
+        }
+
+        return b -> new BoxingAdapter(b);
+    }
+
+    public static <T, S extends Spliterator<T>> void testSpliterator(Supplier<S> supplier,
+                                                              UnaryOperator<Consumer<T>> boxingAdapter,
+                                                              ContentAsserter<T> asserter) {
+        ArrayList<T> fromForEach = new ArrayList<>();
+        Spliterator<T> spliterator = supplier.get();
+        Consumer<T> addToFromForEach = boxingAdapter.apply(fromForEach::add);
+        spliterator.forEachRemaining(addToFromForEach);
+
+        Collection<T> exp = Collections.unmodifiableList(fromForEach);
+
+        testNullPointerException(supplier);
+        testForEach(exp, supplier, boxingAdapter, asserter);
+        testTryAdvance(exp, supplier, boxingAdapter, asserter);
+        testMixedTryAdvanceForEach(exp, supplier, boxingAdapter, asserter);
+        testMixedTraverseAndSplit(exp, supplier, boxingAdapter, asserter);
+        testSplitAfterFullTraversal(supplier, boxingAdapter);
+        testSplitOnce(exp, supplier, boxingAdapter, asserter);
+        testSplitSixDeep(exp, supplier, boxingAdapter, asserter);
+        testSplitUntilNull(exp, supplier, boxingAdapter, asserter);
+    }
+
+    public static <T, S extends Spliterator<T>> void testForEach(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter) {
+        testForEach(exp, supplier, boxingAdapter, defaultContentAsserter());
+    }
+
+    public static <T, S extends Spliterator<T>> void testTryAdvance(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter) {
+        testTryAdvance(exp, supplier, boxingAdapter, defaultContentAsserter());
+    }
+
+    public static <T, S extends Spliterator<T>> void testMixedTryAdvanceForEach(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter) {
+        testMixedTryAdvanceForEach(exp, supplier, boxingAdapter, defaultContentAsserter());
+    }
+
+    public static <T, S extends Spliterator<T>> void testMixedTraverseAndSplit(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter) {
+        testMixedTraverseAndSplit(exp, supplier, boxingAdapter, defaultContentAsserter());
+    }
+
+    public static <T, S extends Spliterator<T>> void testSplitOnce(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter) {
+        testSplitOnce(exp, supplier, boxingAdapter, defaultContentAsserter());
+    }
+
+    public static <T, S extends Spliterator<T>> void testSplitSixDeep(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter) {
+        testSplitSixDeep(exp, supplier, boxingAdapter, defaultContentAsserter());
+    }
+
+    public static <T, S extends Spliterator<T>> void testSplitUntilNull(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter) {
+        testSplitUntilNull(exp, supplier, boxingAdapter, defaultContentAsserter());
+    }
+
+    private static <T, S extends Spliterator<T>> void testNullPointerException(Supplier<S> s) {
+        S sp = s.get();
+        // Have to check instances and use casts to avoid tripwire messages and
+        // directly test the primitive methods
+        if (sp instanceof Spliterator.OfInt) {
+            Spliterator.OfInt psp = (Spliterator.OfInt) sp;
+            executeAndCatch(NullPointerException.class, () -> psp.forEachRemaining((IntConsumer) null));
+            executeAndCatch(NullPointerException.class, () -> psp.tryAdvance((IntConsumer) null));
+        }
+        else if (sp instanceof Spliterator.OfLong) {
+            Spliterator.OfLong psp = (Spliterator.OfLong) sp;
+            executeAndCatch(NullPointerException.class, () -> psp.forEachRemaining((LongConsumer) null));
+            executeAndCatch(NullPointerException.class, () -> psp.tryAdvance((LongConsumer) null));
+        }
+        else if (sp instanceof Spliterator.OfDouble) {
+            Spliterator.OfDouble psp = (Spliterator.OfDouble) sp;
+            executeAndCatch(NullPointerException.class, () -> psp.forEachRemaining((DoubleConsumer) null));
+            executeAndCatch(NullPointerException.class, () -> psp.tryAdvance((DoubleConsumer) null));
+        }
+        else {
+            executeAndCatch(NullPointerException.class, () -> sp.forEachRemaining(null));
+            executeAndCatch(NullPointerException.class, () -> sp.tryAdvance(null));
+        }
+    }
+
+    private static <T, S extends Spliterator<T>> void testForEach(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter,
+            ContentAsserter<T> asserter) {
+        S spliterator = supplier.get();
+        long sizeIfKnown = spliterator.getExactSizeIfKnown();
+        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
+
+        ArrayList<T> fromForEach = new ArrayList<>();
+        spliterator = supplier.get();
+        Consumer<T> addToFromForEach = boxingAdapter.apply(fromForEach::add);
+        spliterator.forEachRemaining(addToFromForEach);
+
+        // Assert that forEach now produces no elements
+        spliterator.forEachRemaining(boxingAdapter.apply(
+                e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
+        // Assert that tryAdvance now produce no elements
+        spliterator.tryAdvance(boxingAdapter.apply(
+                e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
+
+        // assert that size, tryAdvance, and forEach are consistent
+        if (sizeIfKnown >= 0) {
+            assertEquals(sizeIfKnown, exp.size());
+        }
+        if (exp.contains(null)) {
+            assertTrue(fromForEach.contains(null));
+        }
+        assertEquals(fromForEach.size(), exp.size());
+
+        asserter.assertContents(fromForEach, exp, isOrdered);
+    }
+
+    private static <T, S extends Spliterator<T>> void testTryAdvance(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter,
+            ContentAsserter<T> asserter) {
+        S spliterator = supplier.get();
+        long sizeIfKnown = spliterator.getExactSizeIfKnown();
+        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
+
+        spliterator = supplier.get();
+        ArrayList<T> fromTryAdvance = new ArrayList<>();
+        Consumer<T> addToFromTryAdvance = boxingAdapter.apply(fromTryAdvance::add);
+        while (spliterator.tryAdvance(addToFromTryAdvance)) { }
+
+        // Assert that forEach now produces no elements
+        spliterator.forEachRemaining(boxingAdapter.apply(
+                e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
+        // Assert that tryAdvance now produce no elements
+        spliterator.tryAdvance(boxingAdapter.apply(
+                e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
+
+        // assert that size, tryAdvance, and forEach are consistent
+        if (sizeIfKnown >= 0) {
+            assertEquals(sizeIfKnown, exp.size());
+        }
+        assertEquals(fromTryAdvance.size(), exp.size());
+
+        asserter.assertContents(fromTryAdvance, exp, isOrdered);
+    }
+
+    private static <T, S extends Spliterator<T>> void testMixedTryAdvanceForEach(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter,
+            ContentAsserter<T> asserter) {
+        S spliterator = supplier.get();
+        long sizeIfKnown = spliterator.getExactSizeIfKnown();
+        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
+
+        // tryAdvance first few elements, then forEach rest
+        ArrayList<T> dest = new ArrayList<>();
+        spliterator = supplier.get();
+        Consumer<T> addToDest = boxingAdapter.apply(dest::add);
+        for (int i = 0; i < 10 && spliterator.tryAdvance(addToDest); i++) { }
+        spliterator.forEachRemaining(addToDest);
+
+        // Assert that forEach now produces no elements
+        spliterator.forEachRemaining(boxingAdapter.apply(
+                e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
+        // Assert that tryAdvance now produce no elements
+        spliterator.tryAdvance(boxingAdapter.apply(
+                e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
+
+        if (sizeIfKnown >= 0) {
+            assertEquals(sizeIfKnown, dest.size());
+        }
+        assertEquals(dest.size(), exp.size());
+
+        asserter.assertContents(dest, exp, isOrdered);
+    }
+
+    private static <T, S extends Spliterator<T>> void testMixedTraverseAndSplit(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter,
+            ContentAsserter<T> asserter) {
+        S spliterator = supplier.get();
+        long sizeIfKnown = spliterator.getExactSizeIfKnown();
+        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
+
+        // tryAdvance first few elements, then forEach rest
+        ArrayList<T> dest = new ArrayList<>();
+        spliterator = supplier.get();
+        Consumer<T> b = boxingAdapter.apply(dest::add);
+
+        Spliterator<T> spl1, spl2, spl3;
+        spliterator.tryAdvance(b);
+        spl2 = spliterator.trySplit();
+        if (spl2 != null) {
+            spl2.tryAdvance(b);
+            spl1 = spl2.trySplit();
+            if (spl1 != null) {
+                spl1.tryAdvance(b);
+                spl1.forEachRemaining(b);
+            }
+            spl2.tryAdvance(b);
+            spl2.forEachRemaining(b);
+        }
+        spliterator.tryAdvance(b);
+        spl3 = spliterator.trySplit();
+        if (spl3 != null) {
+            spl3.tryAdvance(b);
+            spl3.forEachRemaining(b);
+        }
+        spliterator.tryAdvance(b);
+        spliterator.forEachRemaining(b);
+
+        if (sizeIfKnown >= 0) {
+            assertEquals(sizeIfKnown, dest.size());
+        }
+        assertEquals(dest.size(), exp.size());
+
+        asserter.assertContents(dest, exp, isOrdered);
+    }
+
+    public static <T, S extends Spliterator<T>> void testSplitAfterFullTraversal(
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter) {
+        // Full traversal using tryAdvance
+        Spliterator<T> spliterator = supplier.get();
+        while (spliterator.tryAdvance(boxingAdapter.apply(e -> { }))) { }
+        Spliterator<T> split = spliterator.trySplit();
+        assertNull(split);
+
+        // Full traversal using forEach
+        spliterator = supplier.get();
+        spliterator.forEachRemaining(boxingAdapter.apply(e -> { }));
+        split = spliterator.trySplit();
+        assertNull(split);
+
+        // Full traversal using tryAdvance then forEach
+        spliterator = supplier.get();
+        spliterator.tryAdvance(boxingAdapter.apply(e -> { }));
+        spliterator.forEachRemaining(boxingAdapter.apply(e -> { }));
+        split = spliterator.trySplit();
+        assertNull(split);
+    }
+
+    private static <T, S extends Spliterator<T>> void testSplitOnce(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter,
+            ContentAsserter<T> asserter) {
+        S spliterator = supplier.get();
+        long sizeIfKnown = spliterator.getExactSizeIfKnown();
+        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
+
+        ArrayList<T> fromSplit = new ArrayList<>();
+        Spliterator<T> s1 = supplier.get();
+        Spliterator<T> s2 = s1.trySplit();
+        long s1Size = s1.getExactSizeIfKnown();
+        long s2Size = (s2 != null) ? s2.getExactSizeIfKnown() : 0;
+        Consumer<T> addToFromSplit = boxingAdapter.apply(fromSplit::add);
+        if (s2 != null)
+            s2.forEachRemaining(addToFromSplit);
+        s1.forEachRemaining(addToFromSplit);
+
+        if (sizeIfKnown >= 0) {
+            assertEquals(sizeIfKnown, fromSplit.size());
+            if (s1Size >= 0 && s2Size >= 0)
+                assertEquals(sizeIfKnown, s1Size + s2Size);
+        }
+
+        asserter.assertContents(fromSplit, exp, isOrdered);
+    }
+
+    private static <T, S extends Spliterator<T>> void testSplitSixDeep(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter,
+            ContentAsserter<T> asserter) {
+        S spliterator = supplier.get();
+        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
+
+        for (int depth=0; depth < 6; depth++) {
+            List<T> dest = new ArrayList<>();
+            spliterator = supplier.get();
+
+            assertSpliterator(spliterator);
+
+            // verify splitting with forEach
+            splitSixDeepVisitor(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), false);
+            asserter.assertContents(dest, exp, isOrdered);
+
+            // verify splitting with tryAdvance
+            dest.clear();
+            spliterator = supplier.get();
+            splitSixDeepVisitor(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), true);
+            asserter.assertContents(dest, exp, isOrdered);
+        }
+    }
+
+    private static <T, S extends Spliterator<T>>
+    void splitSixDeepVisitor(int depth, int curLevel,
+                             List<T> dest, S spliterator, UnaryOperator<Consumer<T>> boxingAdapter,
+                             int rootCharacteristics, boolean useTryAdvance) {
+        if (curLevel < depth) {
+            long beforeSize = spliterator.getExactSizeIfKnown();
+            Spliterator<T> split = spliterator.trySplit();
+            if (split != null) {
+                assertSpliterator(split, rootCharacteristics);
+                assertSpliterator(spliterator, rootCharacteristics);
+
+                if ((rootCharacteristics & Spliterator.SUBSIZED) != 0 &&
+                    (rootCharacteristics & Spliterator.SIZED) != 0) {
+                    assertEquals(beforeSize, split.estimateSize() + spliterator.estimateSize());
+                }
+                splitSixDeepVisitor(depth, curLevel + 1, dest, split, boxingAdapter, rootCharacteristics, useTryAdvance);
+            }
+            splitSixDeepVisitor(depth, curLevel + 1, dest, spliterator, boxingAdapter, rootCharacteristics, useTryAdvance);
+        }
+        else {
+            long sizeIfKnown = spliterator.getExactSizeIfKnown();
+            if (useTryAdvance) {
+                Consumer<T> addToDest = boxingAdapter.apply(dest::add);
+                int count = 0;
+                while (spliterator.tryAdvance(addToDest)) {
+                    ++count;
+                }
+
+                if (sizeIfKnown >= 0)
+                    assertEquals(sizeIfKnown, count);
+
+                // Assert that forEach now produces no elements
+                spliterator.forEachRemaining(boxingAdapter.apply(
+                        e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
+
+                Spliterator<T> split = spliterator.trySplit();
+                assertNull(split);
+            }
+            else {
+                List<T> leafDest = new ArrayList<>();
+                Consumer<T> addToLeafDest = boxingAdapter.apply(leafDest::add);
+                spliterator.forEachRemaining(addToLeafDest);
+
+                if (sizeIfKnown >= 0)
+                    assertEquals(sizeIfKnown, leafDest.size());
+
+                // Assert that forEach now produces no elements
+                spliterator.tryAdvance(boxingAdapter.apply(
+                        e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
+
+                Spliterator<T> split = spliterator.trySplit();
+                assertNull(split);
+
+                dest.addAll(leafDest);
+            }
+        }
+    }
+
+    private static <T, S extends Spliterator<T>> void testSplitUntilNull(
+            Collection<T> exp,
+            Supplier<S> supplier,
+            UnaryOperator<Consumer<T>> boxingAdapter,
+            ContentAsserter<T> asserter) {
+        Spliterator<T> s = supplier.get();
+        boolean isOrdered = s.hasCharacteristics(Spliterator.ORDERED);
+        assertSpliterator(s);
+
+        List<T> splits = new ArrayList<>();
+        Consumer<T> c = boxingAdapter.apply(splits::add);
+
+        testSplitUntilNull(new SplitNode<T>(c, s));
+        asserter.assertContents(splits, exp, isOrdered);
+    }
+
+    private static class SplitNode<T> {
+        // Constant for every node
+        final Consumer<T> c;
+        final int rootCharacteristics;
+
+        final Spliterator<T> s;
+
+        SplitNode(Consumer<T> c, Spliterator<T> s) {
+            this(c, s.characteristics(), s);
+        }
+
+        private SplitNode(Consumer<T> c, int rootCharacteristics, Spliterator<T> s) {
+            this.c = c;
+            this.rootCharacteristics = rootCharacteristics;
+            this.s = s;
+        }
+
+        SplitNode<T> fromSplit(Spliterator<T> split) {
+            return new SplitNode<>(c, rootCharacteristics, split);
+        }
+    }
+
+    /**
+     * Set the maximum stack capacity to 0.25MB. This should be more than enough to detect a bad spliterator
+     * while not unduly disrupting test infrastructure given the test data sizes that are used are small.
+     * Note that j.u.c.ForkJoinPool sets the max queue size to 64M (1 << 26).
+     */
+    private static final int MAXIMUM_STACK_CAPACITY = 1 << 18; // 0.25MB
+
+    private static <T> void testSplitUntilNull(SplitNode<T> e) {
+        // Use an explicit stack to avoid a StackOverflowException when testing a Spliterator
+        // that when repeatedly split produces a right-balanced (and maybe degenerate) tree, or
+        // for a spliterator that is badly behaved.
+        Deque<SplitNode<T>> stack = new ArrayDeque<>();
+        stack.push(e);
+
+        int iteration = 0;
+        while (!stack.isEmpty()) {
+            assertTrue(iteration++ < MAXIMUM_STACK_CAPACITY, "Exceeded maximum stack modification count of 1 << 18");
+
+            e = stack.pop();
+            Spliterator<T> parentAndRightSplit = e.s;
+
+            long parentEstimateSize = parentAndRightSplit.estimateSize();
+            assertTrue(parentEstimateSize >= 0,
+                       String.format("Split size estimate %d < 0", parentEstimateSize));
+
+            long parentSize = parentAndRightSplit.getExactSizeIfKnown();
+            Spliterator<T> leftSplit = parentAndRightSplit.trySplit();
+            if (leftSplit == null) {
+                parentAndRightSplit.forEachRemaining(e.c);
+                continue;
+            }
+
+            assertSpliterator(leftSplit, e.rootCharacteristics);
+            assertSpliterator(parentAndRightSplit, e.rootCharacteristics);
+
+            if (parentEstimateSize != Long.MAX_VALUE && leftSplit.estimateSize() > 0
+                && parentAndRightSplit.estimateSize() > 0) {
+                assertTrue(leftSplit.estimateSize() < parentEstimateSize,
+                           String.format("Left split size estimate %d >= parent split size estimate %d",
+                                         leftSplit.estimateSize(), parentEstimateSize));
+                assertTrue(parentAndRightSplit.estimateSize() < parentEstimateSize,
+                           String.format("Right split size estimate %d >= parent split size estimate %d",
+                                         leftSplit.estimateSize(), parentEstimateSize));
+            }
+            else {
+                assertTrue(leftSplit.estimateSize() <= parentEstimateSize,
+                           String.format("Left split size estimate %d > parent split size estimate %d",
+                                         leftSplit.estimateSize(), parentEstimateSize));
+                assertTrue(parentAndRightSplit.estimateSize() <= parentEstimateSize,
+                           String.format("Right split size estimate %d > parent split size estimate %d",
+                                         leftSplit.estimateSize(), parentEstimateSize));
+            }
+
+            long leftSize = leftSplit.getExactSizeIfKnown();
+            long rightSize = parentAndRightSplit.getExactSizeIfKnown();
+            if (parentSize >= 0 && leftSize >= 0 && rightSize >= 0)
+                assertEquals(parentSize, leftSize + rightSize,
+                             String.format("exact left split size %d + exact right split size %d != parent exact split size %d",
+                                           leftSize, rightSize, parentSize));
+
+            // Add right side to stack first so left side is popped off first
+            stack.push(e.fromSplit(parentAndRightSplit));
+            stack.push(e.fromSplit(leftSplit));
+        }
+    }
+
+    private static void assertSpliterator(Spliterator<?> s, int rootCharacteristics) {
+        if ((rootCharacteristics & Spliterator.SUBSIZED) != 0) {
+            assertTrue(s.hasCharacteristics(Spliterator.SUBSIZED),
+                       "Child split is not SUBSIZED when root split is SUBSIZED");
+        }
+        assertSpliterator(s);
+    }
+
+    private static void assertSpliterator(Spliterator<?> s) {
+        if (s.hasCharacteristics(Spliterator.SUBSIZED)) {
+            assertTrue(s.hasCharacteristics(Spliterator.SIZED));
+        }
+        if (s.hasCharacteristics(Spliterator.SIZED)) {
+            assertTrue(s.estimateSize() != Long.MAX_VALUE);
+            assertTrue(s.getExactSizeIfKnown() >= 0);
+        }
+        try {
+            s.getComparator();
+            assertTrue(s.hasCharacteristics(Spliterator.SORTED));
+        } catch (IllegalStateException e) {
+            assertFalse(s.hasCharacteristics(Spliterator.SORTED));
+        }
+    }
+
+    private static<T> void assertContents(Collection<T> actual, Collection<T> expected, boolean isOrdered) {
+        if (isOrdered) {
+            assertEquals(actual, expected);
+        }
+        else {
+            LambdaTestHelpers.assertContentsUnordered(actual, expected);
+        }
+    }
+
+    public static void executeAndCatch(Class<? extends Exception> expected, Runnable r) {
+        Exception caught = null;
+        try {
+            r.run();
+        }
+        catch (Exception e) {
+            caught = e;
+        }
+
+        assertNotNull(caught,
+                      String.format("No Exception was thrown, expected an Exception of %s to be thrown",
+                                    expected.getName()));
+        assertTrue(expected.isInstance(caught),
+                   String.format("Exception thrown %s not an instance of %s",
+                                 caught.getClass().getName(), expected.getName()));
+    }
+
+    public static<U> void mixedTraverseAndSplit(Consumer<U> b, Spliterator<U> splTop) {
+        Spliterator<U> spl1, spl2, spl3;
+        splTop.tryAdvance(b);
+        spl2 = splTop.trySplit();
+        if (spl2 != null) {
+            spl2.tryAdvance(b);
+            spl1 = spl2.trySplit();
+            if (spl1 != null) {
+                spl1.tryAdvance(b);
+                spl1.forEachRemaining(b);
+            }
+            spl2.tryAdvance(b);
+            spl2.forEachRemaining(b);
+        }
+        splTop.tryAdvance(b);
+        spl3 = splTop.trySplit();
+        if (spl3 != null) {
+            spl3.tryAdvance(b);
+            spl3.forEachRemaining(b);
+        }
+        splTop.tryAdvance(b);
+        splTop.forEachRemaining(b);
+    }
+
+    public static void mixedTraverseAndSplit(IntConsumer b, Spliterator.OfInt splTop) {
+        Spliterator.OfInt spl1, spl2, spl3;
+        splTop.tryAdvance(b);
+        spl2 = splTop.trySplit();
+        if (spl2 != null) {
+            spl2.tryAdvance(b);
+            spl1 = spl2.trySplit();
+            if (spl1 != null) {
+                spl1.tryAdvance(b);
+                spl1.forEachRemaining(b);
+            }
+            spl2.tryAdvance(b);
+            spl2.forEachRemaining(b);
+        }
+        splTop.tryAdvance(b);
+        spl3 = splTop.trySplit();
+        if (spl3 != null) {
+            spl3.tryAdvance(b);
+            spl3.forEachRemaining(b);
+        }
+        splTop.tryAdvance(b);
+        splTop.forEachRemaining(b);
+    }
+
+    public static void mixedTraverseAndSplit(LongConsumer b, Spliterator.OfLong splTop) {
+        Spliterator.OfLong spl1, spl2, spl3;
+        splTop.tryAdvance(b);
+        spl2 = splTop.trySplit();
+        if (spl2 != null) {
+            spl2.tryAdvance(b);
+            spl1 = spl2.trySplit();
+            if (spl1 != null) {
+                spl1.tryAdvance(b);
+                spl1.forEachRemaining(b);
+            }
+            spl2.tryAdvance(b);
+            spl2.forEachRemaining(b);
+        }
+        splTop.tryAdvance(b);
+        spl3 = splTop.trySplit();
+        if (spl3 != null) {
+            spl3.tryAdvance(b);
+            spl3.forEachRemaining(b);
+        }
+        splTop.tryAdvance(b);
+        splTop.forEachRemaining(b);
+    }
+
+    public static void mixedTraverseAndSplit(DoubleConsumer b, Spliterator.OfDouble splTop) {
+        Spliterator.OfDouble spl1, spl2, spl3;
+        splTop.tryAdvance(b);
+        spl2 = splTop.trySplit();
+        if (spl2 != null) {
+            spl2.tryAdvance(b);
+            spl1 = spl2.trySplit();
+            if (spl1 != null) {
+                spl1.tryAdvance(b);
+                spl1.forEachRemaining(b);
+            }
+            spl2.tryAdvance(b);
+            spl2.forEachRemaining(b);
+        }
+        splTop.tryAdvance(b);
+        spl3 = splTop.trySplit();
+        if (spl3 != null) {
+            spl3.tryAdvance(b);
+            spl3.forEachRemaining(b);
+        }
+        splTop.tryAdvance(b);
+        splTop.forEachRemaining(b);
+    }
+
+}
--- a/jdk/test/java/util/stream/bootlib/java.base/java/util/stream/DoubleStreamTestScenario.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/stream/bootlib/java.base/java/util/stream/DoubleStreamTestScenario.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 import java.util.PrimitiveIterator;
 import java.util.Set;
 import java.util.Spliterator;
+import java.util.SpliteratorTestHelper;
 import java.util.function.Consumer;
 import java.util.function.DoubleConsumer;
 import java.util.function.Function;
--- a/jdk/test/java/util/stream/bootlib/java.base/java/util/stream/IntStreamTestScenario.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/stream/bootlib/java.base/java/util/stream/IntStreamTestScenario.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 import java.util.PrimitiveIterator;
 import java.util.Set;
 import java.util.Spliterator;
+import java.util.SpliteratorTestHelper;
 import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.function.IntConsumer;
--- a/jdk/test/java/util/stream/bootlib/java.base/java/util/stream/LongStreamTestScenario.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/stream/bootlib/java.base/java/util/stream/LongStreamTestScenario.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 import java.util.PrimitiveIterator;
 import java.util.Set;
 import java.util.Spliterator;
+import java.util.SpliteratorTestHelper;
 import java.util.function.Consumer;
 import java.util.function.Function;
 import java.util.function.LongConsumer;
--- a/jdk/test/java/util/stream/bootlib/java.base/java/util/stream/SpliteratorTestHelper.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,715 +0,0 @@
-/*
- * Copyright (c) 2012, 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.
- */
-package java.util.stream;
-
-import org.testng.annotations.Test;
-
-import java.util.ArrayDeque;
-import java.util.ArrayList;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.Deque;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.Spliterator;
-import java.util.function.*;
-
-import static org.testng.Assert.*;
-import static org.testng.Assert.assertEquals;
-import static org.testng.Assert.fail;
-
-/**
- * Assertion methods for spliterators, to be called from other tests
- */
-public class SpliteratorTestHelper {
-
-    public interface ContentAsserter<T> {
-        void assertContents(Collection<T> actual, Collection<T> expected, boolean isOrdered);
-    }
-
-    private static ContentAsserter<Object> DEFAULT_CONTENT_ASSERTER
-            = SpliteratorTestHelper::assertContents;
-
-    @SuppressWarnings("unchecked")
-    private static <T> ContentAsserter<T> defaultContentAsserter() {
-        return (ContentAsserter<T>) DEFAULT_CONTENT_ASSERTER;
-    }
-
-    public static void testSpliterator(Supplier<Spliterator<Integer>> supplier) {
-        testSpliterator(supplier, defaultContentAsserter());
-    }
-
-    public static void testSpliterator(Supplier<Spliterator<Integer>> supplier,
-                                       ContentAsserter<Integer> asserter) {
-        testSpliterator(supplier, (Consumer<Integer> b) -> b, asserter);
-    }
-
-    public static void testIntSpliterator(Supplier<Spliterator.OfInt> supplier) {
-        testIntSpliterator(supplier, defaultContentAsserter());
-    }
-
-    public static void testIntSpliterator(Supplier<Spliterator.OfInt> supplier,
-                                          ContentAsserter<Integer> asserter) {
-        class BoxingAdapter implements Consumer<Integer>, IntConsumer {
-            private final Consumer<Integer> b;
-
-            BoxingAdapter(Consumer<Integer> b) {
-                this.b = b;
-            }
-
-            @Override
-            public void accept(Integer value) {
-                throw new IllegalStateException();
-            }
-
-            @Override
-            public void accept(int value) {
-                b.accept(value);
-            }
-        }
-
-        testSpliterator(supplier, BoxingAdapter::new, asserter);
-    }
-
-    public static void testLongSpliterator(Supplier<Spliterator.OfLong> supplier) {
-        testLongSpliterator(supplier, defaultContentAsserter());
-    }
-
-    public static void testLongSpliterator(Supplier<Spliterator.OfLong> supplier,
-                                           ContentAsserter<Long> asserter) {
-        class BoxingAdapter implements Consumer<Long>, LongConsumer {
-            private final Consumer<Long> b;
-
-            BoxingAdapter(Consumer<Long> b) {
-                this.b = b;
-            }
-
-            @Override
-            public void accept(Long value) {
-                throw new IllegalStateException();
-            }
-
-            @Override
-            public void accept(long value) {
-                b.accept(value);
-            }
-        }
-
-        testSpliterator(supplier, BoxingAdapter::new, asserter);
-    }
-
-    public static void testDoubleSpliterator(Supplier<Spliterator.OfDouble> supplier) {
-        testDoubleSpliterator(supplier, defaultContentAsserter());
-    }
-
-    public static void testDoubleSpliterator(Supplier<Spliterator.OfDouble> supplier,
-                                             ContentAsserter<Double> asserter) {
-        class BoxingAdapter implements Consumer<Double>, DoubleConsumer {
-            private final Consumer<Double> b;
-
-            BoxingAdapter(Consumer<Double> b) {
-                this.b = b;
-            }
-
-            @Override
-            public void accept(Double value) {
-                throw new IllegalStateException();
-            }
-
-            @Override
-            public void accept(double value) {
-                b.accept(value);
-            }
-        }
-
-        testSpliterator(supplier, BoxingAdapter::new, asserter);
-    }
-
-    static <T, S extends Spliterator<T>> void testSpliterator(Supplier<S> supplier,
-                                                              UnaryOperator<Consumer<T>> boxingAdapter,
-                                                              ContentAsserter<T> asserter) {
-        ArrayList<T> fromForEach = new ArrayList<>();
-        Spliterator<T> spliterator = supplier.get();
-        Consumer<T> addToFromForEach = boxingAdapter.apply(fromForEach::add);
-        spliterator.forEachRemaining(addToFromForEach);
-
-        Collection<T> exp = Collections.unmodifiableList(fromForEach);
-
-        testNullPointerException(supplier);
-        testForEach(exp, supplier, boxingAdapter, asserter);
-        testTryAdvance(exp, supplier, boxingAdapter, asserter);
-        testMixedTryAdvanceForEach(exp, supplier, boxingAdapter, asserter);
-        testMixedTraverseAndSplit(exp, supplier, boxingAdapter, asserter);
-        testSplitAfterFullTraversal(supplier, boxingAdapter);
-        testSplitOnce(exp, supplier, boxingAdapter, asserter);
-        testSplitSixDeep(exp, supplier, boxingAdapter, asserter);
-        testSplitUntilNull(exp, supplier, boxingAdapter, asserter);
-    }
-
-    //
-
-    private static <T, S extends Spliterator<T>> void testNullPointerException(Supplier<S> s) {
-        S sp = s.get();
-        // Have to check instances and use casts to avoid tripwire messages and
-        // directly test the primitive methods
-        if (sp instanceof Spliterator.OfInt) {
-            Spliterator.OfInt psp = (Spliterator.OfInt) sp;
-            executeAndCatch(NullPointerException.class, () -> psp.forEachRemaining((IntConsumer) null));
-            executeAndCatch(NullPointerException.class, () -> psp.tryAdvance((IntConsumer) null));
-        }
-        else if (sp instanceof Spliterator.OfLong) {
-            Spliterator.OfLong psp = (Spliterator.OfLong) sp;
-            executeAndCatch(NullPointerException.class, () -> psp.forEachRemaining((LongConsumer) null));
-            executeAndCatch(NullPointerException.class, () -> psp.tryAdvance((LongConsumer) null));
-        }
-        else if (sp instanceof Spliterator.OfDouble) {
-            Spliterator.OfDouble psp = (Spliterator.OfDouble) sp;
-            executeAndCatch(NullPointerException.class, () -> psp.forEachRemaining((DoubleConsumer) null));
-            executeAndCatch(NullPointerException.class, () -> psp.tryAdvance((DoubleConsumer) null));
-        }
-        else {
-            executeAndCatch(NullPointerException.class, () -> sp.forEachRemaining(null));
-            executeAndCatch(NullPointerException.class, () -> sp.tryAdvance(null));
-        }
-    }
-
-    private static <T, S extends Spliterator<T>> void testForEach(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter,
-            ContentAsserter<T> asserter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        ArrayList<T> fromForEach = new ArrayList<>();
-        spliterator = supplier.get();
-        Consumer<T> addToFromForEach = boxingAdapter.apply(fromForEach::add);
-        spliterator.forEachRemaining(addToFromForEach);
-
-        // Assert that forEach now produces no elements
-        spliterator.forEachRemaining(boxingAdapter.apply(
-                e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
-        // Assert that tryAdvance now produce no elements
-        spliterator.tryAdvance(boxingAdapter.apply(
-                e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
-
-        // assert that size, tryAdvance, and forEach are consistent
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, exp.size());
-        }
-        assertEquals(fromForEach.size(), exp.size());
-
-        asserter.assertContents(fromForEach, exp, isOrdered);
-    }
-
-    private static <T, S extends Spliterator<T>> void testTryAdvance(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter,
-            ContentAsserter<T> asserter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        spliterator = supplier.get();
-        ArrayList<T> fromTryAdvance = new ArrayList<>();
-        Consumer<T> addToFromTryAdvance = boxingAdapter.apply(fromTryAdvance::add);
-        while (spliterator.tryAdvance(addToFromTryAdvance)) { }
-
-        // Assert that forEach now produces no elements
-        spliterator.forEachRemaining(boxingAdapter.apply(
-                e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
-        // Assert that tryAdvance now produce no elements
-        spliterator.tryAdvance(boxingAdapter.apply(
-                e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
-
-        // assert that size, tryAdvance, and forEach are consistent
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, exp.size());
-        }
-        assertEquals(fromTryAdvance.size(), exp.size());
-
-        asserter.assertContents(fromTryAdvance, exp, isOrdered);
-    }
-
-    private static <T, S extends Spliterator<T>> void testMixedTryAdvanceForEach(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter,
-            ContentAsserter<T> asserter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        // tryAdvance first few elements, then forEach rest
-        ArrayList<T> dest = new ArrayList<>();
-        spliterator = supplier.get();
-        Consumer<T> addToDest = boxingAdapter.apply(dest::add);
-        for (int i = 0; i < 10 && spliterator.tryAdvance(addToDest); i++) { }
-        spliterator.forEachRemaining(addToDest);
-
-        // Assert that forEach now produces no elements
-        spliterator.forEachRemaining(boxingAdapter.apply(
-                e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
-        // Assert that tryAdvance now produce no elements
-        spliterator.tryAdvance(boxingAdapter.apply(
-                e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
-
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, dest.size());
-        }
-        assertEquals(dest.size(), exp.size());
-
-        asserter.assertContents(dest, exp, isOrdered);
-    }
-
-    private static <T, S extends Spliterator<T>> void testMixedTraverseAndSplit(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter,
-            ContentAsserter<T> asserter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        // tryAdvance first few elements, then forEach rest
-        ArrayList<T> dest = new ArrayList<>();
-        spliterator = supplier.get();
-        Consumer<T> b = boxingAdapter.apply(dest::add);
-
-        Spliterator<T> spl1, spl2, spl3;
-        spliterator.tryAdvance(b);
-        spl2 = spliterator.trySplit();
-        if (spl2 != null) {
-            spl2.tryAdvance(b);
-            spl1 = spl2.trySplit();
-            if (spl1 != null) {
-                spl1.tryAdvance(b);
-                spl1.forEachRemaining(b);
-            }
-            spl2.tryAdvance(b);
-            spl2.forEachRemaining(b);
-        }
-        spliterator.tryAdvance(b);
-        spl3 = spliterator.trySplit();
-        if (spl3 != null) {
-            spl3.tryAdvance(b);
-            spl3.forEachRemaining(b);
-        }
-        spliterator.tryAdvance(b);
-        spliterator.forEachRemaining(b);
-
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, dest.size());
-        }
-        assertEquals(dest.size(), exp.size());
-
-        asserter.assertContents(dest, exp, isOrdered);
-    }
-
-    private static <T, S extends Spliterator<T>> void testSplitAfterFullTraversal(
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter) {
-        // Full traversal using tryAdvance
-        Spliterator<T> spliterator = supplier.get();
-        while (spliterator.tryAdvance(boxingAdapter.apply(e -> { }))) { }
-        Spliterator<T> split = spliterator.trySplit();
-        assertNull(split);
-
-        // Full traversal using forEach
-        spliterator = supplier.get();
-        spliterator.forEachRemaining(boxingAdapter.apply(e -> { }));
-        split = spliterator.trySplit();
-        assertNull(split);
-
-        // Full traversal using tryAdvance then forEach
-        spliterator = supplier.get();
-        spliterator.tryAdvance(boxingAdapter.apply(e -> { }));
-        spliterator.forEachRemaining(boxingAdapter.apply(e -> { }));
-        split = spliterator.trySplit();
-        assertNull(split);
-    }
-
-    private static <T, S extends Spliterator<T>> void testSplitOnce(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter,
-            ContentAsserter<T> asserter) {
-        S spliterator = supplier.get();
-        long sizeIfKnown = spliterator.getExactSizeIfKnown();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        ArrayList<T> fromSplit = new ArrayList<>();
-        Spliterator<T> s1 = supplier.get();
-        Spliterator<T> s2 = s1.trySplit();
-        long s1Size = s1.getExactSizeIfKnown();
-        long s2Size = (s2 != null) ? s2.getExactSizeIfKnown() : 0;
-        Consumer<T> addToFromSplit = boxingAdapter.apply(fromSplit::add);
-        if (s2 != null)
-            s2.forEachRemaining(addToFromSplit);
-        s1.forEachRemaining(addToFromSplit);
-
-        if (sizeIfKnown >= 0) {
-            assertEquals(sizeIfKnown, fromSplit.size());
-            if (s1Size >= 0 && s2Size >= 0)
-                assertEquals(sizeIfKnown, s1Size + s2Size);
-        }
-
-        asserter.assertContents(fromSplit, exp, isOrdered);
-    }
-
-    private static <T, S extends Spliterator<T>> void testSplitSixDeep(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter,
-            ContentAsserter<T> asserter) {
-        S spliterator = supplier.get();
-        boolean isOrdered = spliterator.hasCharacteristics(Spliterator.ORDERED);
-
-        for (int depth=0; depth < 6; depth++) {
-            List<T> dest = new ArrayList<>();
-            spliterator = supplier.get();
-
-            assertSpliterator(spliterator);
-
-            // verify splitting with forEach
-            splitSixDeepVisitor(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), false);
-            asserter.assertContents(dest, exp, isOrdered);
-
-            // verify splitting with tryAdvance
-            dest.clear();
-            spliterator = supplier.get();
-            splitSixDeepVisitor(depth, 0, dest, spliterator, boxingAdapter, spliterator.characteristics(), true);
-            asserter.assertContents(dest, exp, isOrdered);
-        }
-    }
-
-    private static <T, S extends Spliterator<T>>
-    void splitSixDeepVisitor(int depth, int curLevel,
-                             List<T> dest, S spliterator, UnaryOperator<Consumer<T>> boxingAdapter,
-                             int rootCharacteristics, boolean useTryAdvance) {
-        if (curLevel < depth) {
-            long beforeSize = spliterator.getExactSizeIfKnown();
-            Spliterator<T> split = spliterator.trySplit();
-            if (split != null) {
-                assertSpliterator(split, rootCharacteristics);
-                assertSpliterator(spliterator, rootCharacteristics);
-
-                if ((rootCharacteristics & Spliterator.SUBSIZED) != 0 &&
-                    (rootCharacteristics & Spliterator.SIZED) != 0) {
-                    assertEquals(beforeSize, split.estimateSize() + spliterator.estimateSize());
-                }
-                splitSixDeepVisitor(depth, curLevel + 1, dest, split, boxingAdapter, rootCharacteristics, useTryAdvance);
-            }
-            splitSixDeepVisitor(depth, curLevel + 1, dest, spliterator, boxingAdapter, rootCharacteristics, useTryAdvance);
-        }
-        else {
-            long sizeIfKnown = spliterator.getExactSizeIfKnown();
-            if (useTryAdvance) {
-                Consumer<T> addToDest = boxingAdapter.apply(dest::add);
-                int count = 0;
-                while (spliterator.tryAdvance(addToDest)) {
-                    ++count;
-                }
-
-                if (sizeIfKnown >= 0)
-                    assertEquals(sizeIfKnown, count);
-
-                // Assert that forEach now produces no elements
-                spliterator.forEachRemaining(boxingAdapter.apply(
-                        e -> fail("Spliterator.forEach produced an element after spliterator exhausted: " + e)));
-
-                Spliterator<T> split = spliterator.trySplit();
-                assertNull(split);
-            }
-            else {
-                List<T> leafDest = new ArrayList<>();
-                Consumer<T> addToLeafDest = boxingAdapter.apply(leafDest::add);
-                spliterator.forEachRemaining(addToLeafDest);
-
-                if (sizeIfKnown >= 0)
-                    assertEquals(sizeIfKnown, leafDest.size());
-
-                // Assert that forEach now produces no elements
-                spliterator.tryAdvance(boxingAdapter.apply(
-                        e -> fail("Spliterator.tryAdvance produced an element after spliterator exhausted: " + e)));
-
-                Spliterator<T> split = spliterator.trySplit();
-                assertNull(split);
-
-                dest.addAll(leafDest);
-            }
-        }
-    }
-
-    private static <T, S extends Spliterator<T>> void testSplitUntilNull(
-            Collection<T> exp,
-            Supplier<S> supplier,
-            UnaryOperator<Consumer<T>> boxingAdapter,
-            ContentAsserter<T> asserter) {
-        Spliterator<T> s = supplier.get();
-        boolean isOrdered = s.hasCharacteristics(Spliterator.ORDERED);
-        assertSpliterator(s);
-
-        List<T> splits = new ArrayList<>();
-        Consumer<T> c = boxingAdapter.apply(splits::add);
-
-        testSplitUntilNull(new SplitNode<T>(c, s));
-        asserter.assertContents(splits, exp, isOrdered);
-    }
-
-    private static class SplitNode<T> {
-        // Constant for every node
-        final Consumer<T> c;
-        final int rootCharacteristics;
-
-        final Spliterator<T> s;
-
-        SplitNode(Consumer<T> c, Spliterator<T> s) {
-            this(c, s.characteristics(), s);
-        }
-
-        private SplitNode(Consumer<T> c, int rootCharacteristics, Spliterator<T> s) {
-            this.c = c;
-            this.rootCharacteristics = rootCharacteristics;
-            this.s = s;
-        }
-
-        SplitNode<T> fromSplit(Spliterator<T> split) {
-            return new SplitNode<>(c, rootCharacteristics, split);
-        }
-    }
-
-    /**
-     * Set the maximum stack capacity to 0.25MB. This should be more than enough to detect a bad spliterator
-     * while not unduly disrupting test infrastructure given the test data sizes that are used are small.
-     * Note that j.u.c.ForkJoinPool sets the max queue size to 64M (1 << 26).
-     */
-    private static final int MAXIMUM_STACK_CAPACITY = 1 << 18; // 0.25MB
-
-    private static <T> void testSplitUntilNull(SplitNode<T> e) {
-        // Use an explicit stack to avoid a StackOverflowException when testing a Spliterator
-        // that when repeatedly split produces a right-balanced (and maybe degenerate) tree, or
-        // for a spliterator that is badly behaved.
-        Deque<SplitNode<T>> stack = new ArrayDeque<>();
-        stack.push(e);
-
-        int iteration = 0;
-        while (!stack.isEmpty()) {
-            assertTrue(iteration++ < MAXIMUM_STACK_CAPACITY, "Exceeded maximum stack modification count of 1 << 18");
-
-            e = stack.pop();
-            Spliterator<T> parentAndRightSplit = e.s;
-
-            long parentEstimateSize = parentAndRightSplit.estimateSize();
-            assertTrue(parentEstimateSize >= 0,
-                       String.format("Split size estimate %d < 0", parentEstimateSize));
-
-            long parentSize = parentAndRightSplit.getExactSizeIfKnown();
-            Spliterator<T> leftSplit = parentAndRightSplit.trySplit();
-            if (leftSplit == null) {
-                parentAndRightSplit.forEachRemaining(e.c);
-                continue;
-            }
-
-            assertSpliterator(leftSplit, e.rootCharacteristics);
-            assertSpliterator(parentAndRightSplit, e.rootCharacteristics);
-
-            if (parentEstimateSize != Long.MAX_VALUE && leftSplit.estimateSize() > 0
-                && parentAndRightSplit.estimateSize() > 0) {
-                assertTrue(leftSplit.estimateSize() < parentEstimateSize,
-                           String.format("Left split size estimate %d >= parent split size estimate %d",
-                                         leftSplit.estimateSize(), parentEstimateSize));
-                assertTrue(parentAndRightSplit.estimateSize() < parentEstimateSize,
-                           String.format("Right split size estimate %d >= parent split size estimate %d",
-                                         leftSplit.estimateSize(), parentEstimateSize));
-            }
-            else {
-                assertTrue(leftSplit.estimateSize() <= parentEstimateSize,
-                           String.format("Left split size estimate %d > parent split size estimate %d",
-                                         leftSplit.estimateSize(), parentEstimateSize));
-                assertTrue(parentAndRightSplit.estimateSize() <= parentEstimateSize,
-                           String.format("Right split size estimate %d > parent split size estimate %d",
-                                         leftSplit.estimateSize(), parentEstimateSize));
-            }
-
-            long leftSize = leftSplit.getExactSizeIfKnown();
-            long rightSize = parentAndRightSplit.getExactSizeIfKnown();
-            if (parentSize >= 0 && leftSize >= 0 && rightSize >= 0)
-                assertEquals(parentSize, leftSize + rightSize,
-                             String.format("exact left split size %d + exact right split size %d != parent exact split size %d",
-                                           leftSize, rightSize, parentSize));
-
-            // Add right side to stack first so left side is popped off first
-            stack.push(e.fromSplit(parentAndRightSplit));
-            stack.push(e.fromSplit(leftSplit));
-        }
-    }
-
-    private static void assertSpliterator(Spliterator<?> s, int rootCharacteristics) {
-        if ((rootCharacteristics & Spliterator.SUBSIZED) != 0) {
-            assertTrue(s.hasCharacteristics(Spliterator.SUBSIZED),
-                       "Child split is not SUBSIZED when root split is SUBSIZED");
-        }
-        assertSpliterator(s);
-    }
-
-    private static void assertSpliterator(Spliterator<?> s) {
-        if (s.hasCharacteristics(Spliterator.SUBSIZED)) {
-            assertTrue(s.hasCharacteristics(Spliterator.SIZED));
-        }
-        if (s.hasCharacteristics(Spliterator.SIZED)) {
-            assertTrue(s.estimateSize() != Long.MAX_VALUE);
-            assertTrue(s.getExactSizeIfKnown() >= 0);
-        }
-        try {
-            s.getComparator();
-            assertTrue(s.hasCharacteristics(Spliterator.SORTED));
-        } catch (IllegalStateException e) {
-            assertFalse(s.hasCharacteristics(Spliterator.SORTED));
-        }
-    }
-
-    private static<T> void assertContents(Collection<T> actual, Collection<T> expected, boolean isOrdered) {
-        if (isOrdered) {
-            assertEquals(actual, expected);
-        }
-        else {
-            LambdaTestHelpers.assertContentsUnordered(actual, expected);
-        }
-    }
-
-    private static void executeAndCatch(Class<? extends Exception> expected, Runnable r) {
-        Exception caught = null;
-        try {
-            r.run();
-        }
-        catch (Exception e) {
-            caught = e;
-        }
-
-        assertNotNull(caught,
-                      String.format("No Exception was thrown, expected an Exception of %s to be thrown",
-                                    expected.getName()));
-        assertTrue(expected.isInstance(caught),
-                   String.format("Exception thrown %s not an instance of %s",
-                                 caught.getClass().getName(), expected.getName()));
-    }
-
-    static<U> void mixedTraverseAndSplit(Consumer<U> b, Spliterator<U> splTop) {
-        Spliterator<U> spl1, spl2, spl3;
-        splTop.tryAdvance(b);
-        spl2 = splTop.trySplit();
-        if (spl2 != null) {
-            spl2.tryAdvance(b);
-            spl1 = spl2.trySplit();
-            if (spl1 != null) {
-                spl1.tryAdvance(b);
-                spl1.forEachRemaining(b);
-            }
-            spl2.tryAdvance(b);
-            spl2.forEachRemaining(b);
-        }
-        splTop.tryAdvance(b);
-        spl3 = splTop.trySplit();
-        if (spl3 != null) {
-            spl3.tryAdvance(b);
-            spl3.forEachRemaining(b);
-        }
-        splTop.tryAdvance(b);
-        splTop.forEachRemaining(b);
-    }
-
-    static void mixedTraverseAndSplit(IntConsumer b, Spliterator.OfInt splTop) {
-        Spliterator.OfInt spl1, spl2, spl3;
-        splTop.tryAdvance(b);
-        spl2 = splTop.trySplit();
-        if (spl2 != null) {
-            spl2.tryAdvance(b);
-            spl1 = spl2.trySplit();
-            if (spl1 != null) {
-                spl1.tryAdvance(b);
-                spl1.forEachRemaining(b);
-            }
-            spl2.tryAdvance(b);
-            spl2.forEachRemaining(b);
-        }
-        splTop.tryAdvance(b);
-        spl3 = splTop.trySplit();
-        if (spl3 != null) {
-            spl3.tryAdvance(b);
-            spl3.forEachRemaining(b);
-        }
-        splTop.tryAdvance(b);
-        splTop.forEachRemaining(b);
-    }
-    static void mixedTraverseAndSplit(LongConsumer b, Spliterator.OfLong splTop) {
-        Spliterator.OfLong spl1, spl2, spl3;
-        splTop.tryAdvance(b);
-        spl2 = splTop.trySplit();
-        if (spl2 != null) {
-            spl2.tryAdvance(b);
-            spl1 = spl2.trySplit();
-            if (spl1 != null) {
-                spl1.tryAdvance(b);
-                spl1.forEachRemaining(b);
-            }
-            spl2.tryAdvance(b);
-            spl2.forEachRemaining(b);
-        }
-        splTop.tryAdvance(b);
-        spl3 = splTop.trySplit();
-        if (spl3 != null) {
-            spl3.tryAdvance(b);
-            spl3.forEachRemaining(b);
-        }
-        splTop.tryAdvance(b);
-        splTop.forEachRemaining(b);
-    }
-
-    static void mixedTraverseAndSplit(DoubleConsumer b, Spliterator.OfDouble splTop) {
-        Spliterator.OfDouble spl1, spl2, spl3;
-        splTop.tryAdvance(b);
-        spl2 = splTop.trySplit();
-        if (spl2 != null) {
-            spl2.tryAdvance(b);
-            spl1 = spl2.trySplit();
-            if (spl1 != null) {
-                spl1.tryAdvance(b);
-                spl1.forEachRemaining(b);
-            }
-            spl2.tryAdvance(b);
-            spl2.forEachRemaining(b);
-        }
-        splTop.tryAdvance(b);
-        spl3 = splTop.trySplit();
-        if (spl3 != null) {
-            spl3.tryAdvance(b);
-            spl3.forEachRemaining(b);
-        }
-        splTop.tryAdvance(b);
-        splTop.forEachRemaining(b);
-    }
-}
--- a/jdk/test/java/util/stream/bootlib/java.base/java/util/stream/StreamTestScenario.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/stream/bootlib/java.base/java/util/stream/StreamTestScenario.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 import java.util.Iterator;
 import java.util.Set;
 import java.util.Spliterator;
+import java.util.SpliteratorTestHelper;
 import java.util.function.Consumer;
 import java.util.function.Function;
 
--- a/jdk/test/java/util/stream/boottest/java.base/java/util/stream/DoubleNodeTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/stream/boottest/java.base/java/util/stream/DoubleNodeTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 import java.util.List;
 import java.util.PrimitiveIterator;
 import java.util.Spliterators;
+import java.util.SpliteratorTestHelper;
 import java.util.function.Function;
 
 import org.testng.annotations.DataProvider;
--- a/jdk/test/java/util/stream/boottest/java.base/java/util/stream/IntNodeTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/stream/boottest/java.base/java/util/stream/IntNodeTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 import java.util.List;
 import java.util.PrimitiveIterator;
 import java.util.Spliterators;
+import java.util.SpliteratorTestHelper;
 import java.util.function.Function;
 
 import org.testng.annotations.DataProvider;
--- a/jdk/test/java/util/stream/boottest/java.base/java/util/stream/LongNodeTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/stream/boottest/java.base/java/util/stream/LongNodeTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 import java.util.List;
 import java.util.PrimitiveIterator;
 import java.util.Spliterators;
+import java.util.SpliteratorTestHelper;
 import java.util.function.Function;
 
 import org.testng.annotations.DataProvider;
--- a/jdk/test/java/util/stream/boottest/java.base/java/util/stream/NodeTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/stream/boottest/java.base/java/util/stream/NodeTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,7 @@
 import java.util.Collections;
 import java.util.Iterator;
 import java.util.List;
+import java.util.SpliteratorTestHelper;
 import java.util.function.Function;
 
 import org.testng.annotations.DataProvider;
--- a/jdk/test/java/util/stream/boottest/java.base/java/util/stream/SliceSpliteratorTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/stream/boottest/java.base/java/util/stream/SliceSpliteratorTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 2017, 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
@@ -30,6 +30,7 @@
 import java.util.Collection;
 import java.util.List;
 import java.util.Spliterator;
+import java.util.SpliteratorTestHelper;
 
 import static java.util.stream.Collectors.toList;
 import static org.testng.Assert.assertEquals;
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/RangeTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/RangeTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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,10 +25,10 @@
 import java.util.Arrays;
 import java.util.Optional;
 import java.util.Spliterator;
+import java.util.SpliteratorTestHelper;
 import java.util.stream.IntStream;
 import java.util.stream.LongStream;
 import java.util.stream.OpTestCase;
-import java.util.stream.SpliteratorTestHelper;
 import java.util.stream.Stream;
 import java.util.stream.TestData;
 
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SpliteratorTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/SpliteratorTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -29,6 +29,7 @@
 import java.util.List;
 import java.util.function.Supplier;
 import java.util.Spliterator;
+import java.util.SpliteratorTestHelper;
 import java.util.stream.*;
 
 import static org.testng.Assert.*;
--- a/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamSpliteratorTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/java/util/stream/test/org/openjdk/tests/java/util/stream/StreamSpliteratorTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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 java.util.Comparator;
 import java.util.List;
 import java.util.Spliterator;
+import java.util.SpliteratorTestHelper;
 import java.util.function.Consumer;
 import java.util.function.DoubleConsumer;
 import java.util.function.Function;
@@ -46,7 +47,6 @@
 import java.util.stream.LongStream;
 import java.util.stream.LongStreamTestDataProvider;
 import java.util.stream.OpTestCase;
-import java.util.stream.SpliteratorTestHelper;
 import java.util.stream.Stream;
 import java.util.stream.StreamSupport;
 import java.util.stream.StreamTestDataProvider;
--- a/jdk/test/javax/swing/plaf/basic/BasicScrollPaneUI/8166591/TooMuchWheelRotationEventsTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/javax/swing/plaf/basic/BasicScrollPaneUI/8166591/TooMuchWheelRotationEventsTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -40,7 +40,7 @@
 
 /*
  * @test
- * @bug 8166591
+ * @bug 8166591 8173876
  * @key headful
  * @summary [macos 10.12] Trackpad scrolling of text on OS X 10.12 Sierra
  *    is very fast (Trackpad, Retina only)
--- a/jdk/test/javax/swing/text/html/StyleSheet/bug4936917.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/javax/swing/text/html/StyleSheet/bug4936917.java	Thu Mar 16 20:47:03 2017 +0000
@@ -21,7 +21,7 @@
  * questions.
  */
 /* @test
-   @bug 4936917 7190578
+   @bug 4936917 7190578 8174717
    @summary  Tests if background is correctly painted when <BODY> has css margins
    @author Denis Sharypov
    @library ../../../regtesthelpers
@@ -72,6 +72,7 @@
         blockTillDisplayed(editorPane);
         Robot robot  = new Robot();
         robot.waitForIdle();
+        robot.delay(300);
 
         int x0 = p.x + 15 ;
         int y = p.y + 15;
--- a/jdk/test/javax/xml/jaxp/common/8035437/Document.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,28 +0,0 @@
-/*
- * Copyright (c) 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
- * 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 org.w3c.dom;
-
-public interface Document {
-
-    public org.w3c.dom.DocumentType getDoctype();
-}
--- a/jdk/test/javax/xml/jaxp/common/8035437/DocumentImpl.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,67 +0,0 @@
-/*
- * Copyright (c) 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
- * 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 com.sun.org.apache.xerces.internal.dom;
-
-import org.w3c.dom.Document;
-import org.w3c.dom.Node;
-import org.w3c.dom.DOMImplementation;
-
-public class DocumentImpl implements Document, Node {
-
-    public short getNodeType() {
-        return 9; //DOCUMENT_NODE = 9
-    }
-
-    public org.w3c.dom.Document getOwnerDocument() {
-        return null;
-    }
-
-    public Node getFirstChild() {
-        return null;
-    }
-
-    public String getPrefix() {
-        return "TestPrefix";
-    }
-
-    public String getLocalName() {
-        return "LocalName";
-    }
-
-    public boolean hasAttributes() {
-        return false;
-    }
-
-    public Node renameNode(Node n, String namespaceURI, String name) {
-        return n;
-    }
-
-    public org.w3c.dom.DocumentType getDoctype() {
-        return null;
-    }
-
-    public DOMImplementation getImplementation() {
-        return DOMImplementationImpl.getDOMImplementation();
-    }
-
-}
--- a/jdk/test/javax/xml/jaxp/common/8035437/Node.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,38 +0,0 @@
-/*
- * Copyright (c) 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
- * 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 org.w3c.dom;
-
-public interface Node {
-
-    public short getNodeType();
-
-    public org.w3c.dom.Document getOwnerDocument();
-
-    public Node getFirstChild();
-
-    public String getPrefix();
-
-    public String getLocalName();
-
-    public boolean hasAttributes();
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/xml/jaxp/common/8035437/patch-src1/org/w3c/dom/Document.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 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
+ * 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 org.w3c.dom;
+
+public interface Document {
+
+    public org.w3c.dom.DocumentType getDoctype();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/xml/jaxp/common/8035437/patch-src1/org/w3c/dom/Node.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,38 @@
+/*
+ * Copyright (c) 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
+ * 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 org.w3c.dom;
+
+public interface Node {
+
+    public short getNodeType();
+
+    public org.w3c.dom.Document getOwnerDocument();
+
+    public Node getFirstChild();
+
+    public String getPrefix();
+
+    public String getLocalName();
+
+    public boolean hasAttributes();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/javax/xml/jaxp/common/8035437/patch-src2/com/sun/org/apache/xerces/internal/dom/DocumentImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,67 @@
+/*
+ * Copyright (c) 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
+ * 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 com.sun.org.apache.xerces.internal.dom;
+
+import org.w3c.dom.Document;
+import org.w3c.dom.Node;
+import org.w3c.dom.DOMImplementation;
+
+public class DocumentImpl implements Document, Node {
+
+    public short getNodeType() {
+        return 9; //DOCUMENT_NODE = 9
+    }
+
+    public org.w3c.dom.Document getOwnerDocument() {
+        return null;
+    }
+
+    public Node getFirstChild() {
+        return null;
+    }
+
+    public String getPrefix() {
+        return "TestPrefix";
+    }
+
+    public String getLocalName() {
+        return "LocalName";
+    }
+
+    public boolean hasAttributes() {
+        return false;
+    }
+
+    public Node renameNode(Node n, String namespaceURI, String name) {
+        return n;
+    }
+
+    public org.w3c.dom.DocumentType getDoctype() {
+        return null;
+    }
+
+    public DOMImplementation getImplementation() {
+        return DOMImplementationImpl.getDOMImplementation();
+    }
+
+}
--- a/jdk/test/javax/xml/jaxp/common/8035437/run.sh	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/javax/xml/jaxp/common/8035437/run.sh	Thu Mar 16 20:47:03 2017 +0000
@@ -28,13 +28,43 @@
 # @summary Tests that java.lang.AbstractMethodError is not thrown when
 #    serializing improper version of DocumentImpl class.
 
+OS=`uname -s`
+case "$OS" in
+  SunOS )
+    PS=":"
+    ;;
+  Linux )
+    PS=":"
+    ;;
+  Darwin )
+    PS=":"
+    ;;
+  AIX )
+    PS=":"
+    ;;
+  Windows*)
+    PS=";"
+    ;;
+  CYGWIN*)
+    PS=";"
+    ;;
+  * )
+    echo "Unrecognized system!"
+    exit 1;
+    ;;
+esac
+
 mkdir -p exec/java.xml compile/java.xml
 
 $COMPILEJAVA/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \
-   -d compile/java.xml -Xmodule:java.xml $TESTSRC/Document.java $TESTSRC/Node.java || exit 1
+   -d compile/java.xml --patch-module java.xml=$TESTSRC/patch-src1 \
+   $TESTSRC/patch-src1/org/w3c/dom/Document.java \
+   $TESTSRC/patch-src1/org/w3c/dom/Node.java || exit 1
 
 $COMPILEJAVA/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \
-   -d exec/java.xml --patch-module java.xml=compile/java.xml -Xmodule:java.xml $TESTSRC/DocumentImpl.java || exit 2
+   -d exec/java.xml --patch-module java.xml=compile/java.xml${PS}$TESTSRC/patch-src2 \
+   $TESTSRC/patch-src2/com/sun/org/apache/xerces/internal/dom/DocumentImpl.java \
+   || exit 2
 
 $COMPILEJAVA/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \
    $TESTSRC/AbstractMethodErrorTest.java -d exec || exit 3
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/jdk/internal/reflect/CallerSensitive/CheckCSMs.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,251 @@
+/*
+ * Copyright (c) 2017, 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 com.sun.tools.classfile.*;
+import com.sun.tools.jdeps.ClassFileReader;
+import static com.sun.tools.classfile.ConstantPool.*;
+import java.io.File;
+import java.io.IOException;
+import java.io.UncheckedIOException;
+import java.net.URI;
+import java.nio.file.FileSystem;
+import java.nio.file.FileSystems;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.concurrent.Callable;
+import java.util.concurrent.ConcurrentSkipListSet;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.ExecutorService;
+import java.util.concurrent.Executors;
+import java.util.concurrent.FutureTask;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/*
+ * @test
+ * @summary CallerSensitive methods should be static or final instance
+ *          methods except the known list of non-final instance methods
+ * @modules jdk.jdeps/com.sun.tools.classfile
+ *          jdk.jdeps/com.sun.tools.jdeps
+ * @build CheckCSMs
+ * @run main/othervm/timeout=900 CheckCSMs
+ */
+public class CheckCSMs {
+    private static int numThreads = 3;
+    private static boolean listCSMs = false;
+    private final ExecutorService pool;
+
+    // The goal is to remove this list of Non-final instance @CS methods
+    // over time.  Do not add any new one to this list.
+    private static Set<String> KNOWN_NON_FINAL_CSMS =
+      Set.of("java/io/ObjectStreamField#getType ()Ljava/lang/Class;",
+             "java/io/ObjectStreamClass#forClass ()Ljava/lang/Class;",
+             "java/lang/Runtime#load (Ljava/lang/String;)V",
+             "java/lang/Runtime#loadLibrary (Ljava/lang/String;)V",
+             "java/lang/Thread#getContextClassLoader ()Ljava/lang/ClassLoader;",
+             "javax/sql/rowset/serial/SerialJavaObject#getFields ()[Ljava/lang/reflect/Field;"
+      );
+
+    public static void main(String[] args) throws Exception {
+        if (args.length > 0 && args[0].equals("--list")) {
+            listCSMs = true;
+        }
+
+        CheckCSMs checkCSMs = new CheckCSMs();
+        Set<String> result = checkCSMs.run(getPlatformClasses());
+        if (!KNOWN_NON_FINAL_CSMS.equals(result)) {
+            Set<String> diff = new HashSet<>(result);
+            diff.removeAll(KNOWN_NON_FINAL_CSMS);
+            throw new RuntimeException("Unexpected non-final instance method: " +
+                result.stream().sorted()
+                      .collect(Collectors.joining("\n", "\n", "")));
+        }
+    }
+
+    private final Set<String> nonFinalCSMs = new ConcurrentSkipListSet<>();
+    private final ReferenceFinder finder;
+    public CheckCSMs() {
+        this.finder = new ReferenceFinder(getFilter(), getVisitor());
+        pool = Executors.newFixedThreadPool(numThreads);
+
+    }
+
+    public Set<String> run(Stream<Path> classes)
+        throws IOException, InterruptedException, ExecutionException,
+               ConstantPoolException
+    {
+        classes.forEach(this::processPath);
+        waitForCompletion();
+        pool.shutdown();
+        return nonFinalCSMs;
+    }
+
+
+    private ReferenceFinder.Filter getFilter() {
+        final String classname = "jdk/internal/reflect/Reflection";
+        final String method = "getCallerClass";
+        return new ReferenceFinder.Filter() {
+            public boolean accept(ConstantPool cpool, CPRefInfo cpref) {
+                try {
+                    CONSTANT_NameAndType_info nat = cpref.getNameAndTypeInfo();
+                    return cpref.getClassName().equals(classname) && nat.getName().equals(method);
+                } catch (ConstantPoolException ex) {
+                    throw new RuntimeException(ex);
+                }
+            }
+        };
+    }
+
+    private ReferenceFinder.Visitor getVisitor() {
+        return new ReferenceFinder.Visitor() {
+            public void visit(ClassFile cf, Method m,  List<CPRefInfo> refs) {
+                try {
+                    // ignore jdk.unsupported/sun.reflect.Reflection.getCallerClass
+                    // which is a "special" delegate to the internal getCallerClass
+                    if (cf.getName().equals("sun/reflect/Reflection") &&
+                        m.getName(cf.constant_pool).equals("getCallerClass"))
+                        return;
+
+                    String name = String.format("%s#%s %s", cf.getName(),
+                                                m.getName(cf.constant_pool),
+                                                m.descriptor.getValue(cf.constant_pool));
+                    if (!CheckCSMs.isStaticOrFinal(cf, m, cf.constant_pool)) {
+                        System.err.println("Unsupported @CallerSensitive: " + name);
+                        nonFinalCSMs.add(name);
+                    } else {
+                        if (listCSMs) {
+                            System.out.format("@CS  %s%n", name);
+                        }
+                    }
+                } catch (ConstantPoolException ex) {
+                    throw new RuntimeException(ex);
+                }
+            }
+        };
+    }
+
+    void processPath(Path path) {
+        try {
+            ClassFileReader reader = ClassFileReader.newInstance(path);
+            for (ClassFile cf : reader.getClassFiles()) {
+                if (cf.access_flags.is(AccessFlags.ACC_MODULE))
+                    continue;
+
+                String classFileName = cf.getName();
+                // for each ClassFile
+                //    parse constant pool to find matching method refs
+                //      parse each method (caller)
+                //      - visit and find method references matching the given method name
+                pool.submit(getTask(cf));
+            }
+        } catch (IOException x) {
+            throw new UncheckedIOException(x);
+        } catch (ConstantPoolException x) {
+            throw new RuntimeException(x);
+        }
+    }
+
+    private static final String CALLER_SENSITIVE_ANNOTATION
+        = "Ljdk/internal/reflect/CallerSensitive;";
+
+    private static boolean isCallerSensitive(Method m, ConstantPool cp)
+        throws ConstantPoolException
+    {
+        RuntimeAnnotations_attribute attr =
+            (RuntimeAnnotations_attribute)m.attributes.get(Attribute.RuntimeVisibleAnnotations);
+        if (attr != null) {
+            for (int i = 0; i < attr.annotations.length; i++) {
+                Annotation ann = attr.annotations[i];
+                String annType = cp.getUTF8Value(ann.type_index);
+                if (CALLER_SENSITIVE_ANNOTATION.equals(annType)) {
+                    return true;
+                }
+            }
+        }
+        return false;
+    }
+
+    private static boolean isStaticOrFinal(ClassFile cf, Method m, ConstantPool cp)
+        throws ConstantPoolException
+    {
+        if (!isCallerSensitive(m, cp))
+            return false;
+
+        // either a static method or a final instance method
+        return m.access_flags.is(AccessFlags.ACC_STATIC) ||
+               m.access_flags.is(AccessFlags.ACC_FINAL) ||
+               cf.access_flags.is(AccessFlags.ACC_FINAL);
+    }
+
+    private final List<FutureTask<Void>> tasks = new ArrayList<FutureTask<Void>>();
+    private FutureTask<Void> getTask(final ClassFile cf) {
+        FutureTask<Void> task = new FutureTask<Void>(new Callable<Void>() {
+            public Void call() throws Exception {
+                finder.parse(cf);
+                return null;
+            }
+        });
+        tasks.add(task);
+        return task;
+    }
+
+    private void waitForCompletion() throws InterruptedException, ExecutionException {
+        for (FutureTask<Void> t : tasks) {
+            t.get();
+        }
+        if (tasks.isEmpty()) {
+            throw new RuntimeException("No classes found, or specified.");
+        }
+        System.out.println("Parsed " + tasks.size() + " classfiles");
+    }
+
+    static Stream<Path> getPlatformClasses() throws IOException {
+        Path home = Paths.get(System.getProperty("java.home"));
+
+        // Either an exploded build or an image.
+        File classes = home.resolve("modules").toFile();
+        if (classes.isDirectory()) {
+            return Stream.of(classes.toPath());
+        } else {
+            return jrtPaths();
+        }
+    }
+
+    static Stream<Path> jrtPaths() {
+        FileSystem jrt = FileSystems.getFileSystem(URI.create("jrt:/"));
+        Path root = jrt.getPath("/");
+
+        try {
+            return Files.walk(root)
+                    .filter(p -> p.getNameCount() > 1)
+                    .filter(p -> p.toString().endsWith(".class"));
+        } catch (IOException x) {
+            throw new UncheckedIOException(x);
+        }
+    }
+}
--- a/jdk/test/jdk/modules/etc/VerifyModuleDelegation.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/jdk/modules/etc/VerifyModuleDelegation.java	Thu Mar 16 20:47:03 2017 +0000
@@ -46,7 +46,7 @@
     private static final String JAVA_BASE = "java.base";
 
     private static final ModuleDescriptor BASE
-        = ModuleDescriptor.module(JAVA_BASE).build();
+        = ModuleDescriptor.newModule(JAVA_BASE).build();
 
     private static final Set<ModuleDescriptor> MREFS
             = Layer.boot().modules().stream().map(Module::getDescriptor)
--- a/jdk/test/jdk/modules/scenarios/container/src/container/container/Main.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/jdk/modules/scenarios/container/src/container/container/Main.java	Thu Mar 16 20:47:03 2017 +0000
@@ -71,9 +71,9 @@
         ModuleFinder finder = ModuleFinder.of(paths);
 
         Configuration cf = Layer.boot().configuration()
-            .resolveRequiresAndUses(finder,
-                                    ModuleFinder.of(),
-                                    Set.of(appModuleName));
+            .resolveAndBind(finder,
+                            ModuleFinder.of(),
+                            Set.of(appModuleName));
 
         System.out.println("Resolved");
         cf.modules().stream()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/org/omg/CORBA/OrbPropertiesTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,78 @@
+/*
+ * Copyright (c) 2017, 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.io.BufferedWriter;
+import java.io.FileWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+
+import org.omg.CORBA.ORB;
+
+/*
+ * @test
+ * @bug 8049375
+ * @summary Extend how the org.omg.CORBA.ORB handles the search for orb.properties
+ * @library /lib/testlibrary
+ * @build jdk.testlibrary.*
+ * @modules java.corba
+ * @compile OrbPropertiesTest.java TestOrbImpl.java TestSingletonOrbImpl.java
+ * @run main/othervm
+ *    -Djava.naming.provider.url=iiop://localhost:1050
+ *    -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
+ *    OrbPropertiesTest -port 1049
+ * @run main/othervm/secure=java.lang.SecurityManager/policy=jtreg.test.policy
+ *    -Djava.naming.provider.url=iiop://localhost:3050
+ *    -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory
+ *    OrbPropertiesTest -port 3049
+ */
+public class OrbPropertiesTest {
+
+    public static void main(String[] args) throws Exception {
+        updateOrbPropertiesFile();
+        // create and initialize the ORB
+        ORB orb = ORB.init(args, null);
+        if (!(orb instanceof TestOrbImpl)) {
+            throw new RuntimeException("org.omg.CORBA.ORBClass property not set as expected");
+        }
+        ORB singletonOrb = ORB.init();
+        System.out.println("singletonOrb class == " + singletonOrb.getClass().getName());
+        if (!(singletonOrb instanceof TestSingletonOrbImpl)) {
+            throw new RuntimeException("org.omg.CORBA.ORBSingletonClass property not set as expected");
+        }
+
+    }
+
+    private static void updateOrbPropertiesFile() throws Exception {
+        String orbPropertiesFile = System.getProperty("java.home", ".") + "/conf/orb.properties";
+        String orbClassMapping = "org.omg.CORBA.ORBClass TestOrbImpl";
+        String orbSingletonClassMapping = "org.omg.CORBA.ORBSingletonClass TestSingletonOrbImpl";
+        String orbPropertiesMappings = orbClassMapping + "\n" + orbSingletonClassMapping +"\n";
+        try (PrintWriter hfPWriter = new PrintWriter(new BufferedWriter(
+                new FileWriter(orbPropertiesFile, false)))) {
+            hfPWriter.println(orbPropertiesMappings);
+        } catch (IOException ioEx) {
+            ioEx.printStackTrace();
+            throw ioEx;
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/org/omg/CORBA/TestOrbImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) 2017, 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.applet.Applet;
+import java.util.Properties;
+
+import org.omg.CORBA.Any;
+import org.omg.CORBA.Context;
+import org.omg.CORBA.ContextList;
+import org.omg.CORBA.Environment;
+import org.omg.CORBA.ExceptionList;
+import org.omg.CORBA.NVList;
+import org.omg.CORBA.NamedValue;
+import org.omg.CORBA.ORB;
+import org.omg.CORBA.Object;
+import org.omg.CORBA.Request;
+import org.omg.CORBA.StructMember;
+import org.omg.CORBA.TCKind;
+import org.omg.CORBA.TypeCode;
+import org.omg.CORBA.UnionMember;
+import org.omg.CORBA.WrongTransaction;
+import org.omg.CORBA.ORBPackage.InvalidName;
+import org.omg.CORBA.portable.OutputStream;
+
+
+public class TestOrbImpl extends ORB{
+
+    @Override
+    protected void set_parameters(String[] args, Properties props) {
+
+    }
+
+    @Override
+    protected void set_parameters(Applet app, Properties props) {
+
+    }
+
+    @Override
+    public String[] list_initial_services() {
+        return null;
+    }
+
+    @Override
+    public Object resolve_initial_references(String object_name)
+            throws InvalidName {
+        return null;
+    }
+
+    @Override
+    public String object_to_string(Object obj) {
+        return null;
+    }
+
+    @Override
+    public Object string_to_object(String str) {
+        return null;
+    }
+
+    @Override
+    public NVList create_list(int count) {
+        return null;
+    }
+
+    @Override
+    public NamedValue create_named_value(String s, Any any, int flags) {
+        return null;
+    }
+
+    @Override
+    public ExceptionList create_exception_list() {
+        return null;
+    }
+
+    @Override
+    public ContextList create_context_list() {
+        return null;
+    }
+
+    @Override
+    public Context get_default_context() {
+        return null;
+    }
+
+    @Override
+    public Environment create_environment() {
+        return null;
+    }
+
+    @Override
+    public OutputStream create_output_stream() {
+        return null;
+    }
+
+    @Override
+    public void send_multiple_requests_oneway(Request[] req) {
+
+    }
+
+    @Override
+    public void send_multiple_requests_deferred(Request[] req) {
+
+    }
+
+    @Override
+    public boolean poll_next_response() {
+        return false;
+    }
+
+    @Override
+    public Request get_next_response() throws WrongTransaction {
+        return null;
+    }
+
+    @Override
+    public TypeCode get_primitive_tc(TCKind tcKind) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_struct_tc(String id, String name,
+            StructMember[] members) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_union_tc(String id, String name,
+            TypeCode discriminator_type, UnionMember[] members) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_enum_tc(String id, String name, String[] members) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_alias_tc(String id, String name,
+            TypeCode original_type) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_exception_tc(String id, String name,
+            StructMember[] members) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_interface_tc(String id, String name) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_string_tc(int bound) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_wstring_tc(int bound) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_sequence_tc(int bound, TypeCode element_type) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_recursive_sequence_tc(int bound, int offset) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_array_tc(int length, TypeCode element_type) {
+        return null;
+    }
+
+    @Override
+    public Any create_any() {
+        return null;
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/org/omg/CORBA/TestSingletonOrbImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,203 @@
+/*
+ * Copyright (c) 2017, 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.applet.Applet;
+import java.util.Properties;
+
+import org.omg.CORBA.Any;
+import org.omg.CORBA.Context;
+import org.omg.CORBA.ContextList;
+import org.omg.CORBA.Environment;
+import org.omg.CORBA.ExceptionList;
+import org.omg.CORBA.NVList;
+import org.omg.CORBA.NamedValue;
+import org.omg.CORBA.ORB;
+import org.omg.CORBA.Object;
+import org.omg.CORBA.Request;
+import org.omg.CORBA.StructMember;
+import org.omg.CORBA.TCKind;
+import org.omg.CORBA.TypeCode;
+import org.omg.CORBA.UnionMember;
+import org.omg.CORBA.WrongTransaction;
+import org.omg.CORBA.ORBPackage.InvalidName;
+import org.omg.CORBA.portable.OutputStream;
+
+
+public class TestSingletonOrbImpl extends ORB {
+
+    @Override
+    protected void set_parameters(String[] args, Properties props) {
+
+    }
+
+    @Override
+    protected void set_parameters(Applet app, Properties props) {
+
+    }
+
+    @Override
+    public String[] list_initial_services() {
+        return null;
+    }
+
+    @Override
+    public Object resolve_initial_references(String object_name)
+            throws InvalidName {
+        return null;
+    }
+
+    @Override
+    public String object_to_string(Object obj) {
+        return null;
+    }
+
+    @Override
+    public Object string_to_object(String str) {
+        return null;
+    }
+
+    @Override
+    public NVList create_list(int count) {
+        return null;
+    }
+
+    @Override
+    public NamedValue create_named_value(String s, Any any, int flags) {
+        return null;
+    }
+
+    @Override
+    public ExceptionList create_exception_list() {
+        return null;
+    }
+
+    @Override
+    public ContextList create_context_list() {
+        return null;
+    }
+
+    @Override
+    public Context get_default_context() {
+        return null;
+    }
+
+    @Override
+    public Environment create_environment() {
+        return null;
+    }
+
+    @Override
+    public OutputStream create_output_stream() {
+        return null;
+    }
+
+    @Override
+    public void send_multiple_requests_oneway(Request[] req) {
+
+    }
+
+    @Override
+    public void send_multiple_requests_deferred(Request[] req) {
+
+    }
+
+    @Override
+    public boolean poll_next_response() {
+        return false;
+    }
+
+    @Override
+    public Request get_next_response() throws WrongTransaction {
+        return null;
+    }
+
+    @Override
+    public TypeCode get_primitive_tc(TCKind tcKind) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_struct_tc(String id, String name,
+            StructMember[] members) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_union_tc(String id, String name,
+            TypeCode discriminator_type, UnionMember[] members) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_enum_tc(String id, String name, String[] members) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_alias_tc(String id, String name,
+            TypeCode original_type) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_exception_tc(String id, String name,
+            StructMember[] members) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_interface_tc(String id, String name) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_string_tc(int bound) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_wstring_tc(int bound) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_sequence_tc(int bound, TypeCode element_type) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_recursive_sequence_tc(int bound, int offset) {
+        return null;
+    }
+
+    @Override
+    public TypeCode create_array_tc(int length, TypeCode element_type) {
+        return null;
+    }
+
+    @Override
+    public Any create_any() {
+        return null;
+    }
+
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/org/omg/CORBA/jtreg.test.policy	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2016, 2017, 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.util.PropertyPermission "*", "read";
+  permission java.io.FilePermission "<<ALL FILES>>", "read, write, execute";
+};
+
+grant codeBase "file:${test.classes}/*" {
+  permission java.net.SocketPermission "*:*", "connect, accept, listen, resolve";
+  permission java.lang.RuntimePermission "accessClassInPackage.com.sun.jndi.cosnaming";
+};
--- a/jdk/test/sun/management/jdp/JdpJmxRemoteDynamicPortTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/sun/management/jdp/JdpJmxRemoteDynamicPortTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -27,7 +27,7 @@
  *  @summary Verify a non-zero value is assigned to jmxremote.port
  *           when VM is started with jmxremote.port=0.
  *  @library /lib/testlibrary
- *  @modules java.management/sun.management.jdp
+ *  @modules jdk.management.agent/sun.management.jdp
  *  @build jdk.testlibrary.* ClientConnection JdpTestUtil JdpTestCase JdpJmxRemoteDynamicPortTestCase DynamicLauncher
  *  @run main JdpJmxRemoteDynamicPortTest
  */
--- a/jdk/test/sun/rmi/rmic/newrmic/equivalence/run.sh	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/sun/rmi/rmic/newrmic/equivalence/run.sh	Thu Mar 16 20:47:03 2017 +0000
@@ -22,6 +22,8 @@
 #
 
 # @test
+# @ignore test is disabled, while further discussion on the rmic -Xnew feature
+# takes place (c.f JDK-8146299, JDK-8145980).
 # @bug 4911536
 # @summary This test verifies that the new implementation of rmic
 # generates equivalent classes as the old implementation, for a set
--- a/jdk/test/sun/security/krb5/auto/BadKdc.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,221 +0,0 @@
-/*
- * Copyright (c) 2009, 2012, 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.io.*;
-import java.net.BindException;
-import java.net.DatagramPacket;
-import java.net.DatagramSocket;
-import java.net.InetAddress;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import javax.security.auth.login.LoginException;
-import sun.security.krb5.Asn1Exception;
-import sun.security.krb5.Config;
-
-public class BadKdc {
-
-    // Matches the krb5 debug output:
-    // >>> KDCCommunication: kdc=kdc.rabbit.hole UDP:14319, timeout=2000,...
-    //                                               ^ kdc#         ^ timeout
-    static final Pattern re = Pattern.compile(
-            ">>> KDCCommunication: kdc=kdc.rabbit.hole UDP:(\\d)...., " +
-            "timeout=(\\d+),");
-
-    // Ratio for timeout values of all timeout tests. Not final so that
-    // each test can choose their own.
-    static float ratio = 2f;
-
-    static void setRatio(float ratio) {
-        BadKdc.ratio = ratio;
-    }
-
-    static float getRatio() {
-        return ratio;
-    }
-
-    // Gets real timeout value. This method is called when writing krb5.conf
-    static int toReal(int from) {
-        return (int)(from * ratio + .5);
-    }
-
-    // De-ratio a millisecond value to second
-    static int toSymbolicSec(int from) {
-        return (int)(from / ratio / 1000f + 0.5);
-    }
-
-    /*
-     * There are several cases this test fails:
-     *
-     * 1. The random selected port is used by another process. No good way to
-     * prevent this happening, coz krb5.conf must be written before KDC starts.
-     * There are two different outcomes:
-     *
-     *  a. Cannot start the KDC. A BindException thrown.
-     *  b. When trying to access a non-existing KDC, a response is received!
-     *     Most likely a Asn1Exception thrown
-     *
-     * 2. Even if a KDC is started, and more than 20 seconds pass by, a timeout
-     * can still happens for the first UDP request. In fact, the KDC did not
-     * received it at all. This happens on almost all platforms, especially
-     * solaris-i586 and solaris-x64.
-     *
-     * To avoid them:
-     *
-     * 1. Catch those exceptions and ignore
-     *
-     * 2. a. Make the timeout longer? useless
-     *    b. Read the output carefully, if there is a timeout, it's OK.
-     *       Just make sure the retries times and KDCs are correct.
-     *       This is tough.
-     *    c. Feed the KDC a UDP packet first. The current "solution".
-     */
-    public static void go(String... expected)
-            throws Exception {
-        try {
-            go0(expected);
-        } catch (BindException be) {
-            System.out.println("The random port is used by another process");
-        } catch (LoginException le) {
-            Throwable cause = le.getCause();
-            if (cause instanceof Asn1Exception) {
-                System.out.println("Bad packet possibly from another process");
-                return;
-            }
-            throw le;
-        }
-    }
-
-    public static void go0(String... expected)
-            throws Exception {
-        System.setProperty("sun.security.krb5.debug", "true");
-
-        // Idle UDP sockets will trigger a SocketTimeoutException, without it,
-        // a PortUnreachableException will be thrown.
-        DatagramSocket d1 = null, d2 = null, d3 = null;
-
-        // Make sure KDCs' ports starts with 1 and 2 and 3,
-        // useful for checking debug output.
-        int p1 = 10000 + new java.util.Random().nextInt(10000);
-        int p2 = 20000 + new java.util.Random().nextInt(10000);
-        int p3 = 30000 + new java.util.Random().nextInt(10000);
-
-        FileWriter fw = new FileWriter("alternative-krb5.conf");
-
-        fw.write("[libdefaults]\n" +
-                "default_realm = " + OneKDC.REALM + "\n" +
-                "kdc_timeout = " + toReal(2000) + "\n");
-        fw.write("[realms]\n" + OneKDC.REALM + " = {\n" +
-                "kdc = " + OneKDC.KDCHOST + ":" + p1 + "\n" +
-                "kdc = " + OneKDC.KDCHOST + ":" + p2 + "\n" +
-                "kdc = " + OneKDC.KDCHOST + ":" + p3 + "\n" +
-                "}\n");
-
-        fw.close();
-        System.setProperty("java.security.krb5.conf", "alternative-krb5.conf");
-        Config.refresh();
-
-        // Turn on k3 only
-        d1 = new DatagramSocket(p1);
-        d2 = new DatagramSocket(p2);
-        KDC k3 = on(p3);
-
-        test(expected[0]);
-        test(expected[1]);
-        Config.refresh();
-        test(expected[2]);
-
-        k3.terminate(); // shutdown k3
-        d3 = new DatagramSocket(p3);
-
-        d2.close();
-        on(p2);         // k2 is on
-
-        test(expected[3]);
-        d1.close();
-        on(p1);         // k1 and k2 is on
-        test(expected[4]);
-
-        d3.close();
-    }
-
-    private static KDC on(int p) throws Exception {
-        KDC k = new KDC(OneKDC.REALM, OneKDC.KDCHOST, p, true);
-        k.addPrincipal(OneKDC.USER, OneKDC.PASS);
-        k.addPrincipalRandKey("krbtgt/" + OneKDC.REALM);
-        // Feed a packet to newly started KDC to warm it up
-        System.err.println("-------- IGNORE THIS ERROR MESSAGE --------");
-        new DatagramSocket().send(
-                new DatagramPacket("Hello".getBytes(), 5,
-                        InetAddress.getByName(OneKDC.KDCHOST), p));
-        return k;
-    }
-
-    private static void test(String expected) throws Exception {
-        ByteArrayOutputStream bo = new ByteArrayOutputStream();
-        System.out.println("----------------- TEST -----------------");
-        try {
-            test0(bo, expected);
-        } catch (Exception e) {
-            System.out.println("----------------- ERROR -----------------");
-            System.out.println(new String(bo.toByteArray()));
-            System.out.println("--------------- ERROR END ---------------");
-            throw e;
-        }
-    }
-
-    /**
-     * One round of test for max_retries and timeout.
-     * @param expected the expected kdc# timeout kdc# timeout...
-     */
-    private static void test0(ByteArrayOutputStream bo, String expected)
-            throws Exception {
-        PrintStream oldout = System.out;
-        boolean failed = false;
-        System.setOut(new PrintStream(bo));
-        try {
-            Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false);
-        } catch (Exception e) {
-            failed = true;
-        } finally {
-            System.setOut(oldout);
-        }
-
-        String[] lines = new String(bo.toByteArray()).split("\n");
-        StringBuilder sb = new StringBuilder();
-        for (String line: lines) {
-            Matcher m = re.matcher(line);
-            if (m.find()) {
-                System.out.println(line);
-                sb.append(m.group(1))
-                        .append(toSymbolicSec(Integer.parseInt(m.group(2))));
-            }
-        }
-        if (failed) sb.append('-');
-
-        String output = sb.toString();
-        System.out.println("Expected: " + expected + ", actual " + output);
-        if (!output.matches(expected)) {
-            throw new Exception("Does not match");
-        }
-    }
-}
--- a/jdk/test/sun/security/krb5/auto/BadKdc1.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,59 +0,0 @@
-/*
- * Copyright (c) 2009, 2012, 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 6843127
- * @run main/othervm/timeout=300 BadKdc1
- * @summary krb5 should not try to access unavailable kdc too often
- */
-
-import java.security.Security;
-
-public class BadKdc1 {
-
-   public static void main(String[] args)
-           throws Exception {
-
-       // 5 sec is default timeout for tryLess
-       if (BadKdc.getRatio() > 2.5) {
-           Security.setProperty("krb5.kdc.bad.policy",
-                   "tryLess:1," + BadKdc.toReal(2000));
-       } else {
-           Security.setProperty("krb5.kdc.bad.policy", "tryLess");
-       }
-
-       BadKdc.go(
-               "121212222222(32){1,3}1222(32){1,3}", // 1 2
-               // The above line means try kdc1 for 2 seconds then kdc1
-               // for 2 seconds... finally kdc3 for 2 seconds.
-               "1222(32){1,3}1222(32){1,3}",    // 1 2
-               // refresh
-               "121212222222(32){1,3}1222(32){1,3}",  // 1 2
-               // k3 off k2 on
-               "(122212(22){1,3}|1222323232-)", // 1
-               // k1 on
-               "(12(12){1,3}|122212|122232-)"  // empty
-       );
-   }
-}
--- a/jdk/test/sun/security/krb5/auto/BadKdc2.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,55 +0,0 @@
-/*
- * Copyright (c) 2009, 2012, 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 6843127
- * @run main/othervm/timeout=300 BadKdc2
- * @summary krb5 should not try to access unavailable kdc too often
- */
-
-import java.io.*;
-import java.security.Security;
-
-public class BadKdc2 {
-
-    public static void main(String[] args)
-            throws Exception {
-
-        // 1 sec is too short.
-        BadKdc.setRatio(3.0f);
-
-        Security.setProperty(
-                "krb5.kdc.bad.policy", "tryLess:2," + BadKdc.toReal(1000));
-        BadKdc.go(
-                "121212222222(32){1,3}11112121(32){1,3}", // 1 2
-                "11112121(32){1,3}11112121(32){1,3}", // 1 2
-                // refresh
-                "121212222222(32){1,3}11112121(32){1,3}", // 1 2
-                // k3 off k2 on
-                "1111(21){1,3}1111(22){1,3}", // 1
-                // k1 on
-                "(11){1,3}(12){1,3}"  // empty
-        );
-    }
-}
--- a/jdk/test/sun/security/krb5/auto/BadKdc3.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2009, 2012, 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 6843127
- * @run main/othervm/timeout=300 BadKdc3
- * @summary krb5 should not try to access unavailable kdc too often
- */
-
-import java.io.*;
-import java.security.Security;
-
-public class BadKdc3 {
-
-    public static void main(String[] args)
-            throws Exception {
-        Security.setProperty("krb5.kdc.bad.policy", "tryLast");
-        BadKdc.go(
-                "121212222222(32){2,4}", // 1 2
-                "(32){2,4}", // 1 2
-                // refresh
-                "121212222222(32){2,4}", // 1 2
-                // k3 off k2 on
-                "323232121212(22){2,4}", // 1 3
-                // k1 on
-                "(22){2,4}"  // 1 3
-        );
-    }
-}
--- a/jdk/test/sun/security/krb5/auto/BadKdc4.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,50 +0,0 @@
-/*
- * Copyright (c) 2009, 2012, 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 6843127
- * @run main/othervm/timeout=300 BadKdc4
- * @summary krb5 should not try to access unavailable kdc too often
- */
-
-import java.io.*;
-import java.security.Security;
-
-public class BadKdc4 {
-
-    public static void main(String[] args)
-            throws Exception {
-        Security.setProperty("krb5.kdc.bad.policy", "");
-        BadKdc.go(
-            "121212222222(32){1,3}121212222222(32){1,3}",
-            "121212222222(32){1,3}121212222222(32){1,3}",
-            // refresh
-            "121212222222(32){1,3}121212222222(32){1,3}",
-            // k3 off k2 on
-            "121212(22){1,3}121212(22){1,3}",
-            // k1 on
-            "(12){2,4}"
-        );
-    }
-}
--- a/jdk/test/sun/security/krb5/auto/CommMatcher.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,86 +0,0 @@
-/*
- * 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.util.ArrayList;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-/**
- * Matches the krb5 debug output:
- * >>> KDCCommunication: kdc=host UDP:11555, timeout=100,Attempt =1, #bytes=138
- *
- * Example:
- *   CommMatcher cm = new CommMatcher();
- *   cm.addPort(12345).addPort(23456);
- *   for (String line : debugOutput) {
- *       if (cm.match(line)) {
- *           println("KDC: %c, %s, Timeout: %d\n",
- *              cm.kdc(), cm.protocol(), cm.timeout());
- *       }
- *   }
- */
-public class CommMatcher {
-
-    static final Pattern re = Pattern.compile(
-            ">>> KDCCommunication: kdc=\\S+ (TCP|UDP):(\\d+), " +
-                    "timeout=(\\d+),Attempt\\s*=(\\d+)");
-
-    List<Integer> kdcPorts = new ArrayList<>();
-    Matcher matcher;
-
-    /**
-     * Add KDC ports one by one. The 1st KDC will be 'a' in {@link #kdc()},
-     * 2nd is 'b', etc, etc.
-     */
-    public CommMatcher addPort(int port) {
-        if (port > 0) {
-            kdcPorts.add(port);
-        } else {
-            kdcPorts.clear();
-        }
-        return this;
-    }
-
-    public boolean match(String line) {
-        matcher = re.matcher(line);
-        return matcher.find();
-    }
-
-    public String protocol() {
-        return matcher.group(1);
-    }
-
-    public char kdc() {
-        int port = Integer.parseInt(matcher.group(2));
-        return (char)(kdcPorts.indexOf(port) + 'a');
-    }
-
-    public int timeout() {
-        return BadKdc.toSymbolicSec(Integer.parseInt(matcher.group(3)));
-    }
-
-    public int attempt() {
-        return Integer.parseInt(matcher.group(4));
-    }
-}
--- a/jdk/test/sun/security/krb5/auto/MaxRetries.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,278 +0,0 @@
-/*
- * Copyright (c) 2010, 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 6844193
- * @compile -XDignore.symbol.file MaxRetries.java
- * @run main/othervm/timeout=300 MaxRetries
- * @summary support max_retries in krb5.conf
- */
-
-import javax.security.auth.login.LoginException;
-import java.io.*;
-import java.net.DatagramSocket;
-import java.security.Security;
-
-public class MaxRetries {
-
-    static int idlePort = -1;
-    static CommMatcher cm = new CommMatcher();
-
-    public static void main(String[] args)
-            throws Exception {
-
-        System.setProperty("sun.security.krb5.debug", "true");
-        OneKDC kdc = new OneKDC(null).writeJAASConf();
-
-        // An idle UDP socket to prevent PortUnreachableException
-        DatagramSocket ds = new DatagramSocket();
-        idlePort = ds.getLocalPort();
-
-        cm.addPort(idlePort);
-        cm.addPort(kdc.getPort());
-
-        System.setProperty("java.security.krb5.conf", "alternative-krb5.conf");
-
-        Security.setProperty("krb5.kdc.bad.policy", "trylast");
-
-        // We always make the real timeout to be 1 second
-        BadKdc.setRatio(0.25f);
-        rewriteMaxRetries(4);
-
-        // Explanation: In this case, max_retries=4 and timeout=4s.
-        // For AS-REQ without preauth, we will see 4 4s timeout on kdc#1
-        // ("a4" repeat 4 times), and one 4s timeout on kdc#2 ("b4"). For
-        // AS-REQ with preauth, one 4s timeout on kdc#2 (second "b4").
-        // we tolerate 4 real timeout on kdc#2, so make it "(b4){2,6}".
-        test1("a4a4a4a4b4b4", "a4a4a4a4(b4){2,6}");
-        test1("b4b4", "(b4){2,6}");
-
-        BadKdc.setRatio(1f);
-        rewriteMaxRetries(1);
-        // Explanation: Since max_retries=1 only, we could fail in 1st or 2nd
-        // AS-REQ to kdc#2.
-        String actual = test1("a1b1b1", "(a1b1b1|a1b1x|a1b1b1x)");
-        if (actual.endsWith("x")) {
-            // If 1st attempt fails, all bads are back available
-            test1("a1b1b1", "(a1b1b1|a1b1x|a1b1b1x)");
-        } else {
-            test1("b1b1", "(b1b1|b1x|b1b1x)");
-        }
-
-        BadKdc.setRatio(0.2f);
-        rewriteMaxRetries(-1);
-        test1("a5a5a5b5b5", "a5a5a5(b5){2,4}");
-        test1("b5b5", "(b5){2,4}");
-
-        BadKdc.setRatio(0.25f);
-        Security.setProperty("krb5.kdc.bad.policy",
-                "tryless:1,1000");
-        rewriteMaxRetries(4);
-        test1("a4a4a4a4b4a4b4", "a4a4a4a4(b4){1,3}a4(b4){1,3}");
-        test1("a4b4a4b4", "a4(b4){1,3}a4(b4){1,3}");
-
-        BadKdc.setRatio(1f);
-        rewriteMaxRetries(1);
-        actual = test1("a1b1a1b1", "(a1b1|a1b1x|a1b1a1b1|a1b1a1b1x)");
-        if (actual.endsWith("x")) {
-            test1("a1b1a1b1", "(a1b1|a1b1x|a1b1a1b1|a1b1a1b1x)");
-        } else {
-            test1("a1b1a1b1", "(a1b1|a1b1x|a1b1a1b1|a1b1a1b1x)");
-        }
-
-        BadKdc.setRatio(.2f);
-        rewriteMaxRetries(-1);
-        test1("a5a5a5b5a5b5", "a5a5a5(b5){1,2}a5(b5){1,2}");
-        test1("a5b5a5b5", "a5(b5){1,2}a5(b5){1,2}");
-
-        BadKdc.setRatio(1f);
-        rewriteMaxRetries(2);
-        if (BadKdc.toReal(2000) > 1000) {
-            // Explanation: if timeout is longer than 1s in tryLess,
-            // we will see "a1" at 2nd kdc#1 access
-            test1("a2a2b2a1b2", "a2a2(b2){1,2}a1(b2){1,2}");
-        } else {
-            test1("a2a2b2a2b2", "a2a2(b2){1,2}a2(b2){1,2}");
-        }
-
-        BadKdc.setRatio(1f);
-
-        rewriteUdpPrefLimit(-1, -1);    // default, no limit
-        test2("UDP");
-
-        rewriteUdpPrefLimit(10, -1);    // global rules
-        test2("TCP");
-
-        rewriteUdpPrefLimit(10, 10000); // realm rules
-        test2("UDP");
-
-        rewriteUdpPrefLimit(10000, 10); // realm rules
-        test2("TCP");
-
-        ds.close();
-    }
-
-    /**
-     * One round of test for max_retries and timeout.
-     *
-     * @param exact the expected exact match, where no timeout
-     *              happens for real KDCs
-     * @param relaxed the expected relaxed match, where some timeout
-     *                could happen for real KDCs
-     * @return the actual result
-     */
-    private static String test1(String exact, String relaxed) throws Exception {
-        ByteArrayOutputStream bo = new ByteArrayOutputStream();
-        PrintStream oldout = System.out;
-        System.setOut(new PrintStream(bo));
-        boolean failed = false;
-        long start = System.nanoTime();
-        try {
-            Context c = Context.fromJAAS("client");
-        } catch (LoginException e) {
-            failed = true;
-        }
-        System.setOut(oldout);
-
-        String[] lines = new String(bo.toByteArray()).split("\n");
-        System.out.println("----------------- TEST (" + exact
-                + ") -----------------");
-
-        // Result, a series of timeout + kdc#
-        StringBuilder sb = new StringBuilder();
-        for (String line: lines) {
-            if (cm.match(line)) {
-                System.out.println(line);
-                sb.append(cm.kdc()).append(cm.timeout());
-            }
-        }
-        if (failed) {
-            sb.append("x");
-        }
-        System.out.println("Time: " + (System.nanoTime() - start) / 1000000000d);
-        String actual = sb.toString();
-        System.out.println("Actual: " + actual);
-        if (actual.equals(exact)) {
-            System.out.println("Exact match: " + exact);
-        } else if (actual.matches(relaxed)) {
-            System.out.println("!!!! Tolerant match: " + relaxed);
-        } else {
-            throw new Exception("Match neither " + exact + " nor " + relaxed);
-        }
-        return actual;
-    }
-
-    /**
-     * One round of test for udp_preference_limit.
-     * @param proto the expected protocol used
-     */
-    private static void test2(String proto) throws Exception {
-        ByteArrayOutputStream bo = new ByteArrayOutputStream();
-        PrintStream oldout = System.out;
-        System.setOut(new PrintStream(bo));
-        Context c = Context.fromJAAS("client");
-        System.setOut(oldout);
-
-        int count = 2;
-        String[] lines = new String(bo.toByteArray()).split("\n");
-        System.out.println("----------------- TEST -----------------");
-        for (String line: lines) {
-            if (cm.match(line)) {
-                System.out.println(line);
-                count--;
-                if (!cm.protocol().equals(proto)) {
-                    throw new Exception("Wrong protocol value");
-                }
-            }
-        }
-        if (count != 0) {
-            throw new Exception("Retry count is " + count + " less");
-        }
-    }
-
-    /**
-     * Set udp_preference_limit for global and realm
-     */
-    private static void rewriteUdpPrefLimit(int global, int realm)
-            throws Exception {
-        BufferedReader fr = new BufferedReader(new FileReader(OneKDC.KRB5_CONF));
-        FileWriter fw = new FileWriter("alternative-krb5.conf");
-        while (true) {
-            String s = fr.readLine();
-            if (s == null) {
-                break;
-            }
-            if (s.startsWith("[realms]")) {
-                // Reconfig global setting
-                fw.write("kdc_timeout = 5000\n");
-                if (global != -1) {
-                    fw.write("udp_preference_limit = " + global + "\n");
-                }
-            } else if (s.trim().startsWith("kdc = ")) {
-                if (realm != -1) {
-                    // Reconfig for realm
-                    fw.write("    udp_preference_limit = " + realm + "\n");
-                }
-            }
-            fw.write(s + "\n");
-        }
-        fr.close();
-        fw.close();
-        sun.security.krb5.Config.refresh();
-    }
-
-    /**
-     * Set max_retries and timeout value for realm. The global value is always
-     * 3 and 5000.
-     *
-     * @param value max_retries and timeout/1000 for a realm, -1 means none.
-     */
-    private static void rewriteMaxRetries(int value) throws Exception {
-        BufferedReader fr = new BufferedReader(new FileReader(OneKDC.KRB5_CONF));
-        FileWriter fw = new FileWriter("alternative-krb5.conf");
-        while (true) {
-            String s = fr.readLine();
-            if (s == null) {
-                break;
-            }
-            if (s.startsWith("[realms]")) {
-                // Reconfig global setting
-                fw.write("max_retries = 3\n");
-                fw.write("kdc_timeout = " + BadKdc.toReal(5000) + "\n");
-            } else if (s.trim().startsWith("kdc = ")) {
-                if (value != -1) {
-                    // Reconfig for realm
-                    fw.write("    max_retries = " + value + "\n");
-                    fw.write("    kdc_timeout = " + BadKdc.toReal(value*1000) + "\n");
-                }
-                // Add a bad KDC as the first candidate
-                fw.write("    kdc = localhost:" + idlePort + "\n");
-            }
-            fw.write(s + "\n");
-        }
-        fr.close();
-        fw.close();
-        sun.security.krb5.Config.refresh();
-    }
-}
--- a/jdk/test/sun/security/krb5/auto/TcpTimeout.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,107 +0,0 @@
-/*
- * Copyright (c) 2010, 2012, 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 6952519
- * @compile -XDignore.symbol.file TcpTimeout.java
- * @run main/othervm TcpTimeout
- * @summary kdc_timeout is not being honoured when using TCP
- */
-
-import java.io.*;
-import java.net.ServerSocket;
-import sun.security.krb5.Config;
-
-public class TcpTimeout {
-    public static void main(String[] args)
-            throws Exception {
-
-        // Set debug to grab debug output like ">>> KDCCommunication"
-        System.setProperty("sun.security.krb5.debug", "true");
-
-        // Called before new ServerSocket on p1 and p2 to make sure
-        // customized nameservice is used
-        KDC k = new KDC(OneKDC.REALM, OneKDC.KDCHOST, 0, true);
-        int p3 = k.getPort();
-        k.addPrincipal(OneKDC.USER, OneKDC.PASS);
-        k.addPrincipalRandKey("krbtgt/" + OneKDC.REALM);
-
-        // Start two listener that does not communicate, simulate timeout
-        ServerSocket ss1 = null;
-        ServerSocket ss2 = null;
-
-        try {
-            ss1 = new ServerSocket(0);
-            ss2 = new ServerSocket(0);
-            int p1 = ss1.getLocalPort();
-            int p2 = ss2.getLocalPort();
-
-            FileWriter fw = new FileWriter("alternative-krb5.conf");
-
-            fw.write("[libdefaults]\n" +
-                    "udp_preference_limit = 1\n" +
-                    "max_retries = 2\n" +
-                    "default_realm = " + OneKDC.REALM + "\n" +
-                    "kdc_timeout = " + BadKdc.toReal(5000) + "\n");
-            fw.write("[realms]\n" + OneKDC.REALM + " = {\n" +
-                    "kdc = " + OneKDC.KDCHOST + ":" + p1 + "\n" +
-                    "kdc = " + OneKDC.KDCHOST + ":" + p2 + "\n" +
-                    "kdc = " + OneKDC.KDCHOST + ":" + p3 + "\n" +
-                    "}\n");
-
-            fw.close();
-            System.setProperty("java.security.krb5.conf",
-                    "alternative-krb5.conf");
-            Config.refresh();
-
-            System.out.println("Ports opened on " + p1 + ", " + p2 + ", " + p3);
-
-            // The correct behavior should be:
-            // 5 sec on p1, 5 sec on p1, fail
-            // 5 sec on p2, 5 sec on p2, fail
-            // p3 ok, p3 ok again for preauth.
-            int count = 6;
-
-            ByteArrayOutputStream bo = new ByteArrayOutputStream();
-            PrintStream oldout = System.out;
-            System.setOut(new PrintStream(bo));
-            Context c = Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false);
-            System.setOut(oldout);
-
-            String[] lines = new String(bo.toByteArray()).split("\n");
-            for (String line: lines) {
-                if (line.startsWith(">>> KDCCommunication")) {
-                    System.out.println(line);
-                    count--;
-                }
-            }
-            if (count != 0) {
-                throw new Exception("Retry count is " + count + " less");
-            }
-        } finally {
-            if (ss1 != null) ss1.close();
-            if (ss2 != null) ss2.close();
-        }
-    }
-}
--- a/jdk/test/sun/security/krb5/auto/UdpTcp.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,71 +0,0 @@
-/*
- * Copyright (c) 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
- * 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 4966382 8039132
- * @run main/othervm UdpTcp UDP
- * @run main/othervm UdpTcp TCP
- * @summary udp or tcp
- */
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-import sun.security.krb5.Config;
-
-public class UdpTcp {
-
-    public static void main(String[] args)
-            throws Exception {
-
-        System.setProperty("sun.security.krb5.debug", "true");
-
-        OneKDC kdc = new OneKDC(null);
-        kdc.writeJAASConf();
-
-        // Two styles of kdc_timeout setting. One global, one realm-specific.
-        if (args[0].equals("UDP")) {
-            KDC.saveConfig(OneKDC.KRB5_CONF, kdc,
-                    "kdc_timeout = 10s");
-        } else {
-            kdc.addConf("kdc_timeout = 10s");
-            KDC.saveConfig(OneKDC.KRB5_CONF, kdc,
-                    "udp_preference_limit = 1");
-        }
-        Config.refresh();
-
-        ByteArrayOutputStream bo = new ByteArrayOutputStream();
-        PrintStream oldout = System.out;
-        System.setOut(new PrintStream(bo));
-        Context.fromUserPass(OneKDC.USER, OneKDC.PASS, false);
-        System.setOut(oldout);
-
-        for (String line: new String(bo.toByteArray()).split("\n")) {
-            if (line.contains(">>> KDCCommunication")) {
-                if (!line.contains(args[0]) || !line.contains("timeout=10000")) {
-                    throw new Exception("No " + args[0] + " in: " + line);
-                }
-            }
-        }
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/ssl/ServerHandshaker/HelloExtensionsTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,287 @@
+/*
+ * Copyright (c) 2017, 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 8173783
+ * @summary 6u141 IllegalArgumentException: jdk.tls.namedGroups
+ * run main/othervm HelloExtensionsTest
+ * run main/othervm HelloExtensionsTest -Djdk.tls.namedGroups="bug, bug"
+ * run main/othervm HelloExtensionsTest -Djdk.tls.namedGroups="secp521r1"
+ *
+ */
+import javax.crypto.*;
+import javax.net.ssl.*;
+import javax.net.ssl.SSLEngineResult.*;
+import java.io.*;
+import java.nio.*;
+import java.security.*;
+
+public class HelloExtensionsTest {
+
+    private static boolean debug = false;
+    private static boolean proceed = true;
+    private static boolean EcAvailable = isEcAvailable();
+
+    static String pathToStores = "../../../../javax/net/ssl/etc";
+    private static String keyStoreFile = "keystore";
+    private static String trustStoreFile = "truststore";
+    private static String passwd = "passphrase";
+
+    private static String keyFilename =
+            System.getProperty("test.src", "./") + "/" + pathToStores +
+                "/" + keyStoreFile;
+    private static String trustFilename =
+            System.getProperty("test.src", "./") + "/" + pathToStores +
+                "/" + trustStoreFile;
+
+    private static void checkDone(SSLEngine ssle) throws Exception {
+        if (!ssle.isInboundDone()) {
+            throw new Exception("isInboundDone isn't done");
+        }
+        if (!ssle.isOutboundDone()) {
+            throw new Exception("isOutboundDone isn't done");
+        }
+    }
+
+    private static void runTest(SSLEngine ssle) throws Exception {
+
+         /*
+
+         A client hello message captured via wireshark by selecting
+         a TLSv1.2 Client Hello record and clicking through to the
+         TLSv1.2 Record Layer line and then selecting the hex stream
+         via "copy -> bytes -> hex stream".
+
+         For Record purposes, here's the ClientHello :
+
+         *** ClientHello, TLSv1.2
+         RandomCookie:  GMT: 1469560450 bytes = { 108, 140, 12, 202,
+         2, 213, 10, 236, 143, 223, 58, 162, 228, 155, 239, 3, 98,
+         232, 89, 41, 116, 120, 13, 37, 105, 153, 97, 241 }
+         Session ID:  {}
+         Cipher Suites: [TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256,
+         TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256, TLS_RSA_WITH_AES_128_CBC_SHA256,
+         TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256,
+         TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256,
+         TLS_DHE_RSA_WITH_AES_128_CBC_SHA256,
+         TLS_DHE_DSS_WITH_AES_128_CBC_SHA256,
+         TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
+         TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
+         TLS_RSA_WITH_AES_128_CBC_SHA,
+         TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA,
+         TLS_ECDH_RSA_WITH_AES_128_CBC_SHA,
+         TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
+         TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
+         TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
+         TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
+         TLS_RSA_WITH_AES_128_GCM_SHA256,
+         TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256,
+         TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256,
+         TLS_DHE_RSA_WITH_AES_128_GCM_SHA256,
+         TLS_DHE_DSS_WITH_AES_128_GCM_SHA256,
+         TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA,
+         TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
+         SSL_RSA_WITH_3DES_EDE_CBC_SHA,
+         TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA,
+         TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA,
+         SSL_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
+         SSL_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
+         TLS_EMPTY_RENEGOTIATION_INFO_SCSV]
+         Compression Methods:  { 0 }
+         Extension elliptic_curves, curve names: {secp256r1,
+         sect163k1, sect163r2, secp192r1, secp224r1, sect233k1, sect233r1,
+         sect283k1, sect283r1, secp384r1, sect409k1, sect409r1, secp521r1,
+         sect571k1, sect571r1, secp160k1, secp160r1, secp160r2, sect163r1,
+         secp192k1, sect193r1, sect193r2, secp224k1, sect239k1, secp256k1}
+         Extension ec_point_formats, formats: [uncompressed]
+         Extension signature_algorithms, signature_algorithms:
+         SHA512withECDSA, SHA512withRSA, SHA384withECDSA, SHA384withRSA,
+         SHA256withECDSA, SHA256withRSA, Unknown (hash:0x3, signature:0x3),
+         Unknown (hash:0x3, signature:0x1), SHA1withECDSA,
+         SHA1withRSA, SHA1withDSA
+         Extension server_name, server_name:
+         [host_name: bugs.openjdk.java.net]
+         */
+
+        String hello = "16030300df010000db03035898b7826c8c0cc" +
+            "a02d50aec8fdf3aa2e49bef0362e8592974780d25699961f" +
+            "100003ac023c027003cc025c02900670040c009c013002fc" +
+            "004c00e00330032c02bc02f009cc02dc031009e00a2c008c" +
+            "012000ac003c00d0016001300ff01000078000a003400320" +
+            "0170001000300130015000600070009000a0018000b000c0" +
+            "019000d000e000f001000110002001200040005001400080" +
+            "016000b00020100000d00180016060306010503050104030" +
+            "401030303010203020102020000001a00180000156275677" +
+            "32e6f70656e6a646b2e6a6176612e6e6574";
+
+        byte[] msg_clihello = hexStringToByteArray(hello);
+        ByteBuffer bf_clihello = ByteBuffer.wrap(msg_clihello);
+
+        SSLSession session = ssle.getSession();
+        int appBufferMax = session.getApplicationBufferSize();
+        int netBufferMax = session.getPacketBufferSize();
+
+        ByteBuffer serverIn = ByteBuffer.allocate(appBufferMax + 50);
+        ByteBuffer serverOut = ByteBuffer.wrap("I'm Server".getBytes());
+        ByteBuffer sTOc = ByteBuffer.allocate(netBufferMax);
+
+        ssle.beginHandshake();
+
+        // unwrap the clientHello message.
+        SSLEngineResult result = ssle.unwrap(bf_clihello, serverIn);
+        System.out.println("server unwrap " + result);
+        runDelegatedTasks(result, ssle);
+
+        if (!proceed) {
+            //expected exception occurred. Don't process anymore
+            return;
+        }
+
+        // one more step, ensure the clientHello message is parsed.
+        SSLEngineResult.HandshakeStatus status = ssle.getHandshakeStatus();
+        if ( status == HandshakeStatus.NEED_UNWRAP) {
+            result = ssle.unwrap(bf_clihello, serverIn);
+            System.out.println("server unwrap " + result);
+            runDelegatedTasks(result, ssle);
+        } else if ( status == HandshakeStatus.NEED_WRAP) {
+            result = ssle.wrap(serverOut, sTOc);
+            System.out.println("server wrap " + result);
+            runDelegatedTasks(result, ssle);
+        } else {
+            throw new Exception("unexpected handshake status " + status);
+        }
+
+        // enough, stop
+    }
+
+    /*
+     * If the result indicates that we have outstanding tasks to do,
+     * go ahead and run them in this thread.
+     */
+    private static void runDelegatedTasks(SSLEngineResult result,
+            SSLEngine engine) throws Exception {
+
+        if (result.getHandshakeStatus() == HandshakeStatus.NEED_TASK) {
+            Runnable runnable;
+            try {
+                while ((runnable = engine.getDelegatedTask()) != null) {
+                    log("\trunning delegated task...");
+                    runnable.run();
+                }
+            } catch (ExceptionInInitializerError e) {
+                String v = System.getProperty("jdk.tls.namedGroups");
+                if (!EcAvailable || v == null) {
+                    // we weren't expecting this if no EC providers
+                    throw new RuntimeException("Unexpected Error :" + e);
+                }
+                if (v != null && v.contains("bug")) {
+                    // OK - we were expecting this Error
+                    log("got expected error for bad jdk.tls.namedGroups");
+                    proceed = false;
+                    return;
+                } else {
+                    System.out.println("Unexpected error. " +
+                        "jdk.tls.namedGroups value: " + v);
+                    throw e;
+                }
+            }
+            HandshakeStatus hsStatus = engine.getHandshakeStatus();
+            if (hsStatus == HandshakeStatus.NEED_TASK) {
+                throw new Exception(
+                    "handshake shouldn't need additional tasks");
+            }
+            log("\tnew HandshakeStatus: " + hsStatus);
+        }
+    }
+
+    private static byte[] hexStringToByteArray(String s) {
+        int len = s.length();
+        byte[] data = new byte[len / 2];
+        for (int i = 0; i < len; i += 2) {
+            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
+                + Character.digit(s.charAt(i+1), 16));
+        }
+        return data;
+    }
+
+    private static boolean isEcAvailable() {
+        try {
+            Signature.getInstance("SHA1withECDSA");
+            Signature.getInstance("NONEwithECDSA");
+            KeyAgreement.getInstance("ECDH");
+            KeyFactory.getInstance("EC");
+            KeyPairGenerator.getInstance("EC");
+            AlgorithmParameters.getInstance("EC");
+        } catch (Exception e) {
+            log("EC not available. Received: " + e);
+            return false;
+        }
+        return true;
+    }
+
+    public static void main(String args[]) throws Exception {
+        SSLEngine ssle = createSSLEngine(keyFilename, trustFilename);
+        runTest(ssle);
+        System.out.println("Test Passed.");
+    }
+
+    /*
+     * Create an initialized SSLContext to use for this test.
+     */
+    static private SSLEngine createSSLEngine(String keyFile, String trustFile)
+            throws Exception {
+
+        SSLEngine ssle;
+
+        KeyStore ks = KeyStore.getInstance("JKS");
+        KeyStore ts = KeyStore.getInstance("JKS");
+
+        char[] passphrase = "passphrase".toCharArray();
+
+        ks.load(new FileInputStream(keyFile), passphrase);
+        ts.load(new FileInputStream(trustFile), passphrase);
+
+        KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
+        kmf.init(ks, passphrase);
+
+        TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
+        tmf.init(ts);
+
+        SSLContext sslCtx = SSLContext.getInstance("TLS");
+
+        sslCtx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
+
+        ssle = sslCtx.createSSLEngine();
+        ssle.setUseClientMode(false);
+
+        return ssle;
+    }
+
+
+    private static void log(String str) {
+        if (debug) {
+            System.out.println(str);
+        }
+    }
+}
--- a/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java	Thu Mar 16 20:47:03 2017 +0000
@@ -456,7 +456,7 @@
                 .shouldMatch("Timestamp signature algorithm: .*key.*weak");
         verify(file, "-J-Djava.security.debug=jar")
                 .shouldHaveExitValue(0)
-                .shouldMatch("SignatureException:.*Disabled");
+                .shouldMatch("SignatureException:.*disabled");
     }
 
     static void checkHalfWeak(String file) throws Throwable {
--- a/jdk/test/sun/security/tools/jarsigner/multiRelease/MVJarSigningTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/sun/security/tools/jarsigner/multiRelease/MVJarSigningTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -74,7 +74,8 @@
     private static final String KEYPASS = "changeit";
     private static final String SIGNED_JAR = "Signed.jar";
     private static final String POLICY_FILE = "SignedJar.policy";
-    private static final String VERSION_MESSAGE = "I am running on version 9";
+    private static final String VERSION = "" + Runtime.version().major();
+    private static final String VERSION_MESSAGE = "I am running on version " + VERSION;
 
     public static void main(String[] args) throws Throwable {
         // compile java files in jarContent directory
--- a/jdk/test/sun/security/util/FilePermCompat/CompatImpact.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/sun/security/util/FilePermCompat/CompatImpact.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,13 +23,14 @@
 
 /*
  * @test
- * @bug 8164705
+ * @bug 8164705 8168410
  * @summary check compatibility after FilePermission change
  * @library /java/security/testlibrary/
  * @modules java.base/jdk.internal.misc
  * @run main CompatImpact prepare
  * @run main CompatImpact builtin
- * @run main CompatImpact mine
+ * @run main/othervm -Djdk.security.filePermCompat=true CompatImpact mine
+ * @run main/fail CompatImpact mine
  * @run main CompatImpact dopriv
  */
 
@@ -72,7 +73,8 @@
                 Files.copy(Paths.get(cp, "CompatImpact$DoPrivInner.class"),
                         Paths.get("inner", "CompatImpact$DoPrivInner.class"));
                 break;
-            // run tests with different policy impls
+            // default policy always covered, user-defined depends on
+            // system property jdk.security.filePermCompact.
             case "builtin":
             case "mine":
                 cp = System.getProperty("test.classes");
@@ -222,7 +224,8 @@
     // Return a Proc object for different policy types
     private static Proc p(String type, String f) throws Exception {
         Proc p = Proc.create("CompatImpact")
-                .prop("java.security.manager", "");
+                .prop("java.security.manager", "")
+                .inheritProp("jdk.security.filePermCompat");
         p.args("test", type);
         switch (type) {
             case "builtin":
--- a/jdk/test/sun/security/util/FilePermCompat/Flag.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/sun/security/util/FilePermCompat/Flag.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,19 +25,16 @@
  * @test
  * @bug 8164705
  * @summary check jdk.filepermission.canonicalize
- * @library /java/security/testlibrary/
- * @modules java.base/jdk.internal.misc
- * @run main/othervm -Djdk.io.permissionsUseCanonicalPath=true Flag truetrue
- * @run main/othervm -Djdk.io.permissionsUseCanonicalPath=false Flag falsetrue
- * @run main/othervm Flag falsetrue
+ * @run main/othervm/policy=flag.policy
+  *     -Djdk.io.permissionsUseCanonicalPath=true Flag true true
+ * @run main/othervm/policy=flag.policy
+  *     -Djdk.io.permissionsUseCanonicalPath=false Flag false true
+ * @run main/othervm/policy=flag.policy Flag false true
  */
 
 import java.io.File;
 import java.io.FilePermission;
 import java.lang.*;
-import java.security.Permission;
-import java.security.Policy;
-import java.security.ProtectionDomain;
 
 public class Flag {
     public static void main(String[] args) throws Exception {
@@ -51,15 +48,6 @@
         FilePermission fp2 = new FilePermission(abs.toString(), "read");
         test1 = fp1.equals(fp2);
 
-        Policy pol = new Policy() {
-            @java.lang.Override
-            public boolean implies(ProtectionDomain domain, Permission permission) {
-                return fp1.implies(permission);
-            }
-        };
-
-        Policy.setPolicy(pol);
-        System.setSecurityManager(new SecurityManager());
         try {
             System.getSecurityManager().checkPermission(fp2);
             test2 = true;
@@ -67,8 +55,9 @@
             test2 = false;
         }
 
-        if (!args[0].equals(test1 + "" + test2)) {
-            throw new Exception("Test failed: " + test1 + test2);
+        if (test1 != Boolean.parseBoolean(args[0]) ||
+                test2 != Boolean.parseBoolean(args[1])) {
+            throw new Exception("Test failed: " + test1 + " " + test2);
         }
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/security/util/FilePermCompat/flag.policy	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,4 @@
+grant {
+    permission java.io.FilePermission "x", "read";
+    permission java.util.PropertyPermission "user.dir", "read";
+};
--- a/jdk/test/sun/text/IntHashtable/Bug4170614Test.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,191 +0,0 @@
-/*
- * 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
- * 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.
- */
-
-/*
-    (this test doesn't have an at-test tag because it's run by a shell
-    script instead of directly by the test harness)
-*/
-
-/*
- *
- *
- * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
- * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
- *
- * Portions copyright (c) 2007 Sun Microsystems, Inc.
- * All Rights Reserved.
- *
- * The original version of this source code and documentation
- * is copyrighted and owned by Taligent, Inc., a wholly-owned
- * subsidiary of IBM. These materials are provided under terms
- * of a License Agreement between Taligent and Sun. This technology
- * is protected by multiple US and International patents.
- *
- * This notice and attribution to Taligent may not be removed.
- * Taligent is a registered trademark of Taligent, Inc.
- *
- * Permission to use, copy, modify, and distribute this software
- * and its documentation for NON-COMMERCIAL purposes and without
- * fee is hereby granted provided that this copyright notice
- * appears in all copies. Please refer to the file "copyright.html"
- * for further important copyright and licensing information.
- *
- * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
- * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
- * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
- * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
- * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
- * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
- *
- */
-package java.text;
-import sun.text.IntHashtable;
-
-
-/**
- * This class tests some internal hashCode() functions.
- * Bug #4170614 complained that we had two iternal classes that
- * break the invariant that if a.equals(b) than a.hashCode() ==
- * b.hashCode().  This is because these classes overrode equals()
- * but not hashCode().  These are both purely internal classes, and
- * the library itself doesn't actually call hashCode(), so this isn't
- * actually causing anyone problems yet.  But if these classes are
- * ever exposed in the API, their hashCode() methods need to work right.
- * PatternEntry will never be exposed in the API, but IntHashtable
- * might be.  This is a shell test to allow us to access classes that
- * are declared package private.
- * @author Richard Gillam
- */
-public class Bug4170614Test {
-    public static void main(String[] args) throws Exception {
-        testIntHashtable();
-        testPatternEntry();
-    }
-
-
-    public static void testIntHashtable() throws Exception {
-        IntHashtable fred = new IntHashtable();
-        fred.put(1, 10);
-        fred.put(2, 20);
-        fred.put(3, 30);
-
-        IntHashtable barney = new IntHashtable();
-        barney.put(1, 10);
-        barney.put(3, 30);
-        barney.put(2, 20);
-
-        IntHashtable homer = new IntHashtable();
-        homer.put(3, 30);
-        homer.put(1, 10);
-        homer.put(7, 900);
-
-        if (fred.equals(barney)) {
-            System.out.println("fred.equals(barney)");
-        }
-        else {
-            System.out.println("!fred.equals(barney)");
-        }
-        System.out.println("fred.hashCode() == " + fred.hashCode());
-        System.out.println("barney.hashCode() == " + barney.hashCode());
-
-        if (!fred.equals(barney)) {
-            throw new Exception("equals() failed on two hashtables that are equal");
-        }
-
-        if (fred.hashCode() != barney.hashCode()) {
-           throw new Exception("hashCode() failed on two hashtables that are equal");
-        }
-
-        System.out.println();
-        if (fred.equals(homer)) {
-            System.out.println("fred.equals(homer)");
-        }
-        else {
-            System.out.println("!fred.equals(homer)");
-        }
-        System.out.println("fred.hashCode() == " + fred.hashCode());
-        System.out.println("homer.hashCode() == " + homer.hashCode());
-
-        if (fred.equals(homer)) {
-            throw new Exception("equals() failed on two hashtables that are not equal");
-        }
-
-        if (fred.hashCode() == homer.hashCode()) {
-            throw new Exception("hashCode() failed on two hashtables that are not equal");
-        }
-
-        System.out.println();
-        System.out.println("testIntHashtable() passed.\n");
-    }
-
-    public static void testPatternEntry() throws Exception {
-        PatternEntry fred = new PatternEntry(1,
-                                             new StringBuffer("hello"),
-                                             new StringBuffer("up"));
-        PatternEntry barney = new PatternEntry(1,
-                                               new StringBuffer("hello"),
-                                               new StringBuffer("down"));
-        // (equals() only considers the "chars" field, so fred and barney are equal)
-        PatternEntry homer = new PatternEntry(1,
-                                              new StringBuffer("goodbye"),
-                                              new StringBuffer("up"));
-
-        if (fred.equals(barney)) {
-            System.out.println("fred.equals(barney)");
-        }
-        else {
-            System.out.println("!fred.equals(barney)");
-        }
-        System.out.println("fred.hashCode() == " + fred.hashCode());
-        System.out.println("barney.hashCode() == " + barney.hashCode());
-
-        if (!fred.equals(barney)) {
-            throw new Exception("equals() failed on two hashtables that are equal");
-        }
-
-        if (fred.hashCode() != barney.hashCode()) {
-           throw new Exception("hashCode() failed on two hashtables that are equal");
-        }
-
-        System.out.println();
-        if (fred.equals(homer)) {
-            System.out.println("fred.equals(homer)");
-        }
-        else {
-            System.out.println("!fred.equals(homer)");
-        }
-        System.out.println("fred.hashCode() == " + fred.hashCode());
-        System.out.println("homer.hashCode() == " + homer.hashCode());
-
-        if (fred.equals(homer)) {
-            throw new Exception("equals() failed on two hashtables that are not equal");
-        }
-
-        if (fred.hashCode() == homer.hashCode()) {
-            throw new Exception("hashCode() failed on two hashtables that are not equal");
-        }
-
-        System.out.println();
-        System.out.println("testPatternEntry() passed.\n");
-    }
-}
--- a/jdk/test/sun/text/IntHashtable/Bug4170614Test.sh	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/sun/text/IntHashtable/Bug4170614Test.sh	Thu Mar 16 20:47:03 2017 +0000
@@ -60,8 +60,8 @@
 TEST_JAVABASE=${TESTCLASSES}/java.base
 mkdir -p ${TEST_JAVABASE}
 ${COMPILEJAVA}/bin/javac ${TESTJAVACOPTS} ${TESTTOOLVMOPTS} \
-    -Xmodule:java.base \
-    -d ${TEST_JAVABASE} Bug4170614Test.java
+    --patch-module java.base=patch-src \
+    -d ${TEST_JAVABASE} patch-src/java/text/Bug4170614Test.java
 
 ${TESTJAVA}/bin/java ${TESTVMOPTS} --patch-module java.base=${TEST_JAVABASE} java.text.Bug4170614Test
 
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/sun/text/IntHashtable/patch-src/java/text/Bug4170614Test.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,191 @@
+/*
+ * 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
+ * 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.
+ */
+
+/*
+    (this test doesn't have an at-test tag because it's run by a shell
+    script instead of directly by the test harness)
+*/
+
+/*
+ *
+ *
+ * (C) Copyright Taligent, Inc. 1996, 1997 - All Rights Reserved
+ * (C) Copyright IBM Corp. 1996 - 1998 - All Rights Reserved
+ *
+ * Portions copyright (c) 2007 Sun Microsystems, Inc.
+ * All Rights Reserved.
+ *
+ * The original version of this source code and documentation
+ * is copyrighted and owned by Taligent, Inc., a wholly-owned
+ * subsidiary of IBM. These materials are provided under terms
+ * of a License Agreement between Taligent and Sun. This technology
+ * is protected by multiple US and International patents.
+ *
+ * This notice and attribution to Taligent may not be removed.
+ * Taligent is a registered trademark of Taligent, Inc.
+ *
+ * Permission to use, copy, modify, and distribute this software
+ * and its documentation for NON-COMMERCIAL purposes and without
+ * fee is hereby granted provided that this copyright notice
+ * appears in all copies. Please refer to the file "copyright.html"
+ * for further important copyright and licensing information.
+ *
+ * SUN MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY OF
+ * THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
+ * TO THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
+ * PARTICULAR PURPOSE, OR NON-INFRINGEMENT. SUN SHALL NOT BE LIABLE FOR
+ * ANY DAMAGES SUFFERED BY LICENSEE AS A RESULT OF USING, MODIFYING OR
+ * DISTRIBUTING THIS SOFTWARE OR ITS DERIVATIVES.
+ *
+ */
+package java.text;
+import sun.text.IntHashtable;
+
+
+/**
+ * This class tests some internal hashCode() functions.
+ * Bug #4170614 complained that we had two iternal classes that
+ * break the invariant that if a.equals(b) than a.hashCode() ==
+ * b.hashCode().  This is because these classes overrode equals()
+ * but not hashCode().  These are both purely internal classes, and
+ * the library itself doesn't actually call hashCode(), so this isn't
+ * actually causing anyone problems yet.  But if these classes are
+ * ever exposed in the API, their hashCode() methods need to work right.
+ * PatternEntry will never be exposed in the API, but IntHashtable
+ * might be.  This is a shell test to allow us to access classes that
+ * are declared package private.
+ * @author Richard Gillam
+ */
+public class Bug4170614Test {
+    public static void main(String[] args) throws Exception {
+        testIntHashtable();
+        testPatternEntry();
+    }
+
+
+    public static void testIntHashtable() throws Exception {
+        IntHashtable fred = new IntHashtable();
+        fred.put(1, 10);
+        fred.put(2, 20);
+        fred.put(3, 30);
+
+        IntHashtable barney = new IntHashtable();
+        barney.put(1, 10);
+        barney.put(3, 30);
+        barney.put(2, 20);
+
+        IntHashtable homer = new IntHashtable();
+        homer.put(3, 30);
+        homer.put(1, 10);
+        homer.put(7, 900);
+
+        if (fred.equals(barney)) {
+            System.out.println("fred.equals(barney)");
+        }
+        else {
+            System.out.println("!fred.equals(barney)");
+        }
+        System.out.println("fred.hashCode() == " + fred.hashCode());
+        System.out.println("barney.hashCode() == " + barney.hashCode());
+
+        if (!fred.equals(barney)) {
+            throw new Exception("equals() failed on two hashtables that are equal");
+        }
+
+        if (fred.hashCode() != barney.hashCode()) {
+           throw new Exception("hashCode() failed on two hashtables that are equal");
+        }
+
+        System.out.println();
+        if (fred.equals(homer)) {
+            System.out.println("fred.equals(homer)");
+        }
+        else {
+            System.out.println("!fred.equals(homer)");
+        }
+        System.out.println("fred.hashCode() == " + fred.hashCode());
+        System.out.println("homer.hashCode() == " + homer.hashCode());
+
+        if (fred.equals(homer)) {
+            throw new Exception("equals() failed on two hashtables that are not equal");
+        }
+
+        if (fred.hashCode() == homer.hashCode()) {
+            throw new Exception("hashCode() failed on two hashtables that are not equal");
+        }
+
+        System.out.println();
+        System.out.println("testIntHashtable() passed.\n");
+    }
+
+    public static void testPatternEntry() throws Exception {
+        PatternEntry fred = new PatternEntry(1,
+                                             new StringBuffer("hello"),
+                                             new StringBuffer("up"));
+        PatternEntry barney = new PatternEntry(1,
+                                               new StringBuffer("hello"),
+                                               new StringBuffer("down"));
+        // (equals() only considers the "chars" field, so fred and barney are equal)
+        PatternEntry homer = new PatternEntry(1,
+                                              new StringBuffer("goodbye"),
+                                              new StringBuffer("up"));
+
+        if (fred.equals(barney)) {
+            System.out.println("fred.equals(barney)");
+        }
+        else {
+            System.out.println("!fred.equals(barney)");
+        }
+        System.out.println("fred.hashCode() == " + fred.hashCode());
+        System.out.println("barney.hashCode() == " + barney.hashCode());
+
+        if (!fred.equals(barney)) {
+            throw new Exception("equals() failed on two hashtables that are equal");
+        }
+
+        if (fred.hashCode() != barney.hashCode()) {
+           throw new Exception("hashCode() failed on two hashtables that are equal");
+        }
+
+        System.out.println();
+        if (fred.equals(homer)) {
+            System.out.println("fred.equals(homer)");
+        }
+        else {
+            System.out.println("!fred.equals(homer)");
+        }
+        System.out.println("fred.hashCode() == " + fred.hashCode());
+        System.out.println("homer.hashCode() == " + homer.hashCode());
+
+        if (fred.equals(homer)) {
+            throw new Exception("equals() failed on two hashtables that are not equal");
+        }
+
+        if (fred.hashCode() == homer.hashCode()) {
+            throw new Exception("hashCode() failed on two hashtables that are not equal");
+        }
+
+        System.out.println();
+        System.out.println("testPatternEntry() passed.\n");
+    }
+}
--- a/jdk/test/tools/jar/mmrjar/Basic.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/jar/mmrjar/Basic.java	Thu Mar 16 20:47:03 2017 +0000
@@ -268,7 +268,7 @@
 
         actual = lines(outbytes);
         expected = Set.of(
-                "hi",
+                "module hi (module-info.class)",
                 "requires mandated java.base",
                 "contains p",
                 "contains p.internal"
@@ -304,7 +304,7 @@
 
         actual = lines(outbytes);
         expected = Set.of(
-                "hi",
+                "module hi (module-info.class)",
                 "requires mandated java.base",
                 "contains p",
                 "contains p.internal",
@@ -331,7 +331,7 @@
         ModuleInfoExtender mie = ModuleInfoExtender.newExtender(
             new ByteArrayInputStream(mdBytes));
 
-        mie.mainClass("foo.main");
+        mie.mainClass("p.Main");
         mie.version(Version.parse("1.0"));
 
         ByteArrayOutputStream baos = new ByteArrayOutputStream();
@@ -345,7 +345,7 @@
 
         // different main-class
         mie = ModuleInfoExtender.newExtender(new ByteArrayInputStream(mdBytes));
-        mie.mainClass("foo.main2");
+        mie.mainClass("p.Main2");
         mie.version(Version.parse("1.0"));
         baos.reset();
         mie.write(baos);
@@ -360,7 +360,7 @@
 
         // different version
         mie = ModuleInfoExtender.newExtender(new ByteArrayInputStream(mdBytes));
-        mie.mainClass("foo.main");
+        mie.mainClass("p.Main");
         mie.version(Version.parse("2.0"));
         baos.reset();
         mie.write(baos);
@@ -395,21 +395,21 @@
         Files.copy(Paths.get("test7-v9", "module-info.class"),
                    Paths.get("test7-v10", "module-info.class"));
 
-        int rc = jar("--create --file mmr.jar --main-class=foo.main -C test7 . --release 9 -C test7-v9 . --release 10 -C test7-v10 .");
-
-System.out.println("-----------------------");
-System.out.println( new String(errbytes.toByteArray()));
-
-
+        int rc = jar("--create --file mmr.jar --main-class=p.Main -C test7 . --release 9 -C test7-v9 . --release 10 -C test7-v10 .");
         Assert.assertEquals(rc, 0);
 
-
-        jar("-tf mmr.jar");
+        jar("-d --file=mmr.jar");
+        System.out.println("-----------------------");
+        System.out.println( new String(outbytes.toByteArray()));
+        Assert.assertEquals(lines(outbytes),
+                            Set.of(
+                           "module m1 (META-INF/versions/9/module-info.class)",
+                           "module m1 (META-INF/versions/10/module-info.class)",
+                           "requires mandated java.base",
+                           "exports p",
+                           "main-class p.Main"));
 
-System.out.println("-----------------------");
-System.out.println( new String(outbytes.toByteArray()));
-
-        Optional<String> exp = Optional.of("foo.main");
+        Optional<String> exp = Optional.of("p.Main");
         try (ZipFile zf = new ZipFile("mmr.jar")) {
             Assert.assertTrue(zf.getEntry("module-info.class") == null);
 
--- a/jdk/test/tools/jar/modularJar/Basic.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/jar/modularJar/Basic.java	Thu Mar 16 20:47:03 2017 +0000
@@ -46,7 +46,7 @@
 
 /*
  * @test
- * @bug 8167328 8171830
+ * @bug 8167328 8171830 8165640 8174248
  * @library /lib/testlibrary
  * @modules jdk.compiler
  *          jdk.jartool
@@ -241,11 +241,6 @@
 
         java(mp, FOO.moduleName + "/" + FOO.mainClass)
             .assertSuccess()
-.resultChecker(r -> {
-        System.out.println("===================================");
-        System.out.println(r.output);
-        System.out.println("===================================");
-})
             .resultChecker(r -> assertModuleData(r, FOO));
         try (InputStream fis = Files.newInputStream(modularJar);
              JarInputStream jis = new JarInputStream(fis)) {
@@ -338,7 +333,7 @@
         // A "bad" main class in first create ( and no version )
         jar("--create",
             "--file=" + modularJar.toString(),
-            "--main-class=" + "IAmNotTheEntryPoint",
+            "--main-class=" + "jdk.test.foo.IAmNotTheEntryPoint",
             "--no-manifest",
             "-C", modClasses.toString(), ".")  // includes module-info.class
            .assertSuccess();
@@ -484,7 +479,7 @@
             .resultChecker(r -> {
                 // Expect similar output: "bar, requires mandated foo, ...
                 // conceals jdk.test.foo, conceals jdk.test.foo.internal"
-                Pattern p = Pattern.compile("\\s+bar\\s+requires\\s++foo");
+                Pattern p = Pattern.compile("module bar \\(module-info.class\\)\\s+requires\\s++foo");
                 assertTrue(p.matcher(r.output).find(),
                            "Expecting to find \"bar, requires foo,...\"",
                            "in output, but did not: [" + r.output + "]");
@@ -740,6 +735,53 @@
     }
 
     @Test
+    public void servicesCreateWithoutFailureNonRootMRMJAR() throws IOException {
+        // without a root module-info.class
+        Path mp = Paths.get("servicesCreateWithoutFailureNonRootMRMJAR");
+        createTestDir(mp);
+        Path modClasses = MODULE_CLASSES.resolve("baz");
+        Path mrjarDir = MRJAR_DIR.resolve("baz");
+        Path modularJar = mp.resolve("baz.jar");
+
+        jar("--create",
+            "--file=" + modularJar.toString(),
+            "--main-class=" + "jdk.test.baz.Baz",
+            "-m", mrjarDir.resolve("META-INF/MANIFEST.MF").toRealPath().toString(),
+            "-C", mrjarDir.toString(), "META-INF/versions/9/module-info.class",
+            "-C", modClasses.toString(), "jdk/test/baz/BazService.class",
+            "-C", modClasses.toString(), "jdk/test/baz/Baz.class",
+            "-C", modClasses.toString(), "jdk/test/baz/internal/BazServiceImpl.class")
+            .assertSuccess();
+
+
+        for (String option : new String[]  {"--print-module-descriptor", "-d" }) {
+
+            jar(option,
+                "--file=" + modularJar.toString())
+                .assertSuccess()
+                .resultChecker(r ->
+                    assertTrue(r.output.contains("main-class jdk.test.baz.Baz"),
+                              "Expected to find ", "main-class jdk.test.baz.Baz",
+                               " in [", r.output, "]"));
+
+            jarWithStdin(modularJar.toFile(),  option)
+                .assertSuccess()
+                .resultChecker(r ->
+                    assertTrue(r.output.contains("main-class jdk.test.baz.Baz"),
+                              "Expected to find ", "main-class jdk.test.baz.Baz",
+                               " in [", r.output, "]"));
+
+        }
+        // run module maain class
+        java(mp, "baz/jdk.test.baz.Baz")
+            .assertSuccess()
+            .resultChecker(r ->
+               assertTrue(r.output.contains("mainClass:jdk.test.baz.Baz"),
+                          "Expected to find ", "mainClass:jdk.test.baz.Baz",
+                          " in [", r.output, "]"));
+    }
+
+    @Test
     public void exportCreateWithMissingPkg() throws IOException {
 
         Path foobar = TEST_SRC.resolve("src").resolve("foobar");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/tools/jar/modularJar/src/baz/jdk/test/baz/Baz.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,34 @@
+/*
+ * Copyright (c) 2017, 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 jdk.test.baz;
+
+import java.lang.module.ModuleDescriptor;
+
+public class Baz {
+    public static void main(String[] args) {
+        ModuleDescriptor md = Baz.class.getModule().getDescriptor();
+        System.out.println("nameAndVersion:" + md.toNameAndVersion());
+        md.mainClass().ifPresent(mc -> System.out.println("mainClass:" + mc));
+    }
+}
--- a/jdk/test/tools/jlink/IntegrationTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/jlink/IntegrationTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -145,7 +145,7 @@
             throw new Exception("Plugin should be null");
         }
 
-        Plugin p2 = Jlink.newPlugin("compress", Collections.emptyMap(), null);
+        Plugin p2 = Jlink.newPlugin("compress", Map.of("compress", "1"), null);
         if (p2 == null) {
             throw new Exception("Plugin should not be null");
         }
--- a/jdk/test/tools/jlink/JLinkNegativeTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/jlink/JLinkNegativeTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,7 @@
  * @test
  * @summary Negative tests for jlink
  * @bug 8130861
+ * @bug 8174718
  * @author Andrei Eremeev
  * @library ../lib
  * @modules java.base/jdk.internal.jimage
@@ -50,6 +51,7 @@
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
+import java.util.Set;
 
 import jdk.internal.module.ModuleInfoWriter;
 import org.testng.SkipException;
@@ -250,7 +252,7 @@
         String moduleName = "hacked4";
         Path jmod = helper.generateDefaultJModule(moduleName).assertSuccess();
         JImageGenerator.addFiles(jmod,
-                new InMemoryFile("/native", new byte[0]),
+                new InMemoryFile("/lib", new byte[0]),
                 new InMemoryFile("/conf", new byte[0]),
                 new InMemoryFile("/bin", new byte[0]));
         try {
@@ -274,7 +276,7 @@
                 helper.getJmodSrcDir(), helper.getJmodClassesDir(), moduleName2, classNames);
 
         try (OutputStream out = Files.newOutputStream(module2.resolve("module-info.class"))) {
-            ModuleInfoWriter.write(ModuleDescriptor.module(moduleName1)
+            ModuleInfoWriter.write(ModuleDescriptor.newModule(moduleName1)
                     .requires("java.base").build(), out);
         }
 
@@ -332,7 +334,7 @@
                 helper.getJarSrcDir(), helper.getJarClassesDir(), moduleName2, classNames);
 
         try (OutputStream out = Files.newOutputStream(module2.resolve("module-info.class"))) {
-            ModuleInfoWriter.write(ModuleDescriptor.module(moduleName1)
+            ModuleInfoWriter.write(ModuleDescriptor.newModule(moduleName1)
                     .requires("java.base").build(), out);
         }
 
@@ -346,4 +348,27 @@
             deleteDirectory(jar2);
         }
     }
+
+    public void testInconsistentModuleInfo() throws IOException {
+        String moduleName = "inconsistentJar";
+        List<String> classNames = Arrays.asList("xorg.acme.internal.B");
+        Path module = helper.generateModuleCompiledClasses(
+                helper.getJarSrcDir(), helper.getJarClassesDir(), moduleName, classNames);
+
+        try (OutputStream out = Files.newOutputStream(module.resolve("module-info.class"))) {
+            ModuleInfoWriter.write(ModuleDescriptor.newModule(moduleName)
+                    .requires("java.base")
+                    .packages(Set.of("org.acme.internal"))
+                    .build(), out);
+        }
+
+        Path jar = JImageGenerator.createJarFile(helper.getJarDir().resolve(moduleName + ".jar"), module);
+        try {
+            helper.generateDefaultImage(moduleName)
+                  .assertFailure("Module inconsistentJar's descriptor indicates the set of packages is : " +
+                  "[org.acme.internal], but module contains packages: [xorg.acme.internal]");
+        } finally {
+            deleteDirectory(jar);
+        }
+    }
 }
--- a/jdk/test/tools/jlink/plugins/CompressorPluginTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/jlink/plugins/CompressorPluginTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -93,80 +93,53 @@
                 new ResourceDecompressorFactory[]{
                     new StringSharingDecompressorFactory()});
 
-        // compress == ZIP + String sharing
-        Properties options = new Properties();
-        options.setProperty(ZipPlugin.NAME, "");
-        checkCompress(classes, new DefaultCompressPlugin(), options,
+        // compress level 0 == no compression
+        Properties options0 = new Properties();
+        options0.setProperty(DefaultCompressPlugin.NAME,
+                "0");
+        checkCompress(classes, new DefaultCompressPlugin(),
+                options0,
                 new ResourceDecompressorFactory[]{
-                    new ZipDecompressorFactory(),
+                });
+
+        // compress level 1 == String sharing
+        Properties options1 = new Properties();
+        options1.setProperty(DefaultCompressPlugin.NAME, "1");
+        checkCompress(classes, new DefaultCompressPlugin(),
+                options1,
+                new ResourceDecompressorFactory[]{
                     new StringSharingDecompressorFactory()
                 });
 
-        // compress == ZIP + String sharing + filter
-        options.setProperty(DefaultCompressPlugin.FILTER,
+        // compress level 1 == String sharing + filter
+        options1.setProperty(DefaultCompressPlugin.FILTER,
                 "**Exception.class");
-        checkCompress(classes, new DefaultCompressPlugin(), options,
+        options1.setProperty(DefaultCompressPlugin.NAME, "1");
+        checkCompress(classes, new DefaultCompressPlugin(),
+                options1,
                 new ResourceDecompressorFactory[]{
-                    new ZipDecompressorFactory(),
                     new StringSharingDecompressorFactory()
                 }, Collections.singletonList(".*Exception.class"));
 
-        // compress level 1 == ZIP
-        Properties options1 = new Properties();
-        options1.setProperty(DefaultCompressPlugin.NAME,
-                "1");
+        // compress level 2 == ZIP
+        Properties options2 = new Properties();
+        options2.setProperty(DefaultCompressPlugin.FILTER,
+                "**Exception.class");
+        options2.setProperty(DefaultCompressPlugin.NAME, "2");
         checkCompress(classes, new DefaultCompressPlugin(),
-                options1,
-                new ResourceDecompressorFactory[]{
-                    new ZipDecompressorFactory()
-                });
-
-        // compress level 1 == ZIP
-        options1.setProperty(DefaultCompressPlugin.FILTER,
-                "**Exception.class");
-        checkCompress(classes, new DefaultCompressPlugin(),
-                options1,
+                options2,
                 new ResourceDecompressorFactory[]{
                     new ZipDecompressorFactory()
                 }, Collections.singletonList(".*Exception.class"));
 
-        // compress level 2 == ZIP + String sharing
-        Properties options2 = new Properties();
-        options2.setProperty(DefaultCompressPlugin.NAME,
-                "2");
-        checkCompress(classes, new DefaultCompressPlugin(),
-                options2,
-                new ResourceDecompressorFactory[]{
-                    new ZipDecompressorFactory(),
-                    new StringSharingDecompressorFactory()
-                });
-
-        // compress level 2 == ZIP + String sharing + filter
+        // compress level 2 == ZIP + filter
         options2.setProperty(DefaultCompressPlugin.FILTER,
                 "**Exception.class");
+        options2.setProperty(DefaultCompressPlugin.NAME, "2");
         checkCompress(classes, new DefaultCompressPlugin(),
                 options2,
                 new ResourceDecompressorFactory[]{
                     new ZipDecompressorFactory(),
-                    new StringSharingDecompressorFactory()
-                }, Collections.singletonList(".*Exception.class"));
-
-        // compress level 0 == String sharing
-        Properties options0 = new Properties();
-        options0.setProperty(DefaultCompressPlugin.NAME, "0");
-        checkCompress(classes, new DefaultCompressPlugin(),
-                options0,
-                new ResourceDecompressorFactory[]{
-                    new StringSharingDecompressorFactory()
-                });
-
-        // compress level 0 == String sharing + filter
-        options0.setProperty(DefaultCompressPlugin.FILTER,
-                "**Exception.class");
-        checkCompress(classes, new DefaultCompressPlugin(),
-                options0,
-                new ResourceDecompressorFactory[]{
-                    new StringSharingDecompressorFactory()
                 }, Collections.singletonList(".*Exception.class"));
     }
 
@@ -234,6 +207,11 @@
             Properties config,
             ResourceDecompressorFactory[] factories,
             List<String> includes) throws Exception {
+        if (factories.length == 0) {
+            // no compression, nothing to check!
+            return;
+        }
+
         long[] original = new long[1];
         long[] compressed = new long[1];
         resources.entries().forEach(resource -> {
--- a/jdk/test/tools/jlink/plugins/ExcludeVMPluginTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/jlink/plugins/ExcludeVMPluginTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -155,10 +155,10 @@
             String[] winput = new String[input.length];
             String[] woutput = new String[expectedOutput.length];
             for (int i = 0; i < input.length; i++) {
-                winput[i] = "/java.base/native" + arch + input[i];
+                winput[i] = "/java.base/lib" + arch + input[i];
             }
             for (int i = 0; i < expectedOutput.length; i++) {
-                woutput[i] = "/java.base/native" + arch + expectedOutput[i];
+                woutput[i] = "/java.base/lib" + arch + expectedOutput[i];
             }
             doCheckVM(vm, winput, jvmcfg, woutput, expectdJvmCfg);
         }
@@ -169,7 +169,7 @@
         byte[] jvmcfgContent = jvmcfg.getBytes();
         ResourcePoolManager poolMgr = new ResourcePoolManager();
         poolMgr.add(
-            ResourcePoolEntry.create("/java.base/native/jvm.cfg",
+            ResourcePoolEntry.create("/java.base/lib/jvm.cfg",
                 ResourcePoolEntry.Type.NATIVE_LIB, jvmcfgContent));
 
         // java.base/module-info.class is used by exclude vm plugin
@@ -192,7 +192,7 @@
         p.configure(config);
         ResourcePool out = p.transform(poolMgr.resourcePool(), outMgr.resourcePoolBuilder());
 
-        String newContent = new String(out.findEntry("/java.base/native/jvm.cfg").get().contentBytes());
+        String newContent = new String(out.findEntry("/java.base/lib/jvm.cfg").get().contentBytes());
 
         if (!expectdJvmCfg.equals(newContent)) {
             throw new Exception("Got content " + newContent + " expected " + expectdJvmCfg);
@@ -209,7 +209,7 @@
         }
 
         out.entries().forEach(md -> {
-            if (md.path().equals("/java.base/native/jvm.cfg") ||
+            if (md.path().equals("/java.base/lib/jvm.cfg") ||
                 md.path().equals("/java.base/module-info.class")) {
                 return;
             }
--- a/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/UserModuleTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/UserModuleTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -45,7 +45,7 @@
 
 /**
  * @test
- * @bug 8142968 8173381
+ * @bug 8142968 8173381 8174740
  * @library /lib/testlibrary
  * @modules jdk.compiler jdk.jlink
  * @build UserModuleTest CompilerUtils jdk.testlibrary.FileUtils jdk.testlibrary.ProcessTools
--- a/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/src/m1/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/jlink/plugins/SystemModuleDescriptors/src/m1/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -21,5 +21,9 @@
  * questions.
  */
 
+/*
+ * m1 has an exported package and also internal package
+ */
 module m1 {
+    exports p1;
 }
--- a/jdk/test/tools/jmod/JmodTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/jmod/JmodTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -66,7 +66,7 @@
 
     static final String CLASSES_PREFIX = "classes/";
     static final String CMDS_PREFIX = "bin/";
-    static final String LIBS_PREFIX = "native/";
+    static final String LIBS_PREFIX = "lib/";
     static final String CONFIGS_PREFIX = "conf/";
 
     @BeforeTest
--- a/jdk/test/tools/jmod/hashes/HashesTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/jmod/hashes/HashesTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -312,9 +312,7 @@
         assertTrue(ht.hashes("m2") == null);
 
         // should not override any JDK packaged modules
-        ModuleFinder finder = new ModulePath(Runtime.version(),
-                                             true,
-                                             mpath);
+        ModuleFinder finder = ModulePath.of(Runtime.version(), true, mpath);
         assertTrue(ht.hashes(finder,"jdk.compiler") == null);
         assertTrue(ht.hashes(finder,"jdk.attach") == null);
     }
@@ -325,9 +323,7 @@
     }
 
     private ModuleHashes hashes(String name) {
-        ModuleFinder finder = new ModulePath(Runtime.version(),
-                                             true,
-                                             lib);
+        ModuleFinder finder = ModulePath.of(Runtime.version(), true, lib);
         return hashes(finder, name);
     }
 
--- a/jdk/test/tools/launcher/ArgsEnvVar.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/launcher/ArgsEnvVar.java	Thu Mar 16 20:47:03 2017 +0000
@@ -40,7 +40,7 @@
     private static File testJar = null;
     private static Map<String, String> env = new HashMap<>();
 
-    private static String JAVA_OPTIONS = "JAVA_OPTIONS";
+    private static String JDK_JAVA_OPTIONS = "JDK_JAVA_OPTIONS";
 
     static void init() throws IOException {
         if  (testJar != null) {
@@ -105,7 +105,7 @@
         File argFile2 = createArgFile("argFile2", List.of("-Darg.file2=TWO"));
         File argFile3 = createArgFile("argFile3", List.of("-Darg.file3=THREE"));
 
-        env.put(JAVA_OPTIONS, "@argFile1\n-Xint\r-cp @@escaped\t@argFile2");
+        env.put(JDK_JAVA_OPTIONS, "@argFile1\n-Xint\r-cp @@escaped\t@argFile2");
 
         TestResult tr = doExec(env, javaCmd, "@argFile3", "-cp", "test.jar", "Foo", "uarg1", "@uarg2");
 
@@ -133,13 +133,13 @@
     }
 
     private TestResult testInEnv(List<String> options) {
-        env.put(JAVA_OPTIONS, String.join(" ", options));
+        env.put(JDK_JAVA_OPTIONS, String.join(" ", options));
         return doExec(env, javaCmd, "-jar", "test.jar");
     }
 
     private TestResult testInEnvAsArgFile(List<String> options) throws IOException {
         File argFile = createArgFile("argFile", options);
-        env.put(JAVA_OPTIONS, "@argFile");
+        env.put(JDK_JAVA_OPTIONS, "@argFile");
         TestResult tr = doExec(env, javaCmd, "-jar", "test.jar");
         argFile.delete();
         return tr;
@@ -187,7 +187,7 @@
         File argFile1 = createArgFile("arg File 1", List.of("-Xint"));
         File argFile2 = createArgFile("arg File 2", List.of("-Dprop='value with spaces'"));
         File argFile3 = createArgFile("arg File 3", List.of("-Xmx32m"));
-        env.put(JAVA_OPTIONS, "'@arg File 1' @\"arg File 2\" @'arg File'\" 3\"");
+        env.put(JDK_JAVA_OPTIONS, "'@arg File 1' @\"arg File 2\" @'arg File'\" 3\"");
 
         TestResult tr = doExec(env, javaCmd, "-jar", "test.jar");
         List<String> options = new ArrayList<>();
@@ -204,7 +204,7 @@
 
     @Test
     public void openQuoteShouldFail() {
-        env.put(JAVA_OPTIONS, "-Dprop='value missing close quote");
+        env.put(JDK_JAVA_OPTIONS, "-Dprop='value missing close quote");
         TestResult tr = doExec(env, javaCmd, "-version");
         tr.checkNegative();
         if (!tr.testStatus) {
@@ -215,11 +215,11 @@
 
     @Test
     public void noWildcard() {
-        env.put(JAVA_OPTIONS, "-cp *");
+        env.put(JDK_JAVA_OPTIONS, "-cp *");
         TestResult tr = doExec(env, javaCmd, "-jar", "test.jar");
         verifyOptions(List.of("-cp", "*", "-jar", "test.jar"), tr);
 
-        env.put(JAVA_OPTIONS, "-p ?");
+        env.put(JDK_JAVA_OPTIONS, "-p ?");
         tr = doExec(env, javaCmd, "-jar", "test.jar", "one", "two");
         verifyOptions(List.of("-p", "?", "-jar", "test.jar", "one", "two"), tr);
     }
--- a/jdk/test/tools/launcher/I18NArgTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/launcher/I18NArgTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -95,21 +95,19 @@
             throw new RuntimeException("test fails");
         }
 
-        // Test via JAVA_OPTIONS
-/*
+        // Test via JDK_JAVA_OPTIONS
         Map<String, String> env = new HashMap<>();
         String cmd = "-Dtest.src=" + TEST_SOURCES_DIR.getAbsolutePath() +
                 " -Dtest.classes=" + TEST_CLASSES_DIR.getAbsolutePath() +
                 " -cp " + TEST_CLASSES_DIR.getAbsolutePath() +
                 " I18NArgTest " + unicodeStr + " " + hexValue;
-        env.put("JAVA_OPTIONS", cmd);
+        env.put("JDK_JAVA_OPTIONS", cmd);
         tr = doExec(env, javaCmd);
         System.out.println(tr.testOutput);
         if (!tr.isOK()) {
             System.err.println(tr);
             throw new RuntimeException("test fails");
         }
-*/
     }
 
     static void testCharacters(String... args) {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/jdk/test/tools/launcher/MainClassCantBeLoadedTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,98 @@
+/*
+ * Copyright (c) 2017, 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 8174694
+ * @summary improve error message shown when main class can't be loaded
+ * @compile MainClassCantBeLoadedTest.java
+ * @run main MainClassCantBeLoadedTest
+ */
+
+import java.io.*;
+import java.util.*;
+
+public class MainClassCantBeLoadedTest extends TestHelper {
+    private MainClassCantBeLoadedTest(){}
+
+    @Test
+    void testLoadingClassWithMissingSuper() throws Exception {
+        if (!isEnglishLocale()) {
+            return;
+        }
+
+        File cwd = new File(".");
+        File srcDir = new File(cwd, "src");
+        if (srcDir.exists()) {
+            recursiveDelete(srcDir);
+        }
+        srcDir.mkdirs();
+
+        /* we want to generate two classes A and B, where B is the superclass of A
+         * class A has a main method
+         */
+        ArrayList<String> scratchpad = new ArrayList<>();
+        scratchpad.add("public class A extends B {");
+        scratchpad.add("    public static void main(String... args) {}");
+        scratchpad.add("}");
+        createFile(new File(srcDir, "A.java"), scratchpad);
+
+        scratchpad.clear();
+        scratchpad.add("class B {}");
+        createFile(new File(srcDir, "B.java"), scratchpad);
+
+        // let's compile both
+        TestResult trCompilation = doExec(javacCmd,
+                "-d", "out",
+                new File(srcDir, "A.java").toString(),
+                new File(srcDir, "B.java").toString());
+        if (!trCompilation.isOK()) {
+            System.err.println(trCompilation);
+            throw new RuntimeException("Error: compiling");
+        }
+
+        // and now B is removed
+        File outDir = new File(cwd, "out");
+        File bClass = new File(outDir, "B.class");
+        bClass.delete();
+
+        // if A is executed
+        TestResult trExecution = doExec(javaCmd, "-cp", "out", "A");
+        // then this error message should be generated
+        trExecution.contains("Error: Could not find or load main class A");
+        trExecution.contains("Caused by: java.lang.NoClassDefFoundError: B");
+        if (!trExecution.testStatus)
+            System.err.println(trExecution);
+    }
+
+    public static void main(String[] args) throws Exception {
+        MainClassCantBeLoadedTest a = new MainClassCantBeLoadedTest();
+        a.run(args);
+        if (testExitValue > 0) {
+            System.out.println("Total of " + testExitValue + " failed");
+            throw new RuntimeException("Test failed");
+        } else {
+            System.out.println("Test passed");
+        }
+    }
+}
--- a/jdk/test/tools/launcher/ToolsOpts.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/launcher/ToolsOpts.java	Thu Mar 16 20:47:03 2017 +0000
@@ -87,11 +87,16 @@
         contents.add("       }\n");
         contents.add("    }\n");
         contents.add("}\n");
-        createFile(new File(mainJava), contents);
+        String mainJavaPath = "patch-src/com/sun/tools/javac/" + mainJava;
+        File mainJavaFile = new File(mainJavaPath.replace('/', File.separatorChar));
+        mainJavaFile.getParentFile().mkdirs();
+        createFile(mainJavaFile, contents);
 
         // compile Main.java into directory to override classes in jdk.compiler
         new File("jdk.compiler").mkdir();
-        compile("-Xmodule:jdk.compiler", "-d", "jdk.compiler", mainJava);
+        compile("--patch-module", "jdk.compiler=patch-src",
+                "-d", "jdk.compiler",
+                mainJavaFile.toString());
     }
 
     static void pass(String msg) {
--- a/jdk/test/tools/launcher/modules/patch/basic/PatchTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/launcher/modules/patch/basic/PatchTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -105,22 +105,24 @@
                                                 MODS_DIR.resolve("test"));
         assertTrue(compiled, "classes did not compile");
 
-        // javac -Xmodule:$MODULE -d patches1/$MODULE patches1/$MODULE/**
+        // javac --patch-module $MODULE=patches1/$MODULE -d patches1/$MODULE patches1/$MODULE/**
         // jar cf patches/$MODULE-1.jar -C patches1/$MODULE .
         for (Path src : Files.newDirectoryStream(SRC1_DIR)) {
             Path output = PATCHES1_DIR.resolve(src.getFileName());
             String mn = src.getFileName().toString();
-            compiled  = CompilerUtils.compile(src, output, "-Xmodule:" + mn);
+            compiled  = CompilerUtils.compile(src, output,
+                                              "--patch-module", mn + "=" + src.toString());
             assertTrue(compiled, "classes did not compile");
             JarUtils.createJarFile(PATCHES_DIR.resolve(mn + "-1.jar"), output);
         }
 
-        // javac -Xmodule:$MODULE -d patches2/$MODULE patches2/$MODULE/**
+        // javac --patch-module $MODULE=patches2/$MODULE -d patches2/$MODULE patches2/$MODULE/**
         // jar cf patches/$MODULE-2.jar -C patches2/$MODULE .
         for (Path src : Files.newDirectoryStream(SRC2_DIR)) {
             Path output = PATCHES2_DIR.resolve(src.getFileName());
             String mn = src.getFileName().toString();
-            compiled  = CompilerUtils.compile(src, output, "-Xmodule:" + mn);
+            compiled  = CompilerUtils.compile(src, output,
+                                              "--patch-module", mn + "=" + src.toString());
             assertTrue(compiled, "classes did not compile");
             JarUtils.createJarFile(PATCHES_DIR.resolve(mn + "-2.jar"), output);
         }
--- a/jdk/test/tools/launcher/modules/patch/basic/PatchTestWarningError.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/launcher/modules/patch/basic/PatchTestWarningError.java	Thu Mar 16 20:47:03 2017 +0000
@@ -93,20 +93,22 @@
                                                 MODS_DIR.resolve("test"));
         assertTrue(compiled, "classes did not compile");
 
-        // javac -Xmodule:$MODULE -d patches1/$MODULE patches1/$MODULE/**
+        // javac --patch-module $MODULE=patches1/$MODULE -d patches1/$MODULE patches1/$MODULE/**
         Path src = SRC1_DIR.resolve("java.base");
         Path output = PATCHES1_DIR.resolve(src.getFileName());
         Files.createDirectories(output);
         String mn = src.getFileName().toString();
-        compiled  = CompilerUtils.compile(src, output, "-Xmodule:" + mn);
+        compiled  = CompilerUtils.compile(src, output,
+                                          "--patch-module", mn + "=" + src.toString());
         assertTrue(compiled, "classes did not compile");
 
-        // javac -Xmodule:$MODULE -d patches2/$MODULE patches2/$MODULE/**
+        // javac --patch-module $MODULE=patches2/$MODULE -d patches2/$MODULE patches2/$MODULE/**
         src = SRC2_DIR.resolve("java.base");
         output = PATCHES2_DIR.resolve(src.getFileName());
         Files.createDirectories(output);
         mn = src.getFileName().toString();
-        compiled  = CompilerUtils.compile(src, output, "-Xmodule:" + mn);
+        compiled  = CompilerUtils.compile(src, output,
+                                          "--patch-module", mn + "=" + src.toString());
         assertTrue(compiled, "classes did not compile");
 
     }
--- a/jdk/test/tools/launcher/modules/patch/systemmodules/PatchSystemModules.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/launcher/modules/patch/systemmodules/PatchSystemModules.java	Thu Mar 16 20:47:03 2017 +0000
@@ -73,9 +73,10 @@
         }
 
         // compile patched source
+        String patchDir = PATCH_SRC_DIR.resolve(JAVA_BASE).toString();
         assertTrue(CompilerUtils.compile(PATCH_SRC_DIR.resolve(JAVA_BASE),
                                          PATCH_DIR.resolve(JAVA_BASE),
-                                         "-Xmodule:java.base"));
+                                         "--patch-module", "java.base=" + patchDir));
         assertTrue(CompilerUtils.compile(PATCH_SRC_DIR.resolve("m2"),
                                          PATCH_DIR.resolve("m2")));
 
--- a/jdk/test/tools/launcher/modules/patch/systemmodules/src1/java.base/jdk/internal/modules/SystemModules.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/jdk/test/tools/launcher/modules/patch/systemmodules/src1/java.base/jdk/internal/modules/SystemModules.java	Thu Mar 16 20:47:03 2017 +0000
@@ -30,6 +30,8 @@
 public final class SystemModules {
     public static final String[] MODULE_NAMES = new String[0];
 
+    public static int PACKAGES_IN_BOOT_LAYER = 1024;
+
     public static boolean hasSplitPackages() {
         return true;
     }
--- a/langtools/.hgtags	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/.hgtags	Thu Mar 16 20:47:03 2017 +0000
@@ -396,5 +396,9 @@
 4f348bd05341581df84ff1510d5b3a9b5b488367 jdk-9+151
 5b6f12de6f9167a582fa2c6ac54e69c591b09e68 jdk-9+152
 03f48cd283f5dd6b7153fd7e0cf2df8582b14391 jdk-9+153
+b670e95106f5327a29e2e2c4f18ee48a8d36e481 jdk-10+0
 6a9dd3d893b0a493a3e5d8d392815b5ee76a02d9 jdk-9+154
 dfcfdb2db85f1bb434209f56ca557ea6f9830aa8 jdk-9+155
+6f91e41163bc09e9b3ec72e8d1185f39296ee5d4 jdk-9+156
+162b521af7bb097019a8afaa44e1f8069ce274eb jdk-9+157
+4eb737a8d439f49a197e8000de26c6580cb4d57b jdk-9+158
--- a/langtools/.jcheck/conf	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/.jcheck/conf	Thu Mar 16 20:47:03 2017 +0000
@@ -1,1 +1,1 @@
-project=jdk9
+project=jdk10
--- a/langtools/make/tools/crules/MutableFieldsAnalyzer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/make/tools/crules/MutableFieldsAnalyzer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -102,7 +102,7 @@
         ignoreFields("com.sun.tools.javac.util.JDK9Wrappers$ModuleFinder",
                 "moduleFinderClass", "ofMethod");
         ignoreFields("com.sun.tools.javac.util.JDK9Wrappers$Configuration",
-                "configurationClass", "resolveRequiresAndUsesMethod");
+                "configurationClass", "resolveAndBindMethod");
         ignoreFields("com.sun.tools.javac.util.JDK9Wrappers$Layer",
                 "layerClass", "bootMethod", "defineModulesWithOneLoaderMethod", "configurationMethod");
         ignoreFields("com.sun.tools.javac.util.JDK9Wrappers$Module",
--- a/langtools/src/java.compiler/share/classes/javax/annotation/processing/AbstractProcessor.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/annotation/processing/AbstractProcessor.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -92,7 +92,7 @@
      * same set of strings as the annotation.  If the class is not so
      * annotated, an empty set is returned.
      *
-     * If the {@link ProcessingEvironment#getSourceVersion source
+     * If the {@link ProcessingEnvironment#getSourceVersion source
      * version} does not support modules, in other words if it is less
      * than or equal to {@link SourceVersion#RELEASE_8 RELEASE_8},
      * then any leading {@link Processor#getSupportedAnnotationTypes
--- a/langtools/src/java.compiler/share/classes/javax/annotation/processing/Processor.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/annotation/processing/Processor.java	Thu Mar 16 20:47:03 2017 +0000
@@ -291,7 +291,7 @@
      * @apiNote When running in an environment which supports modules,
      * processors are encouraged to include the module prefix when
      * describing their supported annotation types. The method {@link
-     * AbstractProcessor.getSupportedAnnotationTypes
+     * AbstractProcessor#getSupportedAnnotationTypes
      * AbstractProcessor.getSupportedAnnotationTypes} provides support
      * for stripping off the module prefix when running in an
      * environment without modules.
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/SourceVersion.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/SourceVersion.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -56,6 +56,7 @@
      * 1.7: diamond syntax, try-with-resources, etc.
      * 1.8: lambda expressions and default methods
      *   9: modules, small cleanups to 1.7 and 1.8 changes
+     *  10: to-be-determined changes
      */
 
     /**
@@ -150,7 +151,15 @@
      *
      * @since 9
      */
-     RELEASE_9;
+     RELEASE_9,
+
+    /**
+     * The version recognized by the Java Platform, Standard Edition
+     * 10.
+     *
+     * @since 10
+     */
+     RELEASE_10;
 
     // Note that when adding constants for newer releases, the
     // behavior of latest() and latestSupported() must be updated too.
@@ -161,7 +170,7 @@
      * @return the latest source version that can be modeled
      */
     public static SourceVersion latest() {
-        return RELEASE_9;
+        return RELEASE_10;
     }
 
     private static final SourceVersion latestSupported = getLatestSupported();
@@ -171,6 +180,8 @@
             String specVersion = System.getProperty("java.specification.version");
 
             switch (specVersion) {
+                case "10":
+                    return RELEASE_10;
                 case "9":
                 case "1.9":
                     return RELEASE_9;
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/element/Element.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/element/Element.java	Thu Mar 16 20:47:03 2017 +0000
@@ -123,6 +123,8 @@
      * @see TypeElement#getSimpleName
      * @see VariableElement#getSimpleName
      * @see ModuleElement#getSimpleName
+     * @revised 9
+     * @spec JPMS
      */
     Name getSimpleName();
 
@@ -158,6 +160,8 @@
      *
      * @return the enclosing element, or {@code null} if there is none
      * @see Elements#getPackageOf
+     * @revised 9
+     * @spec JPMS
      */
     Element getEnclosingElement();
 
@@ -193,6 +197,8 @@
      * @see Elements#getAllMembers
      * @jls 8.8.9 Default Constructor
      * @jls 8.9 Enums
+     * @revised 9
+     * @spec JPMS
      */
     List<? extends Element> getEnclosedElements();
 
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/element/ElementKind.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/element/ElementKind.java	Thu Mar 16 20:47:03 2017 +0000
@@ -99,6 +99,7 @@
     /**
      * A module.
      * @since 9
+     * @spec JPMS
      */
      MODULE;
 
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/element/ElementVisitor.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/element/ElementVisitor.java	Thu Mar 16 20:47:03 2017 +0000
@@ -159,6 +159,7 @@
      * @param p  a visitor-specified parameter
      * @return a visitor-specified result
      * @since 9
+     * @spec JPMS
      */
     default R visitModule(ModuleElement e, P p) {
         return visitUnknown(e, p);
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/element/ModuleElement.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/element/ModuleElement.java	Thu Mar 16 20:47:03 2017 +0000
@@ -33,6 +33,7 @@
  *
  * @see javax.lang.model.util.Elements#getModuleOf
  * @since 9
+ * @spec JPMS
  */  // TODO: add @jls to module section
 public interface ModuleElement extends Element, QualifiedNameable {
 
@@ -104,6 +105,7 @@
      * future versions of the Java&trade; programming language.
      *
      * @since 9
+     * @spec JPMS
      */
     enum DirectiveKind {
         /** A "requires (static|transitive)* module-name" directive. */
@@ -122,6 +124,7 @@
      * Represents a "module statement" within the declaration of this module.
      *
      * @since 9
+     * @spec JPMS
      *
      */ // TODO: add jls to Module Statement
     interface Directive {
@@ -136,6 +139,7 @@
     /**
      * A dependency of a module.
      * @since 9
+     * @spec JPMS
      */
     interface RequiresDirective extends Directive {
         /**
@@ -160,6 +164,7 @@
     /**
      * An exported package of a module.
      * @since 9
+     * @spec JPMS
      */
     interface ExportsDirective extends Directive {
 
@@ -181,6 +186,7 @@
     /**
      * An opened package of a module.
      * @since 9
+     * @spec JPMS
      */
     interface OpensDirective extends Directive {
 
@@ -202,6 +208,7 @@
     /**
      * An implementation of a service provided by a module.
      * @since 9
+     * @spec JPMS
      */
     interface ProvidesDirective extends Directive {
         /**
@@ -220,6 +227,7 @@
     /**
      * A reference to a service used by a module.
      * @since 9
+     * @spec JPMS
      */
     interface UsesDirective extends Directive {
         /**
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/element/PackageElement.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/element/PackageElement.java	Thu Mar 16 20:47:03 2017 +0000
@@ -93,6 +93,9 @@
      * source version} without modules.
      *
      * @return the enclosing module or {@code null} if no such module exists
+     *
+     * @revised 9
+     * @spec JPMS
      */
     @Override
     Element getEnclosingElement();
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/type/TypeKind.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/type/TypeKind.java	Thu Mar 16 20:47:03 2017 +0000
@@ -157,6 +157,7 @@
      * A pseudo-type corresponding to a module element.
      * @see NoType
      * @since 9
+     * @spec JPMS
      */
     MODULE;
 
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/util/AbstractElementVisitor6.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/util/AbstractElementVisitor6.java	Thu Mar 16 20:47:03 2017 +0000
@@ -136,6 +136,7 @@
      * @return the result of {@code visitUnknown}
      *
      * @since 9
+     * @spec JPMS
      */
     @Override
     public R visitModule(ModuleElement e, P p) {
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/util/AbstractElementVisitor9.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/util/AbstractElementVisitor9.java	Thu Mar 16 20:47:03 2017 +0000
@@ -63,6 +63,7 @@
  * @see AbstractElementVisitor7
  * @see AbstractElementVisitor8
  * @since 9
+ * @spec JPMS
  */
 @SupportedSourceVersion(RELEASE_9)
 public abstract class AbstractElementVisitor9<R, P> extends AbstractElementVisitor8<R, P> {
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/util/ElementFilter.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/util/ElementFilter.java	Thu Mar 16 20:47:03 2017 +0000
@@ -189,6 +189,7 @@
      * @return a list of modules in {@code elements}
      * @param elements the elements to filter
      * @since 9
+     * @spec JPMS
      */
     public static List<ModuleElement>
             modulesIn(Iterable<? extends Element> elements) {
@@ -200,6 +201,7 @@
      * @return a set of modules in {@code elements}
      * @param elements the elements to filter
      * @since 9
+     * @spec JPMS
      */
     public static Set<ModuleElement>
             modulesIn(Set<? extends Element> elements) {
@@ -236,6 +238,7 @@
      * @return a list of {@code exports} directives in {@code directives}
      * @param directives the directives to filter
      * @since 9
+     * @spec JPMS
      */
     public static List<ExportsDirective>
             exportsIn(Iterable<? extends Directive> directives) {
@@ -258,6 +261,7 @@
      * @return a list of {@code provides} directives in {@code directives}
      * @param directives the directives to filter
      * @since 9
+     * @spec JPMS
      */
     public static List<ProvidesDirective>
             providesIn(Iterable<? extends Directive> directives) {
@@ -269,6 +273,7 @@
      * @return a list of {@code requires} directives in {@code directives}
      * @param directives the directives to filter
      * @since 9
+     * @spec JPMS
      */
     public static List<RequiresDirective>
             requiresIn(Iterable<? extends Directive> directives) {
@@ -280,6 +285,7 @@
      * @return a list of {@code uses} directives in {@code directives}
      * @param directives the directives to filter
      * @since 9
+     * @spec JPMS
      */
     public static List<UsesDirective>
             usesIn(Iterable<? extends Directive> directives) {
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/util/ElementKindVisitor9.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/util/ElementKindVisitor9.java	Thu Mar 16 20:47:03 2017 +0000
@@ -75,6 +75,7 @@
  * @see ElementKindVisitor7
  * @see ElementKindVisitor8
  * @since 9
+ * @spec JPMS
  */
 @SupportedSourceVersion(RELEASE_9)
 public class ElementKindVisitor9<R, P> extends ElementKindVisitor8<R, P> {
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/util/ElementScanner9.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/util/ElementScanner9.java	Thu Mar 16 20:47:03 2017 +0000
@@ -88,6 +88,7 @@
  * @see ElementScanner7
  * @see ElementScanner8
  * @since 9
+ * @spec JPMS
  */
 @SupportedSourceVersion(RELEASE_9)
 public class ElementScanner9<R, P> extends ElementScanner8<R, P> {
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/util/Elements.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/util/Elements.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,9 +25,12 @@
 
 package javax.lang.model.util;
 
-
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
+import java.util.LinkedHashSet;
 
 import javax.lang.model.AnnotatedConstruct;
 import javax.lang.model.element.*;
@@ -65,6 +68,7 @@
      * @param name  fully qualified package name, or an empty string for an unnamed package
      * @param module module relative to which the lookup should happen
      * @return the specified package, or {@code null} if it cannot be found
+     * @see #getAllPackageElements
      * @since 9
      */
     default PackageElement getPackageElement(ModuleElement module, CharSequence name) {
@@ -72,6 +76,49 @@
     }
 
     /**
+     * Returns all package elements with the given canonical name.
+     *
+     * There may be more than one package element with the same canonical
+     * name if the package elements are in different modules.
+     *
+     * @implSpec The default implementation of this method calls
+     * {@link #getAllModuleElements() getAllModuleElements} and stores
+     * the result. If the set of modules is empty, {@link
+     * #getPackageElement(CharSequence) getPackageElement(name)} is
+     * called passing through the name argument. If {@code
+     * getPackageElement(name)} is {@code null}, an empty set of
+     * package elements is returned; otherwise, a single-element set
+     * with the found package element is returned. If the set of
+     * modules is nonempty, the modules are iterated over and any
+     * non-{@code null} results of {@link
+     * #getPackageElement(ModuleElement, CharSequence)
+     * getPackageElement(module, name)} are accumulated into a
+     * set. The set is then returned.
+     *
+     * @param name  the canonical name
+     * @return the package elements, or an empty set if no package with the name can be found
+     * @see #getPackageElement(ModuleElement, CharSequence)
+     * @since 9
+     */
+    default Set<? extends PackageElement> getAllPackageElements(CharSequence name) {
+        Set<? extends ModuleElement> modules = getAllModuleElements();
+        if (modules.isEmpty()) {
+            PackageElement packageElt = getPackageElement(name);
+            return (packageElt != null) ?
+                Collections.singleton(packageElt):
+                Collections.emptySet();
+        } else {
+            Set<PackageElement> result = new LinkedHashSet<>(1); // Usually expect at most 1 result
+            for (ModuleElement module: modules) {
+                PackageElement packageElt = getPackageElement(module, name);
+                if (packageElt != null)
+                    result.add(packageElt);
+            }
+            return Collections.unmodifiableSet(result);
+        }
+    }
+
+    /**
      * Returns a type element given its canonical name if the type element is unique in the environment.
      * If running with modules, all modules in the modules graph are searched for matching
      * type elements.
@@ -90,6 +137,7 @@
      * @param name  the canonical name
      * @param module module relative to which the lookup should happen
      * @return the named type element, or {@code null} if it cannot be found
+     * @see #getAllTypeElements
      * @since 9
      */
     default TypeElement getTypeElement(ModuleElement module, CharSequence name) {
@@ -97,11 +145,54 @@
     }
 
     /**
+     * Returns all type elements with the given canonical name.
+     *
+     * There may be more than one type element with the same canonical
+     * name if the type elements are in different modules.
+     *
+     * @implSpec The default implementation of this method calls
+     * {@link #getAllModuleElements() getAllModuleElements} and stores
+     * the result. If the set of modules is empty, {@link
+     * #getTypeElement(CharSequence) getTypeElement(name)} is called
+     * passing through the name argument. If {@code
+     * getTypeElement(name)} is {@code null}, an empty set of type
+     * elements is returned; otherwise, a single-element set with the
+     * found type element is returned. If the set of modules is
+     * nonempty, the modules are iterated over and any non-{@code null}
+     * results of {@link #getTypeElement(ModuleElement,
+     * CharSequence) getTypeElement(module, name)} are accumulated
+     * into a set. The set is then returned.
+     *
+     * @param name  the canonical name
+     * @return the type elements, or an empty set if no type with the name can be found
+     * @see #getTypeElement(ModuleElement, CharSequence)
+     * @since 9
+     */
+    default Set<? extends TypeElement> getAllTypeElements(CharSequence name) {
+        Set<? extends ModuleElement> modules = getAllModuleElements();
+        if (modules.isEmpty()) {
+            TypeElement typeElt = getTypeElement(name);
+            return (typeElt != null) ?
+                Collections.singleton(typeElt):
+                Collections.emptySet();
+        } else {
+            Set<TypeElement> result = new LinkedHashSet<>(1); // Usually expect at most 1 result
+            for (ModuleElement module: modules) {
+                TypeElement typeElt = getTypeElement(module, name);
+                if (typeElt != null)
+                    result.add(typeElt);
+            }
+            return Collections.unmodifiableSet(result);
+        }
+    }
+
+    /**
      * Returns a module element given its fully qualified name.
-     * If the named module cannot be found, null is returned. One situation where a module
-     * cannot be found is if the environment does not include modules, such as
-     * an annotation processing environment configured for
-     * a {@linkplain
+     *
+     * If the named module cannot be found, {@code null} is
+     * returned. One situation where a module cannot be found is if
+     * the environment does not include modules, such as an annotation
+     * processing environment configured for a {@linkplain
      * javax.annotation.processing.ProcessingEnvironment#getSourceVersion
      * source version} without modules.
      *
@@ -110,13 +201,36 @@
      *
      * @param name  the name
      * @return the named module element, or {@code null} if it cannot be found
+     * @see #getAllModuleElements
      * @since 9
+     * @spec JPMS
      */
     default ModuleElement getModuleElement(CharSequence name) {
         return null;
     }
 
     /**
+     * Returns all module elements in the current environment.
+     *
+     * If no modules are present, an empty set is returned. One
+     * situation where no modules are present occurs when the
+     * environment does not include modules, such as an annotation
+     * processing environment configured for a {@linkplain
+     * javax.annotation.processing.ProcessingEnvironment#getSourceVersion
+     * source version} without modules.
+     *
+     * @implSpec The default implementation of this method returns
+     * an empty set.
+     *
+     * @return the known module elements, or an empty set if there are no modules
+     * @see #getModuleElement(CharSequence)
+     * @since 9
+     */
+    default Set<? extends ModuleElement> getAllModuleElements() {
+        return Collections.emptySet();
+    }
+
+    /**
      * Returns the values of an annotation's elements, including defaults.
      *
      * @see AnnotationMirror#getElementValues()
@@ -359,6 +473,7 @@
      * @param type the element being examined
      * @return the module of an element
      * @since 9
+     * @spec JPMS
      */
     default ModuleElement getModuleOf(Element type) {
         return null;
--- a/langtools/src/java.compiler/share/classes/javax/lang/model/util/SimpleElementVisitor9.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/lang/model/util/SimpleElementVisitor9.java	Thu Mar 16 20:47:03 2017 +0000
@@ -71,6 +71,7 @@
  * @see SimpleElementVisitor7
  * @see SimpleElementVisitor8
  * @since 9
+ * @spec JPMS
  */
 @SupportedSourceVersion(RELEASE_9)
 public class SimpleElementVisitor9<R, P> extends SimpleElementVisitor8<R, P> {
--- a/langtools/src/java.compiler/share/classes/javax/tools/DocumentationTool.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/tools/DocumentationTool.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -121,7 +121,20 @@
      */
     interface DocumentationTask extends Callable<Boolean> {
         /**
-         * Set the locale to be applied when formatting diagnostics and
+         * Adds root modules to be taken into account during module
+         * resolution.
+         * Invalid module names may cause either
+         * {@code IllegalArgumentException} to be thrown,
+         * or diagnostics to be reported when the task is started.
+         * @param moduleNames the names of the root modules
+         * @throws IllegalArgumentException may be thrown for some
+         *      invalid module names
+         * @throws IllegalStateException if the task has started
+         */
+        void addModules(Iterable<String> moduleNames);
+
+        /**
+         * Sets the locale to be applied when formatting diagnostics and
          * other localized data.
          *
          * @param locale the locale to apply; {@code null} means apply no
--- a/langtools/src/java.compiler/share/classes/javax/tools/ForwardingJavaFileManager.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/tools/ForwardingJavaFileManager.java	Thu Mar 16 20:47:03 2017 +0000
@@ -165,22 +165,42 @@
         fileManager.close();
     }
 
+    /**
+     * @since 9
+     * @spec JPMS
+     */
     public Location getLocationForModule(Location location, String moduleName) throws IOException {
         return fileManager.getLocationForModule(location, moduleName);
     }
 
+    /**
+     * @since 9
+     * @spec JPMS
+     */
     public Location getLocationForModule(Location location, JavaFileObject fo, String pkgName) throws IOException {
         return fileManager.getLocationForModule(location, fo, pkgName);
     }
 
+    /**
+     * @since 9
+     * @spec JPMS
+     */
     public <S> ServiceLoader<S> getServiceLoader(Location location, Class<S> service) throws  IOException {
         return fileManager.getServiceLoader(location, service);
     }
 
+    /**
+     * @since 9
+     * @spec JPMS
+     */
     public String inferModuleName(Location location) throws IOException {
         return fileManager.inferModuleName(location);
     }
 
+    /**
+     * @since 9
+     * @spec JPMS
+     */
     public Iterable<Set<Location>> listLocationsForModules(Location location) throws IOException {
         return fileManager.listLocationsForModules(location);
     }
--- a/langtools/src/java.compiler/share/classes/javax/tools/JavaCompiler.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/tools/JavaCompiler.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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,7 +25,6 @@
 
 package javax.tools;
 
-import java.io.File;
 import java.io.Writer;
 import java.nio.charset.Charset;
 import java.util.Locale;
@@ -296,6 +295,18 @@
      * {@linkplain #setProcessors setProcessors} method.
      */
     interface CompilationTask extends Callable<Boolean> {
+        /**
+         * Adds root modules to be taken into account during module
+         * resolution.
+         * Invalid module names may cause either
+         * {@code IllegalArgumentException} to be thrown,
+         * or diagnostics to be reported when the task is started.
+         * @param moduleNames the names of the root modules
+         * @throws IllegalArgumentException may be thrown for some
+         *      invalid module names
+         * @throws IllegalStateException if the task has started
+         */
+        void addModules(Iterable<String> moduleNames);
 
         /**
          * Sets processors (for annotation processing).  This will
@@ -307,7 +318,7 @@
         void setProcessors(Iterable<? extends Processor> processors);
 
         /**
-         * Set the locale to be applied when formatting diagnostics and
+         * Sets the locale to be applied when formatting diagnostics and
          * other localized data.
          *
          * @param locale the locale to apply; {@code null} means apply no
@@ -330,6 +341,7 @@
          * in user code.
          * @throws IllegalStateException if called more than once
          */
+        @Override
         Boolean call();
     }
 }
--- a/langtools/src/java.compiler/share/classes/javax/tools/JavaFileManager.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/tools/JavaFileManager.java	Thu Mar 16 20:47:03 2017 +0000
@@ -130,7 +130,7 @@
      * It is not possible to directly list the classes in a module-oriented
      * location. Instead, you can get a package-oriented location for any specific module
      * using methods like {@link JavaFileManager#getLocationForModule} or
-     * {@link JavaFileManager#listLocationsForModule}.
+     * {@link JavaFileManager#listLocationsForModules}.
      */
     interface Location {
         /**
@@ -165,6 +165,7 @@
          *
          * @return true if this location is expected to contain modules
          * @since 9
+         * @spec JPMS
          */
         default boolean isModuleOrientedLocation() {
             return getName().matches("\\bMODULE\\b");
@@ -472,6 +473,7 @@
      * @throws IllegalArgumentException if the location is neither an output location nor a
      * module-oriented location
      * @since 9
+     * @spec JPMS
      */ // TODO: describe failure modes
     default Location getLocationForModule(Location location, String moduleName) throws IOException {
         throw new UnsupportedOperationException();
@@ -499,6 +501,7 @@
      * @throws IllegalArgumentException if the location is neither an output location nor a
      * module-oriented location
      * @since 9
+     * @spec JPMS
      */
     default Location getLocationForModule(Location location, JavaFileObject fo, String pkgName) throws IOException {
         throw new UnsupportedOperationException();
@@ -522,6 +525,7 @@
      * @throws IOException if an I/O error occurred
      * @throws UnsupportedOperationException if this operation if not supported by this file manager
      * @since 9
+     * @spec JPMS
      */ // TODO: describe failure modes
     default <S> ServiceLoader<S> getServiceLoader(Location location, Class<S> service) throws  IOException {
         throw new UnsupportedOperationException();
@@ -540,6 +544,7 @@
      * @throws UnsupportedOperationException if this operation if not supported by this file manager
      * @throws IllegalArgumentException if the location is not one known to this file manager
      * @since 9
+     * @spec JPMS
      */ // TODO: describe failure modes
     default String inferModuleName(Location location) throws IOException {
         throw new UnsupportedOperationException();
@@ -559,6 +564,7 @@
      * @throws UnsupportedOperationException if this operation if not supported by this file manager
      * @throws IllegalArgumentException if the location is not a module-oriented location
      * @since 9
+     * @spec JPMS
      */ // TODO: describe failure modes
     default Iterable<Set<Location>> listLocationsForModules(Location location) throws IOException {
         throw new UnsupportedOperationException();
--- a/langtools/src/java.compiler/share/classes/javax/tools/StandardLocation.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/javax/tools/StandardLocation.java	Thu Mar 16 20:47:03 2017 +0000
@@ -64,6 +64,7 @@
 
     /**
      * Location to search for modules containing annotation processors.
+     * @spec JPMS
      * @since 9
      */
     ANNOTATION_PROCESSOR_MODULE_PATH,
@@ -82,27 +83,38 @@
 
     /**
      * Location to search for the source code of modules.
+     * @spec JPMS
      * @since 9
      */
     MODULE_SOURCE_PATH,
 
     /**
      * Location to search for upgradeable system modules.
+     * @spec JPMS
      * @since 9
      */
     UPGRADE_MODULE_PATH,
 
     /**
      * Location to search for system modules.
+     * @spec JPMS
      * @since 9
      */
     SYSTEM_MODULES,
 
     /**
      * Location to search for precompiled user modules.
+     * @spec JPMS
      * @since 9
      */
-    MODULE_PATH;
+    MODULE_PATH,
+
+    /**
+     * Location to search for module patches.
+     * @since 9
+     * @spec JPMS
+     */
+    PATCH_MODULE_PATH;
 
     /**
      * Returns a location object with the given name.  The following
@@ -115,6 +127,9 @@
      *
      * @param name a name
      * @return a location
+     *
+     * @revised 9
+     * @spec JPMS
      */
     public static Location locationFor(final String name) {
         if (locations.isEmpty()) {
@@ -158,6 +173,7 @@
             case UPGRADE_MODULE_PATH:
             case SYSTEM_MODULES:
             case MODULE_PATH:
+            case PATCH_MODULE_PATH:
                 return true;
             default:
                 return false;
--- a/langtools/src/java.compiler/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/java.compiler/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -29,6 +29,8 @@
   * These APIs model declarations and types of the Java programming language,
   * and define interfaces for tools such as compilers which can be invoked
   * from a program.
+  *
+  * @since 9
   */
 module java.compiler {
     exports javax.annotation.processing;
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/api/BasicJavacTask.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/api/BasicJavacTask.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -155,6 +155,11 @@
     }
 
     @Override @DefinedBy(Api.COMPILER)
+    public void addModules(Iterable<String> moduleNames) {
+        throw new IllegalStateException();
+    }
+
+    @Override @DefinedBy(Api.COMPILER)
     public void setProcessors(Iterable<? extends Processor> processors) {
         throw new IllegalStateException();
     }
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/api/ClientCodeWrapper.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/api/ClientCodeWrapper.java	Thu Mar 16 20:47:03 2017 +0000
@@ -361,7 +361,7 @@
         @Override @DefinedBy(Api.COMPILER)
         public Location getLocationForModule(Location location, JavaFileObject fo, String pkgName) throws IOException {
             try {
-                return clientJavaFileManager.getLocationForModule(location, fo, pkgName);
+                return clientJavaFileManager.getLocationForModule(location, unwrap(fo), pkgName);
             } catch (ClientCodeException e) {
                 throw e;
             } catch (RuntimeException | Error e) {
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/api/JavacTaskImpl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/api/JavacTaskImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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,17 +33,12 @@
 
 import javax.annotation.processing.Processor;
 import javax.lang.model.element.Element;
-import javax.lang.model.element.ElementKind;
 import javax.lang.model.element.TypeElement;
-import javax.lang.model.util.ElementFilter;
 import javax.tools.*;
-import javax.tools.JavaFileObject.Kind;
 
 import com.sun.source.tree.*;
 import com.sun.tools.javac.code.*;
 import com.sun.tools.javac.code.Symbol.ClassSymbol;
-import com.sun.tools.javac.code.Symbol.ModuleSymbol;
-import com.sun.tools.javac.code.Symbol.PackageSymbol;
 import com.sun.tools.javac.comp.*;
 import com.sun.tools.javac.file.BaseFileManager;
 import com.sun.tools.javac.main.*;
@@ -82,6 +77,7 @@
     private ListBuffer<Env<AttrContext>> genList;
     private final AtomicBoolean used = new AtomicBoolean();
     private Iterable<? extends Processor> processors;
+    private ListBuffer<String> addModules = new ListBuffer<>();
 
     protected JavacTaskImpl(Context context) {
         super(context, true);
@@ -101,7 +97,7 @@
                 prepareCompiler(false);
                 if (compiler.errorCount() > 0)
                     return Main.Result.ERROR;
-                compiler.compile(args.getFileObjects(), args.getClassNames(), processors);
+                compiler.compile(args.getFileObjects(), args.getClassNames(), processors, addModules);
                 return (compiler.errorCount() > 0) ? Main.Result.ERROR : Main.Result.OK; // FIXME?
             }, Main.Result.SYSERR, Main.Result.ABNORMAL);
         } finally {
@@ -114,6 +110,18 @@
     }
 
     @Override @DefinedBy(Api.COMPILER)
+    public void addModules(Iterable<String> moduleNames) {
+        Objects.requireNonNull(moduleNames);
+        // not mt-safe
+        if (used.get())
+            throw new IllegalStateException();
+        for (String m : moduleNames) {
+            Objects.requireNonNull(m);
+            addModules.add(m);
+        }
+    }
+
+    @Override @DefinedBy(Api.COMPILER)
     public void setProcessors(Iterable<? extends Processor> processors) {
         Objects.requireNonNull(processors);
         // not mt-safe
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/api/JavacTrees.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/api/JavacTrees.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -418,6 +418,7 @@
 
     private Symbol attributeDocReference(TreePath path, DCReference ref) {
         Env<AttrContext> env = getAttrContext(path);
+        if (env == null) return null;
 
         Log.DeferredDiagnosticHandler deferredDiagnosticHandler =
                 new Log.DeferredDiagnosticHandler(log);
@@ -482,7 +483,7 @@
                 paramTypes = lb.toList();
             }
 
-            ClassSymbol sym = (ClassSymbol) types.cvarUpperBound(tsym.type).tsym;
+            ClassSymbol sym = (ClassSymbol) types.skipTypeVars(tsym.type, false).tsym;
 
             Symbol msym = (memberName == sym.name)
                     ? findConstructor(sym, paramTypes)
@@ -881,6 +882,7 @@
                 case INTERFACE:
 //                    System.err.println("CLASS: " + ((JCClassDecl)tree).sym.getSimpleName());
                     env = enter.getClassEnv(((JCClassDecl)tree).sym);
+                    if (env == null) return null;
                     break;
                 case METHOD:
 //                    System.err.println("METHOD: " + ((JCMethodDecl)tree).sym.getSimpleName());
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ClassFinder.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ClassFinder.java	Thu Mar 16 20:47:03 2017 +0000
@@ -553,20 +553,47 @@
 
         Location classLocn = msym.classLocation;
         Location sourceLocn = msym.sourceLocation;
+        Location patchLocn = msym.patchLocation;
+        Location patchOutLocn = msym.patchOutputLocation;
 
-        if (wantClassFiles && (classLocn != null)) {
-            fillIn(p, classLocn,
-                   list(classLocn,
-                        p,
-                        packageName,
-                        classKinds));
-        }
-        if (wantSourceFiles && (sourceLocn != null)) {
-            fillIn(p, sourceLocn,
-                   list(sourceLocn,
-                        p,
-                        packageName,
-                        sourceKinds));
+        boolean prevPreferCurrent = preferCurrent;
+
+        try {
+            preferCurrent = false;
+            if (wantClassFiles && (patchOutLocn != null)) {
+                fillIn(p, patchOutLocn,
+                       list(patchOutLocn,
+                            p,
+                            packageName,
+                            classKinds));
+            }
+            if ((wantClassFiles || wantSourceFiles) && (patchLocn != null)) {
+                Set<JavaFileObject.Kind> combined = EnumSet.noneOf(JavaFileObject.Kind.class);
+                combined.addAll(classKinds);
+                combined.addAll(sourceKinds);
+                fillIn(p, patchLocn,
+                       list(patchLocn,
+                            p,
+                            packageName,
+                            combined));
+            }
+            preferCurrent = true;
+            if (wantClassFiles && (classLocn != null)) {
+                fillIn(p, classLocn,
+                       list(classLocn,
+                            p,
+                            packageName,
+                            classKinds));
+            }
+            if (wantSourceFiles && (sourceLocn != null)) {
+                fillIn(p, sourceLocn,
+                       list(sourceLocn,
+                            p,
+                            packageName,
+                            sourceKinds));
+            }
+        } finally {
+            preferCurrent = prevPreferCurrent;
         }
     }
 
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Directive.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Directive.java	Thu Mar 16 20:47:03 2017 +0000
@@ -53,8 +53,8 @@
 
     /** Flags for RequiresDirective. */
     public enum RequiresFlag {
-        TRANSITIVE(0x0010),
-        STATIC_PHASE(0x0020),
+        TRANSITIVE(0x0020),
+        STATIC_PHASE(0x0040),
         SYNTHETIC(0x1000),
         MANDATED(0x8000),
         EXTRA(0x10000);
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ModuleFinder.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/ModuleFinder.java	Thu Mar 16 20:47:03 2017 +0000
@@ -267,6 +267,7 @@
     private List<ModuleSymbol> scanModulePath(ModuleSymbol toFind) {
         ListBuffer<ModuleSymbol> results = new ListBuffer<>();
         Map<Name, Location> namesInSet = new HashMap<>();
+        boolean multiModuleMode = fileManager.hasLocation(StandardLocation.MODULE_SOURCE_PATH);
         while (moduleLocationIterator.hasNext()) {
             Set<Location> locns = (moduleLocationIterator.next());
             namesInSet.clear();
@@ -279,10 +280,29 @@
                             // module has already been found, so ignore this instance
                             continue;
                         }
+                        if (fileManager.hasLocation(StandardLocation.PATCH_MODULE_PATH) &&
+                            msym.patchLocation == null) {
+                            msym.patchLocation =
+                                    fileManager.getLocationForModule(StandardLocation.PATCH_MODULE_PATH,
+                                                                     msym.name.toString());
+                            checkModuleInfoOnLocation(msym.patchLocation, Kind.CLASS, Kind.SOURCE);
+                            if (msym.patchLocation != null &&
+                                multiModuleMode &&
+                                fileManager.hasLocation(StandardLocation.CLASS_OUTPUT)) {
+                                msym.patchOutputLocation =
+                                        fileManager.getLocationForModule(StandardLocation.CLASS_OUTPUT,
+                                                                         msym.name.toString());
+                                checkModuleInfoOnLocation(msym.patchOutputLocation, Kind.CLASS);
+                            }
+                        }
                         if (moduleLocationIterator.outer == StandardLocation.MODULE_SOURCE_PATH) {
-                            msym.sourceLocation = l;
-                            if (fileManager.hasLocation(StandardLocation.CLASS_OUTPUT)) {
-                                msym.classLocation = fileManager.getLocationForModule(StandardLocation.CLASS_OUTPUT, msym.name.toString());
+                            if (msym.patchLocation == null) {
+                                msym.sourceLocation = l;
+                                if (fileManager.hasLocation(StandardLocation.CLASS_OUTPUT)) {
+                                    msym.classLocation =
+                                            fileManager.getLocationForModule(StandardLocation.CLASS_OUTPUT,
+                                                                             msym.name.toString());
+                                }
                             }
                         } else {
                             msym.classLocation = l;
@@ -291,7 +311,8 @@
                             moduleLocationIterator.outer == StandardLocation.UPGRADE_MODULE_PATH) {
                             msym.flags_field |= Flags.SYSTEM_MODULE;
                         }
-                        if (toFind == msym || toFind == null) {
+                        if (toFind == null ||
+                            (toFind == msym && (msym.sourceLocation != null || msym.classLocation != null))) {
                             // Note: cannot return msym directly, because we must finish
                             // processing this set first
                             results.add(msym);
@@ -311,6 +332,21 @@
         return results.toList();
     }
 
+    private void checkModuleInfoOnLocation(Location location, Kind... kinds) throws IOException {
+        if (location == null)
+            return ;
+
+        for (Kind kind : kinds) {
+            JavaFileObject file = fileManager.getJavaFileForInput(location,
+                                                                  names.module_info.toString(),
+                                                                  kind);
+            if (file != null) {
+                log.error(Errors.LocnModuleInfoNotAllowedOnPatchPath(file));
+                return;
+            }
+        }
+    }
+
     private void findModuleInfo(ModuleSymbol msym) {
         try {
             JavaFileObject src_fo = (msym.sourceLocation == null) ? null
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Source.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, 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
@@ -70,8 +70,11 @@
     /** 1.8 lambda expressions and default methods. */
     JDK1_8("1.8"),
 
-    /** 1.9 covers the to be determined language features that will be added in JDK 9. */
-    JDK1_9("1.9");
+    /** 1.9 modularity. */
+    JDK1_9("1.9"),
+
+    /** 1.10 covers the to be determined language features that will be added in JDK 10. */
+    JDK1_10("1.10");
 
     private static final Context.Key<Source> sourceKey = new Context.Key<>();
 
@@ -99,6 +102,7 @@
         tab.put("7", JDK1_7); // Make 7 an alias for 1.7
         tab.put("8", JDK1_8); // Make 8 an alias for 1.8
         tab.put("9", JDK1_9); // Make 9 an alias for 1.9
+        tab.put("10", JDK1_10); // Make 10 an alias for 1.10
     }
 
     private Source(String name) {
@@ -116,6 +120,7 @@
     }
 
     public Target requiredTarget() {
+        if (this.compareTo(JDK1_10) >= 0) return Target.JDK1_10;
         if (this.compareTo(JDK1_9) >= 0) return Target.JDK1_9;
         if (this.compareTo(JDK1_8) >= 0) return Target.JDK1_8;
         if (this.compareTo(JDK1_7) >= 0) return Target.JDK1_7;
@@ -240,6 +245,8 @@
             return RELEASE_8;
         case JDK1_9:
             return RELEASE_9;
+        case JDK1_10:
+            return RELEASE_10;
         default:
             return null;
         }
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/code/Symbol.java	Thu Mar 16 20:47:03 2017 +0000
@@ -908,6 +908,8 @@
         public Name version;
         public JavaFileManager.Location sourceLocation;
         public JavaFileManager.Location classLocation;
+        public JavaFileManager.Location patchLocation;
+        public JavaFileManager.Location patchOutputLocation;
 
         /** All directives, in natural order. */
         public List<com.sun.tools.javac.code.Directive> directives;
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Attr.java	Thu Mar 16 20:47:03 2017 +0000
@@ -3994,10 +3994,16 @@
                         rs.methodArguments(argtypes.map(checkDeferredMap)),
                         kindName(sym.location()),
                         sym.location());
-               owntype = new MethodType(owntype.getParameterTypes(),
-                       types.erasure(owntype.getReturnType()),
-                       types.erasure(owntype.getThrownTypes()),
-                       syms.methodClass);
+                if (resultInfo.pt != Infer.anyPoly ||
+                        !owntype.hasTag(METHOD) ||
+                        !owntype.isPartial()) {
+                    //if this is not a partially inferred method type, erase return type. Otherwise,
+                    //erasure is carried out in PartiallyInferredMethodType.check().
+                    owntype = new MethodType(owntype.getParameterTypes(),
+                            types.erasure(owntype.getReturnType()),
+                            types.erasure(owntype.getThrownTypes()),
+                            syms.methodClass);
+                }
             }
 
             PolyKind pkind = (sym.type.hasTag(FORALL) &&
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/AttrContext.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/AttrContext.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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
@@ -79,6 +79,10 @@
      */
     boolean isNewClass = false;
 
+    /** Indicate if the type being visited is a service implementation
+     */
+    boolean visitingServiceImplementation = false;
+
     /** Are arguments to current function applications boxed into an array for varargs?
      */
     Resolve.MethodResolutionPhase pendingResolutionPhase = null;
@@ -127,6 +131,7 @@
         info.isAnonymousDiamond = isAnonymousDiamond;
         info.isNewClass = isNewClass;
         info.preferredTreeForDiagnostics = preferredTreeForDiagnostics;
+        info.visitingServiceImplementation = visitingServiceImplementation;
         return info;
     }
 
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Enter.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Enter.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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 javax.tools.JavaFileManager;
 
 import com.sun.tools.javac.code.*;
+import com.sun.tools.javac.code.Kinds.KindName;
 import com.sun.tools.javac.code.Kinds.KindSelector;
 import com.sun.tools.javac.code.Scope.*;
 import com.sun.tools.javac.code.Symbol.*;
@@ -155,6 +156,7 @@
 
     public Env<AttrContext> getClassEnv(TypeSymbol sym) {
         Env<AttrContext> localEnv = getEnv(sym);
+        if (localEnv == null) return null;
         Env<AttrContext> lintEnv = localEnv;
         while (lintEnv.info.lint == null)
             lintEnv = lintEnv.next;
@@ -400,8 +402,14 @@
             c = syms.enterClass(env.toplevel.modle, tree.name, packge);
             packge.members().enterIfAbsent(c);
             if ((tree.mods.flags & PUBLIC) != 0 && !classNameMatchesFileName(c, env)) {
+                KindName topElement = KindName.CLASS;
+                if ((tree.mods.flags & ENUM) != 0) {
+                    topElement = KindName.ENUM;
+                } else if ((tree.mods.flags & INTERFACE) != 0) {
+                    topElement = KindName.INTERFACE;
+                }
                 log.error(tree.pos(),
-                          "class.public.should.be.in.file", tree.name);
+                          "class.public.should.be.in.file", topElement, tree.name);
             }
         } else {
             if (!tree.name.isEmpty() &&
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Infer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Infer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -319,7 +319,8 @@
                  *  need to use it several times: with several targets.
                  */
                 saved_undet = inferenceContext.save();
-                if (allowGraphInference && !warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED)) {
+                boolean unchecked = warn.hasNonSilentLint(Lint.LintCategory.UNCHECKED);
+                if (allowGraphInference && !unchecked) {
                     boolean shouldPropagate = shouldPropagate(getReturnType(), resultInfo, inferenceContext);
 
                     InferenceContext minContext = shouldPropagate ?
@@ -338,7 +339,10 @@
                     }
                 }
                 inferenceContext.solve(noWarnings);
-                return inferenceContext.asInstType(this).getReturnType();
+                Type ret = inferenceContext.asInstType(this).getReturnType();
+                //inline logic from Attr.checkMethod - if unchecked conversion was required, erase
+                //return type _after_ resolution
+                return unchecked ? types.erasure(ret) : ret;
             } catch (InferenceException ex) {
                 resultInfo.checkContext.report(null, ex.getDiagnostic());
                 Assert.error(); //cannot get here (the above should throw)
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Modules.java	Thu Mar 16 20:47:03 2017 +0000
@@ -145,7 +145,7 @@
 
     public final boolean multiModuleMode;
 
-    private final String moduleOverride;
+    private final String legacyModuleOverride;
 
     private final Name java_se;
     private final Name java_;
@@ -192,7 +192,7 @@
 
         lintOptions = options.isUnset(Option.XLINT_CUSTOM, "-" + LintCategory.OPTIONS.option);
 
-        moduleOverride = options.get(Option.XMODULE);
+        legacyModuleOverride = options.get(Option.XMODULE);
 
         multiModuleMode = fileManager.hasLocation(StandardLocation.MODULE_SOURCE_PATH);
         ClassWriter classWriter = ClassWriter.instance(context);
@@ -366,9 +366,26 @@
 
                 JavaFileObject prev = log.useSource(tree.sourcefile);
                 try {
-                    Location locn = getModuleLocation(tree);
-                    if (locn != null) {
-                        Name name = names.fromString(fileManager.inferModuleName(locn));
+                    Location msplocn = getModuleLocation(tree);
+                    Location plocn = fileManager.hasLocation(StandardLocation.PATCH_MODULE_PATH) ?
+                            fileManager.getLocationForModule(StandardLocation.PATCH_MODULE_PATH,
+                                                             tree.sourcefile, getPackageName(tree)) :
+                            null;
+
+                    if (plocn != null) {
+                        Name name = names.fromString(fileManager.inferModuleName(plocn));
+                        ModuleSymbol msym = moduleFinder.findModule(name);
+                        tree.modle = msym;
+                        rootModules.add(msym);
+
+                        if (msplocn != null) {
+                            Name mspname = names.fromString(fileManager.inferModuleName(msplocn));
+                            if (name != mspname) {
+                                log.error(tree.pos(), Errors.FilePatchedAndMsp(name, mspname));
+                            }
+                        }
+                    } else if (msplocn != null) {
+                        Name name = names.fromString(fileManager.inferModuleName(msplocn));
                         ModuleSymbol msym;
                         JCModuleDecl decl = tree.getModuleDecl();
                         if (decl != null) {
@@ -383,7 +400,7 @@
                             msym = syms.enterModule(name);
                         }
                         if (msym.sourceLocation == null) {
-                            msym.sourceLocation = locn;
+                            msym.sourceLocation = msplocn;
                             if (fileManager.hasLocation(StandardLocation.CLASS_OUTPUT)) {
                                 msym.classLocation = fileManager.getLocationForModule(
                                         StandardLocation.CLASS_OUTPUT, msym.name.toString());
@@ -414,7 +431,9 @@
             }
             defaultModule = syms.unnamedModule;
         } else {
+            ModuleSymbol module = null;
             if (defaultModule == null) {
+                String moduleOverride = singleModuleOverride(trees);
                 switch (rootModules.size()) {
                     case 0:
                         defaultModule = moduleFinder.findSingleModule();
@@ -422,38 +441,49 @@
                             if (moduleOverride != null) {
                                 checkNoAllModulePath();
                                 defaultModule = moduleFinder.findModule(names.fromString(moduleOverride));
-                                defaultModule.sourceLocation = StandardLocation.SOURCE_PATH;
+                                if (legacyModuleOverride != null) {
+                                    defaultModule.sourceLocation = StandardLocation.SOURCE_PATH;
+                                }
+                                defaultModule.patchOutputLocation = StandardLocation.CLASS_OUTPUT;
                             } else {
                                 // Question: why not do findAllModules and initVisiblePackages here?
                                 // i.e. body of unnamedModuleCompleter
                                 defaultModule.completer = getUnnamedModuleCompleter();
+                                defaultModule.sourceLocation = StandardLocation.SOURCE_PATH;
                                 defaultModule.classLocation = StandardLocation.CLASS_PATH;
                             }
                         } else {
-                            checkSpecifiedModule(trees, Errors.ModuleInfoWithXmoduleClasspath);
+                            checkSpecifiedModule(trees, moduleOverride, Errors.ModuleInfoWithPatchedModuleClassoutput);
                             checkNoAllModulePath();
                             defaultModule.complete();
                             // Question: why not do completeModule here?
                             defaultModule.completer = sym -> completeModule((ModuleSymbol) sym);
+                            defaultModule.sourceLocation = StandardLocation.SOURCE_PATH;
                         }
                         rootModules.add(defaultModule);
                         break;
                     case 1:
-                        checkSpecifiedModule(trees, Errors.ModuleInfoWithXmoduleSourcepath);
+                        checkSpecifiedModule(trees, moduleOverride, Errors.ModuleInfoWithPatchedModuleSourcepath);
                         checkNoAllModulePath();
                         defaultModule = rootModules.iterator().next();
+                        defaultModule.sourceLocation = StandardLocation.SOURCE_PATH;
                         defaultModule.classLocation = StandardLocation.CLASS_OUTPUT;
                         break;
                     default:
                         Assert.error("too many modules");
                 }
-                defaultModule.sourceLocation = StandardLocation.SOURCE_PATH;
             } else if (rootModules.size() == 1 && defaultModule == rootModules.iterator().next()) {
                 defaultModule.complete();
                 defaultModule.completer = sym -> completeModule((ModuleSymbol) sym);
             } else {
                 Assert.check(rootModules.isEmpty());
-                rootModules.add(defaultModule);
+                String moduleOverride = singleModuleOverride(trees);
+                if (moduleOverride != null) {
+                    module = moduleFinder.findModule(names.fromString(moduleOverride));
+                } else {
+                    module = defaultModule;
+                }
+                rootModules.add(module);
             }
 
             if (defaultModule != syms.unnamedModule) {
@@ -461,12 +491,56 @@
                 syms.unnamedModule.classLocation = StandardLocation.CLASS_PATH;
             }
 
+            if (module == null) {
+                module = defaultModule;
+            }
+
             for (JCCompilationUnit tree: trees) {
-                tree.modle = defaultModule;
+                tree.modle = module;
             }
         }
     }
 
+    private String singleModuleOverride(List<JCCompilationUnit> trees) {
+        if (!fileManager.hasLocation(StandardLocation.PATCH_MODULE_PATH)) {
+            return legacyModuleOverride;
+        }
+
+        Set<String> override = new LinkedHashSet<>();
+        for (JCCompilationUnit tree : trees) {
+            JavaFileObject fo = tree.sourcefile;
+
+            try {
+                Location loc =
+                        fileManager.getLocationForModule(StandardLocation.PATCH_MODULE_PATH,
+                                                         fo, getPackageName(tree));
+
+                if (loc != null) {
+                    override.add(fileManager.inferModuleName(loc));
+                }
+            } catch (IOException ex) {
+                throw new Error(ex);
+            }
+        }
+
+        switch (override.size()) {
+            case 0: return legacyModuleOverride;
+            case 1: return override.iterator().next();
+            default:
+                log.error(Errors.TooManyPatchedModules(override));
+                return null;
+        }
+    }
+
+    private String getPackageName(JCCompilationUnit tree) {
+        if (tree.getModuleDecl() != null) {
+            return null;
+        } else {
+            JCPackageDecl pkg = tree.getPackage();
+            return (pkg == null) ? "" : TreeInfo.fullName(pkg.pid).toString();
+        }
+    }
+
     /**
      * Determine the location for the module on the module source path
      * or source output directory which contains a given CompilationUnit.
@@ -478,32 +552,23 @@
      * @throws IOException if there is a problem while searching for the module.
      */
     private Location getModuleLocation(JCCompilationUnit tree) throws IOException {
-        Name pkgName;
-        if (tree.getModuleDecl() != null) {
-            pkgName = null;
-        } else {
-            JCPackageDecl pkg = tree.getPackage();
-            pkgName = (pkg == null) ? names.empty : TreeInfo.fullName(pkg.pid);
-        }
-
+        String pkgName = getPackageName(tree);
         JavaFileObject fo = tree.sourcefile;
 
-        // For now, just check module source path.
-        // We may want to check source path as well.
         Location loc =
                 fileManager.getLocationForModule(StandardLocation.MODULE_SOURCE_PATH,
-                                                 fo, (pkgName == null) ? null : pkgName.toString());
+                                                 fo, (pkgName == null) ? null : pkgName);
         if (loc == null) {
             Location sourceOutput = fileManager.hasLocation(StandardLocation.SOURCE_OUTPUT) ?
                     StandardLocation.SOURCE_OUTPUT : StandardLocation.CLASS_OUTPUT;
             loc =
                 fileManager.getLocationForModule(sourceOutput,
-                                                 fo, (pkgName == null) ? null : pkgName.toString());
+                                                 fo, (pkgName == null) ? null : pkgName);
         }
         return loc;
     }
 
-    private void checkSpecifiedModule(List<JCCompilationUnit> trees, JCDiagnostic.Error error) {
+    private void checkSpecifiedModule(List<JCCompilationUnit> trees, String moduleOverride, JCDiagnostic.Error error) {
         if (moduleOverride != null) {
             JavaFileObject prev = log.useSource(trees.head.sourcefile);
             try {
@@ -931,8 +996,18 @@
             }
             ListBuffer<ClassSymbol> impls = new ListBuffer<>();
             for (JCExpression implName : tree.implNames) {
-                Type it = attr.attribType(implName, env, syms.objectType);
+                Type it;
+                boolean prevVisitingServiceImplementation = env.info.visitingServiceImplementation;
+                try {
+                    env.info.visitingServiceImplementation = true;
+                    it = attr.attribType(implName, env, syms.objectType);
+                } finally {
+                    env.info.visitingServiceImplementation = prevVisitingServiceImplementation;
+                }
                 ClassSymbol impl = (ClassSymbol) it.tsym;
+                if ((impl.flags_field & PUBLIC) == 0) {
+                    log.error(implName.pos(), Errors.NotDefPublic(impl, impl.location()));
+                }
                 //find provider factory:
                 MethodSymbol factory = factoryMethod(impl);
                 if (factory != null) {
@@ -1594,8 +1669,8 @@
     }
 
     public void newRound() {
+        allModules = null;
         rootModules = null;
-        allModules = null;
         warnedMissing.clear();
     }
 }
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/comp/Resolve.java	Thu Mar 16 20:47:03 2017 +0000
@@ -307,6 +307,11 @@
         if (env.enclMethod != null && (env.enclMethod.mods.flags & ANONCONSTR) != 0)
             return true;
 
+        if (env.info.visitingServiceImplementation &&
+            env.toplevel.modle == c.packge().modle) {
+            return true;
+        }
+
         boolean isAccessible = false;
         switch ((short)(c.flags() & AccessFlags)) {
             case PRIVATE:
@@ -389,6 +394,11 @@
         if (env.enclMethod != null && (env.enclMethod.mods.flags & ANONCONSTR) != 0)
             return true;
 
+        if (env.info.visitingServiceImplementation &&
+            env.toplevel.modle == sym.packge().modle) {
+            return true;
+        }
+
         switch ((short)(sym.flags() & AccessFlags)) {
         case PRIVATE:
             return
@@ -2094,7 +2104,7 @@
 
         for (S sym : candidates) {
             if (validate.test(sym))
-                return new InvisibleSymbolError(env, suppressError, sym);
+                return createInvisibleSymbolError(env, suppressError, sym);
         }
 
         Set<ModuleSymbol> recoverableModules = new HashSet<>(syms.getAllModules());
@@ -2113,7 +2123,7 @@
                     S sym = load.apply(ms, name);
 
                     if (sym != null && validate.test(sym)) {
-                        return new InvisibleSymbolError(env, suppressError, sym);
+                        return createInvisibleSymbolError(env, suppressError, sym);
                     }
                 }
             }
@@ -2122,6 +2132,21 @@
         return defaultResult;
     }
 
+    private Symbol createInvisibleSymbolError(Env<AttrContext> env, boolean suppressError, Symbol sym) {
+        if (symbolPackageVisible(env, sym)) {
+            return new AccessError(env, null, sym);
+        } else {
+            return new InvisibleSymbolError(env, suppressError, sym);
+        }
+    }
+
+    private boolean symbolPackageVisible(Env<AttrContext> env, Symbol sym) {
+        ModuleSymbol envMod = env.toplevel.modle;
+        PackageSymbol symPack = sym.packge();
+        return envMod == symPack.modle ||
+               envMod.visiblePackages.containsKey(symPack.fullname);
+    }
+
     /**
      * Find a type declared in a scope (not inherited).  Return null
      * if none is found.
@@ -4094,8 +4119,7 @@
                             pos, "not.def.access.package.cant.access",
                         sym, sym.location(), inaccessiblePackageReason(env, sym.packge()));
                 } else if (   sym.packge() != syms.rootPackage
-                           && sym.packge().modle != env.toplevel.modle
-                           && !isAccessible(env, sym.outermostClass())) {
+                           && !symbolPackageVisible(env, sym)) {
                     return diags.create(dkind, log.currentSource(),
                             pos, "not.def.access.class.intf.cant.access.reason",
                             sym, sym.location(), sym.location().packge(),
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/JavacFileManager.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/JavacFileManager.java	Thu Mar 16 20:47:03 2017 +0000
@@ -968,7 +968,7 @@
             Collection<Path> paths = locations.getLocation(location);
             ModuleFinder finder = ModuleFinder.of(paths.toArray(new Path[paths.size()]));
             Layer bootLayer = Layer.boot();
-            Configuration cf = bootLayer.configuration().resolveRequiresAndUses(ModuleFinder.of(), finder, Collections.emptySet());
+            Configuration cf = bootLayer.configuration().resolveAndBind(ModuleFinder.of(), finder, Collections.emptySet());
             Layer layer = bootLayer.defineModulesWithOneLoader(cf, ClassLoader.getSystemClassLoader());
             return ServiceLoaderHelper.load(layer, service);
         } else {
@@ -980,7 +980,7 @@
     public Location getLocationForModule(Location location, JavaFileObject fo, String pkgName) throws IOException {
         checkModuleOrientedOrOutputLocation(location);
         if (!(fo instanceof PathFileObject))
-            throw new IllegalArgumentException(fo.getName());
+            return null;
         int depth = 1; // allow 1 for filename
         if (pkgName != null && !pkgName.isEmpty()) {
             depth += 1;
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/file/Locations.java	Thu Mar 16 20:47:03 2017 +0000
@@ -432,7 +432,7 @@
         /**
          * @see JavaFileManager#getLocationForModule(Location, JavaFileObject, String)
          */
-        Location getLocationForModule(Path dir) {
+        Location getLocationForModule(Path dir) throws IOException  {
             return null;
         }
 
@@ -545,7 +545,7 @@
                 l = new ModuleLocationHandler(location.getName() + "[" + name + "]",
                         name,
                         Collections.singleton(out),
-                        true, false);
+                        true);
                 moduleLocations.put(name, l);
                 pathLocations.put(out.toAbsolutePath(), l);
            }
@@ -864,29 +864,14 @@
         protected final String name;
         protected final String moduleName;
         protected final Collection<Path> searchPath;
-        protected final Collection<Path> searchPathWithOverrides;
         protected final boolean output;
 
         ModuleLocationHandler(String name, String moduleName, Collection<Path> searchPath,
-                boolean output, boolean allowOverrides) {
+                boolean output) {
             this.name = name;
             this.moduleName = moduleName;
             this.searchPath = searchPath;
             this.output = output;
-
-            if (allowOverrides && patchMap != null) {
-                SearchPath mPatch = patchMap.get(moduleName);
-                if (mPatch != null) {
-                    SearchPath sp = new SearchPath();
-                    sp.addAll(mPatch);
-                    sp.addAll(searchPath);
-                    searchPathWithOverrides = sp;
-                } else {
-                    searchPathWithOverrides = searchPath;
-                }
-            } else {
-                searchPathWithOverrides = searchPath;
-            }
         }
 
         @Override @DefinedBy(Api.COMPILER)
@@ -909,7 +894,7 @@
             // For now, we always return searchPathWithOverrides. This may differ from the
             // JVM behavior if there is a module-info.class to be found in the overriding
             // classes.
-            return searchPathWithOverrides;
+            return searchPath;
         }
 
         @Override // defined by LocationHandler
@@ -985,6 +970,11 @@
         }
 
         private void checkValidModulePathEntry(Path p) {
+            if (!Files.exists(p)) {
+                // warning may be generated later
+                return;
+            }
+
             if (Files.isDirectory(p)) {
                 // either an exploded module or a directory of modules
                 return;
@@ -1063,7 +1053,7 @@
                         String name = location.getName()
                                 + "[" + pathIndex + ":" + moduleName + "]";
                         ModuleLocationHandler l = new ModuleLocationHandler(name, moduleName,
-                                Collections.singleton(path), false, true);
+                                Collections.singleton(path), false);
                         return Collections.singleton(l);
                     } catch (ModuleNameReader.BadClassFile e) {
                         log.error(Errors.LocnBadModuleInfo(path));
@@ -1088,7 +1078,7 @@
                     String name = location.getName()
                             + "[" + pathIndex + "." + (index++) + ":" + moduleName + "]";
                     ModuleLocationHandler l = new ModuleLocationHandler(name, moduleName,
-                            Collections.singleton(modulePath), false, true);
+                            Collections.singleton(modulePath), false);
                     result.add(l);
                 }
                 return result;
@@ -1105,7 +1095,7 @@
                 String name = location.getName()
                         + "[" + pathIndex + ":" + moduleName + "]";
                 ModuleLocationHandler l = new ModuleLocationHandler(name, moduleName,
-                        Collections.singleton(modulePath), false, true);
+                        Collections.singleton(modulePath), false);
                 return Collections.singleton(l);
             }
 
@@ -1272,7 +1262,7 @@
             pathLocations = new LinkedHashMap<>();
             map.forEach((k, v) -> {
                 String name = location.getName() + "[" + k + "]";
-                ModuleLocationHandler h = new ModuleLocationHandler(name, k, v, false, false);
+                ModuleLocationHandler h = new ModuleLocationHandler(name, k, v, false);
                 moduleLocations.put(k, h);
                 v.forEach(p -> pathLocations.put(normalize(p), h));
             });
@@ -1412,6 +1402,7 @@
         private Path systemJavaHome;
         private Path modules;
         private Map<String, ModuleLocationHandler> systemModules;
+        private Map<Path, Location> pathLocations;
 
         SystemModulesLocationHandler() {
             super(StandardLocation.SYSTEM_MODULES, Option.SYSTEM);
@@ -1486,6 +1477,12 @@
         }
 
         @Override
+        Location getLocationForModule(Path dir) throws IOException {
+            initSystemModules();
+            return (pathLocations == null) ? null : pathLocations.get(dir);
+        }
+
+        @Override
         Iterable<Set<Location>> listLocationsForModules() throws IOException {
             initSystemModules();
             Set<Location> locns = new LinkedHashSet<>();
@@ -1539,18 +1536,96 @@
             }
 
             systemModules = new LinkedHashMap<>();
+            pathLocations = new LinkedHashMap<>();
             try (DirectoryStream<Path> stream = Files.newDirectoryStream(modules, Files::isDirectory)) {
                 for (Path entry : stream) {
                     String moduleName = entry.getFileName().toString();
                     String name = location.getName() + "[" + moduleName + "]";
                     ModuleLocationHandler h = new ModuleLocationHandler(name, moduleName,
-                            Collections.singleton(entry), false, true);
+                            Collections.singleton(entry), false);
                     systemModules.put(moduleName, h);
+                    pathLocations.put(normalize(entry), h);
                 }
             }
         }
     }
 
+    private class PatchModulesLocationHandler extends BasicLocationHandler {
+        private final Map<String, ModuleLocationHandler> moduleLocations = new HashMap<>();
+        private final Map<Path, Location> pathLocations = new HashMap<>();
+
+        PatchModulesLocationHandler() {
+            super(StandardLocation.PATCH_MODULE_PATH, Option.PATCH_MODULE);
+        }
+
+        @Override
+        boolean handleOption(Option option, String value) {
+            if (!options.contains(option)) {
+                return false;
+            }
+
+            // Allow an extended syntax for --patch-module consisting of a series
+            // of values separated by NULL characters. This is to facilitate
+            // supporting deferred file manager options on the command line.
+            // See Option.PATCH_MODULE for the code that composes these multiple
+            // values.
+            for (String v : value.split("\0")) {
+                int eq = v.indexOf('=');
+                if (eq > 0) {
+                    String moduleName = v.substring(0, eq);
+                    SearchPath mPatchPath = new SearchPath()
+                            .addFiles(v.substring(eq + 1));
+                    String name = location.getName() + "[" + moduleName + "]";
+                    ModuleLocationHandler h = new ModuleLocationHandler(name, moduleName, mPatchPath, false);
+                    moduleLocations.put(moduleName, h);
+                    for (Path r : mPatchPath) {
+                        pathLocations.put(normalize(r), h);
+                    }
+                } else {
+                    // Should not be able to get here;
+                    // this should be caught and handled in Option.PATCH_MODULE
+                    log.error(Errors.LocnInvalidArgForXpatch(value));
+                }
+            }
+
+            return true;
+        }
+
+        @Override
+        boolean isSet() {
+            return !moduleLocations.isEmpty();
+        }
+
+        @Override
+        Collection<Path> getPaths() {
+            throw new UnsupportedOperationException();
+        }
+
+        @Override
+        void setPaths(Iterable<? extends Path> files) throws IOException {
+            throw new UnsupportedOperationException();
+        }
+
+        @Override
+        Location getLocationForModule(String name) throws IOException {
+            return moduleLocations.get(name);
+        }
+
+        @Override
+        Location getLocationForModule(Path dir) throws IOException {
+            return (pathLocations == null) ? null : pathLocations.get(dir);
+        }
+
+        @Override
+        Iterable<Set<Location>> listLocationsForModules() throws IOException {
+            Set<Location> locns = new LinkedHashSet<>();
+            for (Location l: moduleLocations.values())
+                locns.add(l);
+            return Collections.singleton(locns);
+        }
+
+    }
+
     Map<Location, LocationHandler> handlersForLocation;
     Map<Option, LocationHandler> handlersForOption;
 
@@ -1568,6 +1643,7 @@
             new OutputLocationHandler(StandardLocation.SOURCE_OUTPUT, Option.S),
             new OutputLocationHandler(StandardLocation.NATIVE_HEADER_OUTPUT, Option.H),
             new ModuleSourcePathLocationHandler(),
+            new PatchModulesLocationHandler(),
             // TODO: should UPGRADE_MODULE_PATH be merged with SYSTEM_MODULES?
             new ModulePathLocationHandler(StandardLocation.UPGRADE_MODULE_PATH, Option.UPGRADE_MODULE_PATH),
             new ModulePathLocationHandler(StandardLocation.MODULE_PATH, Option.MODULE_PATH),
@@ -1582,51 +1658,9 @@
         }
     }
 
-    private Map<String, SearchPath> patchMap;
-
     boolean handleOption(Option option, String value) {
-        switch (option) {
-            case PATCH_MODULE:
-                if (value == null) {
-                    patchMap = null;
-                } else {
-                    // Allow an extended syntax for --patch-module consisting of a series
-                    // of values separated by NULL characters. This is to facilitate
-                    // supporting deferred file manager options on the command line.
-                    // See Option.PATCH_MODULE for the code that composes these multiple
-                    // values.
-                    for (String v : value.split("\0")) {
-                        int eq = v.indexOf('=');
-                        if (eq > 0) {
-                            String mName = v.substring(0, eq);
-                            SearchPath mPatchPath = new SearchPath()
-                                    .addFiles(v.substring(eq + 1));
-                            boolean ok = true;
-                            for (Path p : mPatchPath) {
-                                Path mi = p.resolve("module-info.class");
-                                if (Files.exists(mi)) {
-                                    log.error(Errors.LocnModuleInfoNotAllowedOnPatchPath(mi));
-                                    ok = false;
-                                }
-                            }
-                            if (ok) {
-                                if (patchMap == null) {
-                                    patchMap = new LinkedHashMap<>();
-                                }
-                                patchMap.put(mName, mPatchPath);
-                            }
-                        } else {
-                            // Should not be able to get here;
-                            // this should be caught and handled in Option.PATCH_MODULE
-                            log.error(Errors.LocnInvalidArgForXpatch(value));
-                        }
-                    }
-                }
-                return true;
-            default:
-                LocationHandler h = handlersForOption.get(option);
-                return (h == null ? false : h.handleOption(option, value));
-        }
+        LocationHandler h = handlersForOption.get(option);
+        return (h == null ? false : h.handleOption(option, value));
     }
 
     boolean hasLocation(Location location) {
@@ -1665,7 +1699,7 @@
         return (h == null ? null : h.getLocationForModule(name));
     }
 
-    Location getLocationForModule(Location location, Path dir) {
+    Location getLocationForModule(Location location, Path dir) throws IOException {
         LocationHandler h = getHandler(location);
         return (h == null ? null : h.getLocationForModule(dir));
     }
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Gen.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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,7 +38,6 @@
 import com.sun.tools.javac.code.Type.*;
 import com.sun.tools.javac.jvm.Code.*;
 import com.sun.tools.javac.jvm.Items.*;
-import com.sun.tools.javac.main.Option;
 import com.sun.tools.javac.tree.EndPosTable;
 import com.sun.tools.javac.tree.JCTree.*;
 
@@ -67,10 +66,9 @@
     private final TreeMaker make;
     private final Names names;
     private final Target target;
-    private Name accessDollar;
+    private final Name accessDollar;
     private final Types types;
     private final Lower lower;
-    private final Flow flow;
     private final Annotate annotate;
     private final StringConcat concat;
 
@@ -95,7 +93,7 @@
 
     /** Constant pool, reset by genClass.
      */
-    private Pool pool;
+    private final Pool pool;
 
     protected Gen(Context context) {
         context.put(genKey, this);
@@ -113,7 +111,6 @@
         methodType = new MethodType(null, null, null, syms.methodClass);
         accessDollar = names.
             fromString("access" + target.syntheticNameChar());
-        flow = Flow.instance(context);
         lower = Lower.instance(context);
 
         Options options = Options.instance(context);
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Profile.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Profile.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2013, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, 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
@@ -40,9 +40,9 @@
  *  deletion without notice.</b>
  */
 public enum Profile {
-    COMPACT1("compact1", 1, Target.JDK1_8, Target.JDK1_9),
-    COMPACT2("compact2", 2, Target.JDK1_8, Target.JDK1_9),
-    COMPACT3("compact3", 3, Target.JDK1_8, Target.JDK1_9),
+    COMPACT1("compact1", 1, Target.JDK1_8, Target.JDK1_9, Target.JDK1_10),
+    COMPACT2("compact2", 2, Target.JDK1_8, Target.JDK1_9, Target.JDK1_10),
+    COMPACT3("compact3", 3, Target.JDK1_8, Target.JDK1_9, Target.JDK1_10),
 
     DEFAULT {
         @Override
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Target.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/jvm/Target.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2017, 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
@@ -61,7 +61,10 @@
     JDK1_8("1.8", 52, 0),
 
     /** JDK 9. */
-    JDK1_9("1.9", 53, 0);
+    JDK1_9("1.9", 53, 0),
+
+    /** JDK 10, initially an alias for 9 */
+    JDK1_10("1.10", 53, 0);
 
     private static final Context.Key<Target> targetKey = new Context.Key<>();
 
@@ -91,6 +94,7 @@
         tab.put("7", JDK1_7);
         tab.put("8", JDK1_8);
         tab.put("9", JDK1_9);
+        tab.put("10", JDK1_10);
     }
 
     public final String name;
@@ -102,7 +106,7 @@
         this.minorVersion = minorVersion;
     }
 
-    public static final Target DEFAULT = JDK1_9;
+    public static final Target DEFAULT = values()[values().length - 1];
 
     public static Target lookup(String name) {
         return tab.get(name);
@@ -146,5 +150,4 @@
     public String multiReleaseValue() {
         return Integer.toString(this.ordinal() - Target.JDK1_1.ordinal() + 1);
     }
-
 }
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Arguments.java	Thu Mar 16 20:47:03 2017 +0000
@@ -598,9 +598,6 @@
                     && !fm.hasLocation(StandardLocation.CLASS_OUTPUT)) {
                 log.error(Errors.NoOutputDir);
             }
-            if (options.isSet(Option.XMODULE)) {
-                log.error(Errors.XmoduleNoModuleSourcepath);
-            }
         }
 
         if (fm.hasLocation(StandardLocation.ANNOTATION_PROCESSOR_MODULE_PATH) &&
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/CommandLine.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/CommandLine.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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
@@ -29,8 +29,9 @@
 import java.io.Reader;
 import java.nio.file.Files;
 import java.nio.file.Paths;
-
-import com.sun.tools.javac.util.ListBuffer;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.List;
 
 /**
  * Various utility methods for processing Java tool command line arguments.
@@ -55,28 +56,80 @@
      * @throws IOException if there is a problem reading any of the @files
      */
     public static String[] parse(String[] args) throws IOException {
-        ListBuffer<String> newArgs = new ListBuffer<>();
+        List<String> newArgs = new ArrayList<>();
+        appendParsedCommandArgs(newArgs, Arrays.asList(args));
+        return newArgs.toArray(new String[newArgs.size()]);
+    }
+
+    private static void appendParsedCommandArgs(List<String> newArgs, List<String> args) throws IOException {
         for (String arg : args) {
             if (arg.length() > 1 && arg.charAt(0) == '@') {
                 arg = arg.substring(1);
                 if (arg.charAt(0) == '@') {
-                    newArgs.append(arg);
+                    newArgs.add(arg);
                 } else {
                     loadCmdFile(arg, newArgs);
                 }
             } else {
-                newArgs.append(arg);
+                newArgs.add(arg);
             }
         }
-        return newArgs.toList().toArray(new String[newArgs.length()]);
     }
 
-    private static void loadCmdFile(String name, ListBuffer<String> args) throws IOException {
+    /**
+     * Process the given environment variable and appends any Win32-style
+     * command files for the specified command line arguments and return
+     * the resulting arguments. A command file argument
+     * is of the form '@file' where 'file' is the name of the file whose
+     * contents are to be parsed for additional arguments. The contents of
+     * the command file are parsed using StreamTokenizer and the original
+     * '@file' argument replaced with the resulting tokens. Recursive command
+     * files are not supported. The '@' character itself can be quoted with
+     * the sequence '@@'.
+     * @param envVariable the env variable to process
+     * @param args the arguments that may contain @files
+     * @return the arguments, with environment variable's content and expansion of @files
+     * @throws IOException if there is a problem reading any of the @files
+     * @throws com.sun.tools.javac.main.CommandLine.UnmatchedQuote
+     */
+    public static List<String> parse(String envVariable, List<String> args)
+            throws IOException, UnmatchedQuote {
+
+        List<String> inArgs = new ArrayList<>();
+        appendParsedEnvVariables(inArgs, envVariable);
+        inArgs.addAll(args);
+        List<String> newArgs = new ArrayList<>();
+        appendParsedCommandArgs(newArgs, inArgs);
+        return newArgs;
+    }
+
+    /**
+     * Process the given environment variable and appends any Win32-style
+     * command files for the specified command line arguments and return
+     * the resulting arguments. A command file argument
+     * is of the form '@file' where 'file' is the name of the file whose
+     * contents are to be parsed for additional arguments. The contents of
+     * the command file are parsed using StreamTokenizer and the original
+     * '@file' argument replaced with the resulting tokens. Recursive command
+     * files are not supported. The '@' character itself can be quoted with
+     * the sequence '@@'.
+     * @param envVariable the env variable to process
+     * @param args the arguments that may contain @files
+     * @return the arguments, with environment variable's content and expansion of @files
+     * @throws IOException if there is a problem reading any of the @files
+     * @throws com.sun.tools.javac.main.CommandLine.UnmatchedQuote
+     */
+    public static String[] parse(String envVariable, String[] args) throws IOException, UnmatchedQuote {
+        List<String> out = parse(envVariable, Arrays.asList(args));
+        return out.toArray(new String[out.size()]);
+    }
+
+    private static void loadCmdFile(String name, List<String> args) throws IOException {
         try (Reader r = Files.newBufferedReader(Paths.get(name))) {
             Tokenizer t = new Tokenizer(r);
             String s;
             while ((s = t.nextToken()) != null) {
-                args.append(s);
+                args.add(s);
             }
         }
     }
@@ -188,4 +241,75 @@
             }
         }
     }
+
+    @SuppressWarnings("fallthrough")
+    private static void appendParsedEnvVariables(List<String> newArgs, String envVariable)
+            throws UnmatchedQuote {
+
+        if (envVariable == null) {
+            return;
+        }
+        String in = System.getenv(envVariable);
+        if (in == null || in.trim().isEmpty()) {
+            return;
+        }
+
+        final char NUL = (char)0;
+        final int len = in.length();
+
+        int pos = 0;
+        StringBuilder sb = new StringBuilder();
+        char quote = NUL;
+        char ch;
+
+        loop:
+        while (pos < len) {
+            ch = in.charAt(pos);
+            switch (ch) {
+                case '\"': case '\'':
+                    if (quote == NUL) {
+                        quote = ch;
+                    } else if (quote == ch) {
+                        quote = NUL;
+                    } else {
+                        sb.append(ch);
+                    }
+                    pos++;
+                    break;
+                case '\f': case '\n': case '\r': case '\t': case ' ':
+                    if (quote == NUL) {
+                        newArgs.add(sb.toString());
+                        sb.setLength(0);
+                        while (ch == '\f' || ch == '\n' || ch == '\r' || ch == '\t' || ch == ' ') {
+                            pos++;
+                            if (pos >= len) {
+                                break loop;
+                            }
+                            ch = in.charAt(pos);
+                        }
+                        break;
+                    }
+                    // fall through
+                default:
+                    sb.append(ch);
+                    pos++;
+            }
+        }
+        if (sb.length() != 0) {
+            newArgs.add(sb.toString());
+        }
+        if (quote != NUL) {
+            throw new UnmatchedQuote(envVariable);
+        }
+    }
+
+    public static class UnmatchedQuote extends Exception {
+        private static final long serialVersionUID = 0;
+
+        public final String variableName;
+
+        UnmatchedQuote(String variable) {
+            this.variableName = variable;
+        }
+    }
 }
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/JavaCompiler.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/JavaCompiler.java	Thu Mar 16 20:47:03 2017 +0000
@@ -888,7 +888,7 @@
 
     public void compile(List<JavaFileObject> sourceFileObject)
         throws Throwable {
-        compile(sourceFileObject, List.nil(), null);
+        compile(sourceFileObject, List.nil(), null, List.nil());
     }
 
     /**
@@ -898,10 +898,13 @@
      * @param classnames class names to process for annotations
      * @param processors user provided annotation processors to bypass
      * discovery, {@code null} means that no processors were provided
+     * @param addModules additional root modules to be used during
+     * module resolution.
      */
     public void compile(Collection<JavaFileObject> sourceFileObjects,
                         Collection<String> classnames,
-                        Iterable<? extends Processor> processors)
+                        Iterable<? extends Processor> processors,
+                        Collection<String> addModules)
     {
         if (!taskListener.isEmpty()) {
             taskListener.started(new TaskEvent(TaskEvent.Kind.COMPILATION));
@@ -932,6 +935,10 @@
                 }
             }
 
+            for (String moduleName : addModules) {
+                modules.addExtraAddModules(moduleName);
+            }
+
             // These method calls must be chained to avoid memory leaks
             processAnnotations(
                 enterTrees(
@@ -1450,6 +1457,11 @@
             return;
         }
 
+        if (!modules.multiModuleMode && env.toplevel.modle != modules.getDefaultModule()) {
+            //can only generate classfiles for a single module:
+            return;
+        }
+
         if (compileStates.isDone(env, CompileState.LOWER)) {
             results.addAll(desugaredEnvs.get(env));
             return;
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Main.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Main.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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
@@ -43,6 +43,7 @@
 import com.sun.tools.javac.file.BaseFileManager;
 import com.sun.tools.javac.file.JavacFileManager;
 import com.sun.tools.javac.jvm.Target;
+import com.sun.tools.javac.main.CommandLine.UnmatchedQuote;
 import com.sun.tools.javac.platform.PlatformDescription;
 import com.sun.tools.javac.processing.AnnotationProcessingError;
 import com.sun.tools.javac.util.*;
@@ -80,6 +81,7 @@
      */
     boolean apiMode;
 
+    private static final String ENV_OPT_NAME = "JDK_JAVAC_OPTIONS";
 
     /** Result codes.
      */
@@ -201,19 +203,12 @@
             return Result.CMDERR;
         }
 
-        // prefix argv with contents of _JAVAC_OPTIONS if set
-        String envOpt = System.getenv("_JAVAC_OPTIONS");
-        if (envOpt != null && !envOpt.trim().isEmpty()) {
-            String[] envv = envOpt.split("\\s+");
-            String[] result = new String[envv.length + argv.length];
-            System.arraycopy(envv, 0, result, 0, envv.length);
-            System.arraycopy(argv, 0, result, envv.length, argv.length);
-            argv = result;
-        }
-
-        // expand @-files
+        // prefix argv with contents of environment variable and expand @-files
         try {
-            argv = CommandLine.parse(argv);
+            argv = CommandLine.parse(ENV_OPT_NAME, argv);
+        } catch (UnmatchedQuote ex) {
+            error("err.unmatched.quote", ex.variableName);
+            return Result.CMDERR;
         } catch (FileNotFoundException | NoSuchFileException e) {
             warning("err.file.not.found", e.getMessage());
             return Result.SYSERR;
@@ -304,7 +299,7 @@
         }
 
         try {
-            comp.compile(args.getFileObjects(), args.getClassNames(), null);
+            comp.compile(args.getFileObjects(), args.getClassNames(), null, List.nil());
 
             if (log.expectDiagKeys != null) {
                 if (log.expectDiagKeys.isEmpty()) {
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/main/Option.java	Thu Mar 16 20:47:03 2017 +0000
@@ -579,7 +579,7 @@
         }
     },
 
-    XMODULE("-Xmodule:", "opt.arg.module", "opt.module", EXTENDED, BASIC) {
+    XMODULE("-Xmodule:", "opt.arg.module", "opt.module", HIDDEN, BASIC) {
         @Override
         public void process(OptionHelper helper, String option, String arg) throws InvalidValueException {
             String prev = helper.get(XMODULE);
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/model/JavacElements.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/model/JavacElements.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,7 @@
 
 package com.sun.tools.javac.model;
 
+import java.util.Collections;
 import java.util.HashSet;
 import java.util.LinkedHashSet;
 import java.util.Map;
@@ -117,6 +118,14 @@
     }
 
     @Override @DefinedBy(Api.LANGUAGE_MODEL)
+    public Set<? extends ModuleElement> getAllModuleElements() {
+        if (allowModules)
+            return Collections.unmodifiableSet(modules.allModules());
+        else
+            return Collections.emptySet();
+    }
+
+    @Override @DefinedBy(Api.LANGUAGE_MODEL)
     public ModuleSymbol getModuleElement(CharSequence name) {
         ensureEntered("getModuleElement");
         if (modules.getDefaultModule() == syms.noModule)
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/platform/JDKPlatformProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/platform/JDKPlatformProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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
@@ -90,6 +90,8 @@
             } catch (IOException | ProviderNotFoundException ex) {
             }
         }
+        // Workaround until full support for --release 9 distinct from --release 10
+        SUPPORTED_JAVA_PLATFORM_VERSIONS.add(targetNumericVersion(Target.JDK1_9));
         SUPPORTED_JAVA_PLATFORM_VERSIONS.add(targetNumericVersion(Target.DEFAULT));
     }
 
@@ -108,7 +110,9 @@
 
         @Override
         public Collection<Path> getPlatformPath() {
-            if (Target.lookup(version) == Target.DEFAULT) {
+            // Comparison should be == Target.DEFAULT once --release 9
+            // is distinct from 10
+            if (Target.lookup(version).compareTo(Target.JDK1_9)  >=  0) {
                 return null;
             }
 
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/PrintingProcessor.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/processing/PrintingProcessor.java	Thu Mar 16 20:47:03 2017 +0000
@@ -55,7 +55,7 @@
  * deletion without notice.</b>
  */
 @SupportedAnnotationTypes("*")
-@SupportedSourceVersion(SourceVersion.RELEASE_9)
+@SupportedSourceVersion(SourceVersion.RELEASE_10)
 public class PrintingProcessor extends AbstractProcessor {
     PrintWriter writer;
 
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/compiler.properties	Thu Mar 16 20:47:03 2017 +0000
@@ -915,6 +915,10 @@
     {0} is not public in {1}; cannot be accessed from outside package
 
 # 0: symbol, 1: symbol
+compiler.err.not.def.public=\
+    {0} is not public in {1}
+
+# 0: symbol, 1: symbol
 compiler.misc.not.def.public.cant.access=\
     {0} is not public in {1}; cannot be accessed from outside package
 
@@ -1246,9 +1250,9 @@
 
 # In the following string, {0} is the name of the class in the Java source.
 # It really should be used two times..
-# 0: name
+# 0: kind name, 1: name
 compiler.err.class.public.should.be.in.file=\
-    class {0} is public, should be declared in a file named {0}.java
+    {0} {1} is public, should be declared in a file named {1}.java
 
 ## All errors which do not refer to a particular line in the source code are
 ## preceded by this string.
@@ -1292,7 +1296,7 @@
 compiler.warn.outdir.is.in.exploded.module=\
     the output directory is within an exploded module: {0}
 
-# 0: path
+# 0: file object
 compiler.err.locn.module-info.not.allowed.on.patch.path=\
     module-info.class not allowed on patch path: {0}
 
@@ -1438,7 +1442,7 @@
 
 # 0: string, 1: string, 2: string
 compiler.note.multiple.elements=\
-    Multiple elements named '{1}' in modules '{2}' were found by javax.lang.model.util.Elements.{0}.
+    Multiple elements named ''{1}'' in modules ''{2}'' were found by javax.lang.model.util.Elements.{0}.
 
 #####
 
@@ -2957,14 +2961,20 @@
 compiler.err.module.decl.sb.in.module-info.java=\
     module declarations should be in a file named module-info.java
 
-compiler.err.module-info.with.xmodule.sourcepath=\
-    illegal combination of -Xmodule and module-info on sourcepath
-
-compiler.err.module-info.with.xmodule.classpath=\
-    illegal combination of -Xmodule and module-info on classpath
-
-compiler.err.xmodule.no.module.sourcepath=\
-    illegal combination of -Xmodule and --module-source-path
+compiler.err.module-info.with.patched.module.sourcepath=\
+    compiling a module patch with module-info on sourcepath
+
+compiler.err.module-info.with.patched.module.classoutput=\
+    compiling a module patch with module-info on class output
+
+# 0: set of string
+compiler.err.too.many.patched.modules=\
+    too many patched modules ({0}), use --module-source-path
+
+# 0: name, 1: name
+compiler.err.file.patched.and.msp=\
+    file accessible from both --patch-module and --module-source-path, \
+    but belongs to a different module on each path: {0}, {1}
 
 compiler.err.processorpath.no.processormodulepath=\
     illegal combination of -processorpath and --processor-module-path
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/javac.properties	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/resources/javac.properties	Thu Mar 16 20:47:03 2017 +0000
@@ -377,6 +377,9 @@
 javac.err.repeated.value.for.patch.module=\
     --patch-module specified more than once for {0}
 
+javac.err.unmatched.quote=\
+    unmatched quote in environment variable %s
+
 ## messages
 
 javac.msg.usage.header=\
--- a/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/util/JDK9Wrappers.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/com/sun/tools/javac/util/JDK9Wrappers.java	Thu Mar 16 20:47:03 2017 +0000
@@ -272,12 +272,12 @@
             init();
         }
 
-        public Configuration resolveRequiresAndUses(
+        public Configuration resolveAndBind(
                 ModuleFinder beforeFinder,
                 ModuleFinder afterFinder,
                 Collection<String> roots) {
             try {
-                Object result = resolveRequiresAndUsesMethod.invoke(theRealConfiguration,
+                Object result = resolveAndBindMethod.invoke(theRealConfiguration,
                                     beforeFinder.theRealModuleFinder,
                                     afterFinder.theRealModuleFinder,
                                     roots
@@ -293,7 +293,7 @@
         // -----------------------------------------------------------------------------------------
 
         private static Class<?> configurationClass = null;
-        private static Method resolveRequiresAndUsesMethod;
+        private static Method resolveAndBindMethod;
 
         static final Class<?> getConfigurationClass() {
             init();
@@ -305,7 +305,7 @@
                 try {
                     configurationClass = Class.forName("java.lang.module.Configuration", false, null);
                     Class<?> moduleFinderInterface = ModuleFinder.getModuleFinderClass();
-                    resolveRequiresAndUsesMethod = configurationClass.getDeclaredMethod("resolveRequiresAndUses",
+                    resolveAndBindMethod = configurationClass.getDeclaredMethod("resolveAndBind",
                                 moduleFinderInterface,
                                 moduleFinderInterface,
                                 Collection.class
--- a/langtools/src/jdk.compiler/share/classes/jdk/internal/shellsupport/doc/JavadocHelper.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/jdk/internal/shellsupport/doc/JavadocHelper.java	Thu Mar 16 20:47:03 2017 +0000
@@ -49,12 +49,15 @@
 import javax.lang.model.element.Element;
 import javax.lang.model.element.ElementKind;
 import javax.lang.model.element.ExecutableElement;
+import javax.lang.model.element.ModuleElement;
 import javax.lang.model.element.TypeElement;
 import javax.lang.model.element.VariableElement;
 import javax.lang.model.type.DeclaredType;
 import javax.lang.model.type.TypeKind;
 import javax.lang.model.type.TypeMirror;
 import javax.lang.model.util.ElementFilter;
+import javax.lang.model.util.Elements;
+import javax.tools.ForwardingJavaFileManager;
 import javax.tools.JavaCompiler;
 import javax.tools.JavaFileManager;
 import javax.tools.JavaFileObject;
@@ -542,8 +545,13 @@
             if (type == null)
                 return null;
 
-            String binaryName = origin.getElements().getBinaryName(type).toString();
-            Pair<JavacTask, CompilationUnitTree> source = findSource(binaryName);
+            Elements elements = origin.getElements();
+            String binaryName = elements.getBinaryName(type).toString();
+            ModuleElement module = elements.getModuleOf(type);
+            String moduleName = module == null || module.isUnnamed()
+                    ? null
+                    : module.getQualifiedName().toString();
+            Pair<JavacTask, CompilationUnitTree> source = findSource(moduleName, binaryName);
 
             if (source == null)
                 return null;
@@ -636,7 +644,8 @@
                 }.scan(cut, null);
             }
 
-        private Pair<JavacTask, CompilationUnitTree> findSource(String binaryName) throws IOException {
+        private Pair<JavacTask, CompilationUnitTree> findSource(String moduleName,
+                                                                String binaryName) throws IOException {
             JavaFileObject jfo = fm.getJavaFileForInput(StandardLocation.SOURCE_PATH,
                                                         binaryName,
                                                         JavaFileObject.Kind.SOURCE);
@@ -645,7 +654,10 @@
                 return null;
 
             List<JavaFileObject> jfos = Arrays.asList(jfo);
-            JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, baseFileManager, d -> {}, null, null, jfos);
+            JavaFileManager patchFM = moduleName != null
+                    ? new PatchModuleFileManager(baseFileManager, jfo, moduleName)
+                    : baseFileManager;
+            JavacTaskImpl task = (JavacTaskImpl) compiler.getTask(null, patchFM, d -> {}, null, null, jfos);
             Iterable<? extends CompilationUnitTree> cuts = task.parse();
 
             task.enter();
@@ -657,6 +669,61 @@
         public void close() throws IOException {
             fm.close();
         }
+
+        private static final class PatchModuleFileManager
+                extends ForwardingJavaFileManager<JavaFileManager> {
+
+            private final JavaFileObject file;
+            private final String moduleName;
+
+            public PatchModuleFileManager(JavaFileManager fileManager,
+                                          JavaFileObject file,
+                                          String moduleName) {
+                super(fileManager);
+                this.file = file;
+                this.moduleName = moduleName;
+            }
+
+            @Override @DefinedBy(Api.COMPILER)
+            public Location getLocationForModule(Location location,
+                                                 JavaFileObject fo,
+                                                 String pkgName) throws IOException {
+                return fo == file
+                        ? PATCH_LOCATION
+                        : super.getLocationForModule(location, fo, pkgName);
+            }
+
+            @Override @DefinedBy(Api.COMPILER)
+            public String inferModuleName(Location location) throws IOException {
+                return location == PATCH_LOCATION
+                        ? moduleName
+                        : super.inferModuleName(location);
+            }
+
+            @Override @DefinedBy(Api.COMPILER)
+            public boolean hasLocation(Location location) {
+                return location == StandardLocation.PATCH_MODULE_PATH ||
+                       super.hasLocation(location);
+            }
+
+            private static final Location PATCH_LOCATION = new Location() {
+                @Override @DefinedBy(Api.COMPILER)
+                public String getName() {
+                    return "PATCH_LOCATION";
+                }
+
+                @Override @DefinedBy(Api.COMPILER)
+                public boolean isOutputLocation() {
+                    return false;
+                }
+
+                @Override @DefinedBy(Api.COMPILER)
+                public boolean isModuleOrientedLocation() {
+                    return false;
+                }
+
+            };
+        }
     }
 
 }
--- a/langtools/src/jdk.compiler/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.compiler/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,6 +26,8 @@
 /** Defines the implementation of the
  *  {@link javax.tools.ToolProvider#getSystemJavaCompiler system Java compiler}
  *  and its command line equivalent, <em>javac</em>, as well as <em>javah</em>.
+ *
+ *  @since 9
  */
 module jdk.compiler {
     requires transitive java.compiler;
--- a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/doclets/formats/html/HtmlDocletWriter.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1705,7 +1705,6 @@
         if (lessThanPos < 0) {
             return text;
         }
-
         StringBuilder result = new StringBuilder();
     main: while (lessThanPos != -1) {
             int currPos = lessThanPos + 1;
@@ -1740,17 +1739,16 @@
                     if (ch == '>' && quoteKind == null) {
                         foundGT = true;
                     }
-                    if (++currPos == len)
+                    if (++currPos == len) {
                         break;
+                    }
                     ch = text.charAt(currPos);
                 }
-                startPos = currPos + 1;
-                currPos = startPos;
+                startPos = currPos;
             }
             lessThanPos = text.indexOf('<', currPos);
         }
         result.append(text.substring(startPos));
-
         return result.toString();
     }
 
@@ -1760,10 +1758,6 @@
                 ('1' <= ch && ch <= '6');
     }
 
-    private static boolean isWhitespace(char ch) {
-        return Character.isWhitespace(ch);
-    }
-
     /**
      * Add a link to the stylesheet file.
      *
--- a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ToolOption.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/main/ToolOption.java	Thu Mar 16 20:47:03 2017 +0000
@@ -204,13 +204,6 @@
         }
     },
 
-    XMODULE("-Xmodule:", false) {
-        @Override
-        public void process(Helper helper, String arg) throws InvalidValueException {
-            Option.XMODULE.process(helper.getOptionHelper(), arg);
-        }
-    },
-
     PATCH_MODULE("--patch-module", true) {
         @Override
         public void process(Helper helper, String arg) throws InvalidValueException {
--- a/langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/resources/javadoc.properties	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/com/sun/tools/javadoc/resources/javadoc.properties	Thu Mar 16 20:47:03 2017 +0000
@@ -82,7 +82,6 @@
 \                                   Specify additional modules to be considered as required by a\n\
 \                                   given module. <other-module> may be ALL-UNNAMED to require\n\
 \                                   the unnamed module.\n\
-\  -Xmodule:<module-name>           Specify a module to which the classes being compiled belong.\n\
 \  --patch-module <module>=<file>(:<file>)*\n\
 \                                   Override or augment a module with classes and resources\n\
 \                                   in JAR files or directories\n
--- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/api/JavadocTaskImpl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/api/JavadocTaskImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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,15 +25,20 @@
 
 package jdk.javadoc.internal.api;
 
+import java.util.ArrayList;
 import java.util.Collections;
+import java.util.List;
 import java.util.Locale;
+import java.util.Objects;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 import javax.tools.DocumentationTool.DocumentationTask;
 import javax.tools.JavaFileObject;
 
+import com.sun.tools.javac.main.Option;
 import com.sun.tools.javac.util.ClientCodeException;
 import com.sun.tools.javac.util.Context;
+import com.sun.tools.javac.util.Options;
 import jdk.javadoc.internal.tool.Start;
 
 /**
@@ -53,6 +58,7 @@
     private Iterable<String> options;
     private Iterable<? extends JavaFileObject> fileObjects;
     private Locale locale;
+    private List<String> addModules = new ArrayList<>();
 
     public JavadocTaskImpl(Context context, Class<?> docletClass,
             Iterable<String> options, Iterable<? extends JavaFileObject> fileObjects) {
@@ -72,6 +78,16 @@
         this.locale = locale;
     }
 
+    @Override
+    public void addModules(Iterable<String> moduleNames) {
+        nullCheck(moduleNames);
+        if (used.get())
+            throw new IllegalStateException();
+        for (String name : moduleNames) {
+            addModules.add(name);
+        }
+    }
+
     public Boolean call() {
         if (!used.getAndSet(true)) {
             initContext();
@@ -89,6 +105,12 @@
     private void initContext() {
         //initialize compiler's default locale
         context.put(Locale.class, locale);
+        if (!addModules.isEmpty()) {
+            String names = String.join(",", addModules);
+            Options opts = Options.instance(context);
+            String prev = opts.get(Option.ADD_MODULES);
+            opts.put(Option.ADD_MODULES, (prev == null) ? names : prev + "," + names);
+        }
     }
 
     private static <T> Iterable<T> nullCheck(Iterable<T> items) {
--- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/HtmlDocletWriter.java	Thu Mar 16 20:47:03 2017 +0000
@@ -647,6 +647,13 @@
                 tree.addContent(fixedNavDiv);
                 HtmlTree paddingDiv = HtmlTree.DIV(HtmlStyle.navPadding, Contents.SPACE);
                 tree.addContent(paddingDiv);
+                HtmlTree scriptTree = HtmlTree.SCRIPT();
+                String scriptCode = "<!--\n"
+                        + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                        + "//-->\n";
+                RawHtml scriptContent = new RawHtml(scriptCode.replace("\n", DocletConstants.NL));
+                scriptTree.addContent(scriptContent);
+                tree.addContent(scriptTree);
             } else {
                 subDiv.addContent(getMarkerAnchor(SectionName.SKIP_NAVBAR_BOTTOM));
                 tree.addContent(subDiv);
--- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ModuleIndexWriter.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/ModuleIndexWriter.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -144,6 +144,7 @@
         Content div = HtmlTree.DIV(HtmlStyle.contentContainer, table);
         if (configuration.allowTag(HtmlTag.MAIN)) {
             htmlTree.addContent(div);
+            body.addContent(htmlTree);
         } else {
             body.addContent(div);
         }
@@ -183,21 +184,12 @@
     protected void addOverviewHeader(Content body) {
         addConfigurationTitle(body);
         if (!utils.getFullBody(configuration.overviewElement).isEmpty()) {
-            HtmlTree subTitleDiv = new HtmlTree(HtmlTag.DIV);
-            subTitleDiv.addStyle(HtmlStyle.subTitle);
-            addSummaryComment(configuration.overviewElement, subTitleDiv);
-            Content div = HtmlTree.DIV(HtmlStyle.header, subTitleDiv);
-            Content see = new ContentBuilder();
-            see.addContent(contents.seeLabel);
-            see.addContent(" ");
-            Content descPara = HtmlTree.P(see);
-            Content descLink = getHyperLink(getDocLink(
-                    SectionName.OVERVIEW_DESCRIPTION),
-                    contents.descriptionLabel, "", "");
-            descPara.addContent(descLink);
-            div.addContent(descPara);
+            HtmlTree div = new HtmlTree(HtmlTag.DIV);
+            div.addStyle(HtmlStyle.contentContainer);
+            addOverviewComment(div);
             if (configuration.allowTag(HtmlTag.MAIN)) {
                 htmlTree.addContent(div);
+                body.addContent(htmlTree);
             } else {
                 body.addContent(div);
             }
@@ -213,29 +205,17 @@
      */
     protected void addOverviewComment(Content htmltree) {
         if (!utils.getFullBody(configuration.overviewElement).isEmpty()) {
-            htmltree.addContent(getMarkerAnchor(SectionName.OVERVIEW_DESCRIPTION));
             addInlineComment(configuration.overviewElement, htmltree);
         }
     }
 
     /**
-     * Adds the tag information as provided in the file specified by the
-     * "-overview" option on the command line.
+     * Not required for this page.
      *
      * @param body the documentation tree to which the overview will be added
      */
     @Override
-    protected void addOverview(Content body) {
-        HtmlTree div = new HtmlTree(HtmlTag.DIV);
-        div.addStyle(HtmlStyle.contentContainer);
-        addOverviewComment(div);
-        if (configuration.allowTag(HtmlTag.MAIN)) {
-            htmlTree.addContent(div);
-            body.addContent(htmlTree);
-        } else {
-            body.addContent(div);
-        }
-    }
+    protected void addOverview(Content body) {}
 
     /**
      * Adds the top text (from the -top option), the upper
--- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/PackageIndexWriter.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/PackageIndexWriter.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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
@@ -134,6 +134,7 @@
         Content div = HtmlTree.DIV(HtmlStyle.contentContainer, table);
         if (configuration.allowTag(HtmlTag.MAIN)) {
             htmlTree.addContent(div);
+            body.addContent(htmlTree);
         } else {
             body.addContent(div);
         }
@@ -176,21 +177,12 @@
     protected void addOverviewHeader(Content body) {
         addConfigurationTitle(body);
         if (!utils.getFullBody(configuration.overviewElement).isEmpty()) {
-            HtmlTree subTitleDiv = new HtmlTree(HtmlTag.DIV);
-            subTitleDiv.addStyle(HtmlStyle.subTitle);
-            addSummaryComment(configuration.overviewElement, subTitleDiv);
-            Content div = HtmlTree.DIV(HtmlStyle.header, subTitleDiv);
-            Content descBody = new ContentBuilder();
-            descBody.addContent(contents.seeLabel);
-            descBody.addContent(" ");
-            Content descPara = HtmlTree.P(descBody);
-            Content descLink = getHyperLink(getDocLink(
-                    SectionName.OVERVIEW_DESCRIPTION),
-                    contents.descriptionLabel, "", "");
-            descPara.addContent(descLink);
-            div.addContent(descPara);
+            HtmlTree div = new HtmlTree(HtmlTag.DIV);
+            div.addStyle(HtmlStyle.contentContainer);
+            addOverviewComment(div);
             if (configuration.allowTag(HtmlTag.MAIN)) {
                 htmlTree.addContent(div);
+                body.addContent(htmlTree);
             } else {
                 body.addContent(div);
             }
@@ -206,29 +198,17 @@
      */
     protected void addOverviewComment(Content htmltree) {
         if (!utils.getFullBody(configuration.overviewElement).isEmpty()) {
-            htmltree.addContent(getMarkerAnchor(SectionName.OVERVIEW_DESCRIPTION));
             addInlineComment(configuration.overviewElement, htmltree);
         }
     }
 
     /**
-     * Adds the tag information as provided in the file specified by the
-     * "-overview" option on the command line.
+     * Not required for this page.
      *
      * @param body the documentation tree to which the overview will be added
      */
     @Override
-    protected void addOverview(Content body) {
-        HtmlTree div = new HtmlTree(HtmlTag.DIV);
-        div.addStyle(HtmlStyle.contentContainer);
-        addOverviewComment(div);
-        if (configuration.allowTag(HtmlTag.MAIN)) {
-            htmlTree.addContent(div);
-            body.addContent(htmlTree);
-        } else {
-            body.addContent(div);
-        }
-    }
+    protected void addOverview(Content body) {}
 
     /**
      * Adds the top text (from the -top option), the upper
--- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/search.js	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/formats/html/resources/search.js	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -169,11 +169,42 @@
             var tresult = new Array();
             var mresult = new Array();
             var tgresult = new Array();
+            var secondaryresult = new Array();
             var displayCount = 0;
             var exactMatcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term) + "$", "i");
             camelCaseRegexp = ($.ui.autocomplete.escapeRegex(request.term)).split(/(?=[A-Z])/).join("([a-z0-9_$]*?)");
             var camelCaseMatcher = new RegExp("^" + camelCaseRegexp);
             secondaryMatcher = new RegExp($.ui.autocomplete.escapeRegex(request.term), "i");
+
+            // Return the nested innermost name from the specified object
+            function nestedName(e) {
+                return e.l.substring(e.l.lastIndexOf(".") + 1);
+            }
+
+            // Sort array items by short name (as opposed to fully qualified name).
+            // Additionally, sort by the nested type name, when present,
+            // as opposed to top level short name.
+            function sortAndConcatResults(a1, a2) {
+                var sortingKey;
+                var sortArray = function(e1, e2) {
+                    var l = sortingKey(e1);
+                    var m = sortingKey(e2);
+                    if (l < m)
+                        return -1;
+                    if (l > m)
+                        return 1;
+                    return 0;
+                };
+                sortingKey = function(e) {
+                    return nestedName(e).toUpperCase();
+                };
+                a1.sort(sortArray);
+                a2.sort(sortArray);
+                a1 = a1.concat(a2);
+                a2.length = 0;
+                return a1;
+            }
+
             if (moduleSearchIndex) {
                 var mdleCount = 0;
                 $.each(moduleSearchIndex, function(index, item) {
@@ -184,10 +215,11 @@
                     } else if (camelCaseMatcher.test(item.l)) {
                         result.unshift(item);
                     } else if (secondaryMatcher.test(item.l)) {
-                        result.push(item);
+                        secondaryresult.push(item);
                     }
                 });
                 displayCount = mdleCount;
+                result = sortAndConcatResults(result, secondaryresult);
             }
             if (packageSearchIndex) {
                 var pCount = 0;
@@ -197,48 +229,51 @@
                     pkg = (item.m)
                             ? (item.m + "/" + item.l)
                             : item.l;
-                    if (exactMatcher.test(item.l)) {
+                    var s = nestedName(item);
+                    if (exactMatcher.test(s)) {
                         presult.unshift(item);
                         pCount++;
                     } else if (camelCaseMatcher.test(pkg)) {
                         presult.unshift(item);
                     } else if (secondaryMatcher.test(pkg)) {
-                        presult.push(item);
+                        secondaryresult.push(item);
                     }
                 });
-                result = result.concat(presult);
+                result = result.concat(sortAndConcatResults(presult, secondaryresult));
                 displayCount = (pCount > displayCount) ? pCount : displayCount;
             }
             if (typeSearchIndex) {
                 var tCount = 0;
                 $.each(typeSearchIndex, function(index, item) {
                     item[category] = catTypes;
-                    if (exactMatcher.test(item.l)) {
+                    var s = nestedName(item);
+                    if (exactMatcher.test(s)) {
                         tresult.unshift(item);
                         tCount++;
-                    } else if (camelCaseMatcher.test(item.l)) {
+                    } else if (camelCaseMatcher.test(s)) {
                         tresult.unshift(item);
                     } else if (secondaryMatcher.test(item.p + "." + item.l)) {
-                        tresult.push(item);
+                        secondaryresult.push(item);
                     }
                 });
-                result = result.concat(tresult);
+                result = result.concat(sortAndConcatResults(tresult, secondaryresult));
                 displayCount = (tCount > displayCount) ? tCount : displayCount;
             }
             if (memberSearchIndex) {
                 var mCount = 0;
                 $.each(memberSearchIndex, function(index, item) {
                     item[category] = catMembers;
-                    if (exactMatcher.test(item.l)) {
+                    var s = nestedName(item);
+                    if (exactMatcher.test(s)) {
                         mresult.unshift(item);
                         mCount++;
-                    } else if (camelCaseMatcher.test(item.l)) {
+                    } else if (camelCaseMatcher.test(s)) {
                         mresult.unshift(item);
                     } else if (secondaryMatcher.test(item.c + "." + item.l)) {
-                        mresult.push(item);
+                        secondaryresult.push(item);
                     }
                 });
-                result = result.concat(mresult);
+                result = result.concat(sortAndConcatResults(mresult, secondaryresult));
                 displayCount = (mCount > displayCount) ? mCount : displayCount;
             }
             if (tagSearchIndex) {
@@ -249,10 +284,10 @@
                         tgresult.unshift(item);
                         tgCount++;
                     } else if (secondaryMatcher.test(item.l)) {
-                        tgresult.push(item);
+                        secondaryresult.push(item);
                     }
                 });
-                result = result.concat(tgresult);
+                result = result.concat(sortAndConcatResults(tgresult, secondaryresult));
                 displayCount = (tgCount > displayCount) ? tgCount : displayCount;
             }
             displayCount = (displayCount > 500) ? displayCount : 500;
@@ -312,4 +347,4 @@
             }
         }
     });
-});
\ No newline at end of file
+});
--- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/Configuration.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/Configuration.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, 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,7 +32,6 @@
 import javax.lang.model.element.ModuleElement;
 import javax.lang.model.element.PackageElement;
 import javax.lang.model.element.TypeElement;
-import javax.lang.model.util.ElementFilter;
 import javax.lang.model.util.SimpleElementVisitor9;
 import javax.tools.JavaFileManager;
 import javax.tools.JavaFileObject;
@@ -1116,7 +1115,7 @@
 
         @Override
         public String toString() {
-            return names.toString();
+            return Arrays.toString(names);
         }
 
         @Override
--- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/WorkArounds.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/WorkArounds.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -46,7 +46,6 @@
 import javax.lang.model.util.Elements;
 import javax.tools.FileObject;
 import javax.tools.JavaFileManager.Location;
-import javax.tools.JavaFileObject;
 
 import com.sun.source.tree.CompilationUnitTree;
 import com.sun.source.util.JavacTask;
@@ -62,7 +61,6 @@
 import com.sun.tools.javac.code.Symbol.ModuleSymbol;
 import com.sun.tools.javac.code.Symbol.PackageSymbol;
 import com.sun.tools.javac.code.Symbol.VarSymbol;
-import com.sun.tools.javac.code.Symtab;
 import com.sun.tools.javac.comp.AttrContext;
 import com.sun.tools.javac.comp.Env;
 import com.sun.tools.javac.model.JavacElements;
@@ -297,6 +295,33 @@
         return null;
     }
 
+    // TODO: the method jx.l.m.Elements::overrides does not check
+    // the return type, see JDK-8174840 until that is resolved,
+    // use a  copy of the same method, with a return type check.
+
+    // Note: the rider.overrides call in this method *must* be consistent
+    // with the call in overrideType(....), the method above.
+    public boolean overrides(ExecutableElement e1, ExecutableElement e2, TypeElement cls) {
+        MethodSymbol rider = (MethodSymbol)e1;
+        MethodSymbol ridee = (MethodSymbol)e2;
+        ClassSymbol origin = (ClassSymbol)cls;
+
+        return rider.name == ridee.name &&
+
+               // not reflexive as per JLS
+               rider != ridee &&
+
+               // we don't care if ridee is static, though that wouldn't
+               // compile
+               !rider.isStatic() &&
+
+               // Symbol.overrides assumes the following
+               ridee.isMemberOf(origin, toolEnv.getTypes()) &&
+
+               // check access, signatures and check return types
+               rider.overrides(ridee, origin, toolEnv.getTypes(), true);
+    }
+
     // TODO: jx.l.m ?
     public Location getLocationForModule(ModuleElement mdle) {
         ModuleSymbol msym = (ModuleSymbol)mdle;
--- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/script.js	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/script.js	Thu Mar 16 20:47:03 2017 +0000
@@ -92,6 +92,9 @@
     if (!tagSearchIndex) {
         createElem(doc, tag, 'tag-search-index.js');
     }
+    $(window).resize(function() {
+        $('.navPadding').css('padding-top', $('.fixedNav').css("height"));
+    });
 }
 
 function createElem(doc, tag, path) {
--- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/stylesheet.css	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/resources/stylesheet.css	Thu Mar 16 20:47:03 2017 +0000
@@ -144,7 +144,7 @@
     margin:0;
 }
 .navPadding {
-    padding-top: 100px;
+    padding-top: 107px;
 }
 .fixedNav {
     position:fixed;
--- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Utils.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/doclets/toolkit/util/Utils.java	Thu Mar 16 20:47:03 2017 +0000
@@ -893,7 +893,7 @@
             }
             List<? extends Element> methods = te.getEnclosedElements();
             for (ExecutableElement ee : ElementFilter.methodsIn(methods)) {
-                if (elementUtils.overrides(method, ee, origin)) {
+                if (configuration.workArounds.overrides(method, ee, origin)) {
                     return ee;
                 }
             }
@@ -1886,11 +1886,6 @@
             }
 
             @Override
-            public String visitPrimitive(PrimitiveType t, Void p) {
-                return t.toString();
-            }
-
-            @Override
             public String visitTypeVariable(javax.lang.model.type.TypeVariable t, Void p) {
                 // The knee jerk reaction is to do this but don't!, as we would like
                 // it to be compatible with the old world, now if we decide to do so
@@ -1900,9 +1895,10 @@
             }
 
             @Override
-            protected String defaultAction(TypeMirror e, Void p) {
-                throw new UnsupportedOperationException("should not happen");
+            protected String defaultAction(TypeMirror t, Void p) {
+                return t.toString();
             }
+
         }.visit(t);
     }
 
--- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/ToolOption.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/ToolOption.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -181,13 +181,6 @@
         }
     },
 
-    XMODULE("-Xmodule:", EXTENDED, false) {
-        @Override
-        public void process(Helper helper, String arg) throws InvalidValueException {
-            Option.XMODULE.process(helper.getOptionHelper(), arg);
-        }
-    },
-
     PATCH_MODULE("--patch-module", EXTENDED, true) {
         @Override
         public void process(Helper helper, String arg) throws InvalidValueException {
@@ -345,7 +338,7 @@
         }
     },
 
-    X("-X", STANDARD) {
+    HELP_EXTRA("--help-extra -X", STANDARD) {
         @Override
         public void process(Helper helper) throws OptionException {
            throw new OptionException(OK, helper::Xusage);
@@ -419,9 +412,7 @@
 
     static ToolOption get(String name) {
         String oname = name;
-        if (name.contains(":")) {
-            oname = name.substring(0, name.indexOf(':') + 1);
-        } else if (name.contains("=")) {
+        if (name.startsWith("--") && name.contains("=")) {
             oname = name.substring(0, name.indexOf('='));
         }
         for (ToolOption o : values()) {
--- a/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/resources/javadoc.properties	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/jdk/javadoc/internal/tool/resources/javadoc.properties	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 1997, 2017, 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
@@ -205,7 +205,7 @@
 main.opt.J.desc=\
     Pass <flag> directly to the runtime system
 
-main.opt.X.desc=\
+main.opt.help.extra.desc=\
     Print a synopsis of nonstandard options and exit
 
 main.usage.foot=\n\
@@ -238,11 +238,6 @@
     given module. <other-module> may be ALL-UNNAMED to require\n\
     the unnamed module.
 
-main.opt.Xmodule.arg=\
-    <module-name>
-main.opt.Xmodule.desc=\
-    Specify a module to which the classes being compiled belong
-
 main.opt.patch.module.arg=\
     <module>=<file>(:<file>)*
 main.opt.patch.module.desc=\
--- a/langtools/src/jdk.javadoc/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.javadoc/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,6 +26,8 @@
 /** Defines the implementation of the
  *  {@link javax.tools.ToolProvider#getSystemDocumentationTool system documentation tool}
  *  and its command line equivalent, <em>javadoc</em>.
+ *
+ *  @since 9
  */
 module jdk.javadoc {
     requires transitive java.compiler;
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/classfile/Module_attribute.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/classfile/Module_attribute.java	Thu Mar 16 20:47:03 2017 +0000
@@ -38,8 +38,8 @@
  *  deletion without notice.</b>
  */
 public class Module_attribute extends Attribute {
-    public static final int ACC_TRANSITIVE      =   0x10;
-    public static final int ACC_STATIC_PHASE    =   0x20;
+    public static final int ACC_TRANSITIVE      =   0x20;
+    public static final int ACC_STATIC_PHASE    =   0x40;
     public static final int ACC_OPEN            =   0x20;
     public static final int ACC_SYNTHETIC       = 0x1000;
     public static final int ACC_MANDATED        = 0x8000;
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeprscan/LoadProc.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeprscan/LoadProc.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -50,7 +50,7 @@
 
 import javax.tools.Diagnostic;
 
-import static javax.lang.model.SourceVersion.RELEASE_9;
+import static javax.lang.model.SourceVersion.RELEASE_10;
 
 /**
  * Annotation processor for the Deprecation Scanner tool.
@@ -58,7 +58,7 @@
  *
  */
 @SupportedAnnotationTypes("java.lang.Deprecated")
-@SupportedSourceVersion(RELEASE_9)
+@SupportedSourceVersion(RELEASE_10)
 public class LoadProc extends AbstractProcessor {
     Elements elements;
     Messager messager;
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeprscan/Main.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeprscan/Main.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -101,7 +101,7 @@
     // Keep these updated manually until there's a compiler API
     // that allows querying of supported releases.
     final Set<String> releasesWithoutForRemoval = Set.of("6", "7", "8");
-    final Set<String> releasesWithForRemoval = Set.of("9");
+    final Set<String> releasesWithForRemoval = Set.of("9", "10");
 
     final Set<String> validReleases;
     {
@@ -353,14 +353,14 @@
      * Process classes from a particular JDK release, using only information
      * in this JDK.
      *
-     * @param release "6", "7", "8", or "9"
+     * @param release "6", "7", "8", "9", or "10"
      * @param classes collection of classes to process, may be empty
      * @return success value
      */
     boolean processRelease(String release, Collection<String> classes) throws IOException {
         options.addAll(List.of("--release", release));
 
-        if (release.equals("9")) {
+        if (release.equals("9") || release.equals("10")) {
             List<String> rootMods = List.of("java.se", "java.se.ee");
             TraverseProc proc = new TraverseProc(rootMods);
             JavaCompiler.CompilationTask task =
@@ -484,7 +484,7 @@
         String dir = null;
         String jar = null;
         String jdkHome = null;
-        String release = "9";
+        String release = "10";
         List<String> loadClasses = new ArrayList<>();
         String csvFile = null;
 
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Graph.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Graph.java	Thu Mar 16 20:47:03 2017 +0000
@@ -116,7 +116,7 @@
                 .forEach(u -> g.adjacentNodes(u).stream()
                                 .filter(v -> isAdjacent(u, v))
                                 .forEach(v -> builder.addEdge(u, v)));
-        return builder.build();
+        return builder.build().reduce();
     }
 
     /**
@@ -274,7 +274,7 @@
         }
 
         public void addNodes(Set<T> nodes) {
-            nodes.addAll(nodes);
+            this.nodes.addAll(nodes);
         }
 
         public void addEdge(T u, T v) {
@@ -335,67 +335,4 @@
             result.addLast(node);
         }
     }
-
-    public static class DotGraph {
-        static final String ORANGE = "#e76f00";
-        static final String BLUE = "#437291";
-        static final String GRAY = "#dddddd";
-
-        static final String REEXPORTS = "";
-        static final String REQUIRES = "style=\"dashed\"";
-        static final String REQUIRES_BASE = "color=\"" + GRAY + "\"";
-
-        static final Set<String> javaModules = modules(name ->
-            (name.startsWith("java.") && !name.equals("java.smartcardio")));
-        static final Set<String> jdkModules = modules(name ->
-            (name.startsWith("java.") ||
-                name.startsWith("jdk.") ||
-                name.startsWith("javafx.")) && !javaModules.contains(name));
-
-        private static Set<String> modules(Predicate<String> predicate) {
-            return ModuleFinder.ofSystem().findAll()
-                               .stream()
-                               .map(ModuleReference::descriptor)
-                               .map(ModuleDescriptor::name)
-                               .filter(predicate)
-                               .collect(Collectors.toSet());
-        }
-
-        static void printAttributes(PrintWriter out) {
-            out.format("  size=\"25,25\";%n");
-            out.format("  nodesep=.5;%n");
-            out.format("  ranksep=1.5;%n");
-            out.format("  pencolor=transparent;%n");
-            out.format("  node [shape=plaintext, fontname=\"DejaVuSans\", fontsize=36, margin=\".2,.2\"];%n");
-            out.format("  edge [penwidth=4, color=\"#999999\", arrowhead=open, arrowsize=2];%n");
-        }
-
-        static void printNodes(PrintWriter out, Graph<String> graph) {
-            out.format("  subgraph se {%n");
-            graph.nodes().stream()
-                 .filter(javaModules::contains)
-                 .forEach(mn -> out.format("  \"%s\" [fontcolor=\"%s\", group=%s];%n",
-                                           mn, ORANGE, "java"));
-            out.format("  }%n");
-            graph.nodes().stream()
-                 .filter(jdkModules::contains)
-                 .forEach(mn -> out.format("    \"%s\" [fontcolor=\"%s\", group=%s];%n",
-                                           mn, BLUE, "jdk"));
-
-            graph.nodes().stream()
-                 .filter(mn -> !javaModules.contains(mn) && !jdkModules.contains(mn))
-                 .forEach(mn -> out.format("  \"%s\";%n", mn));
-        }
-
-        static void printEdges(PrintWriter out, Graph<String> graph,
-                               String node, Set<String> requiresTransitive) {
-            graph.adjacentNodes(node).forEach(dn -> {
-                String attr = dn.equals("java.base") ? REQUIRES_BASE
-                        : (requiresTransitive.contains(dn) ? REEXPORTS : REQUIRES);
-                out.format("  \"%s\" -> \"%s\" [%s];%n", node, dn, attr);
-            });
-        }
-    }
-
-
 }
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsConfiguration.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2017, 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
@@ -118,7 +118,7 @@
         }
 
         this.configuration = Configuration.empty()
-                .resolveRequires(finder, ModuleFinder.of(), mods);
+                .resolve(finder, ModuleFinder.of(), mods);
 
         this.configuration.modules().stream()
                 .map(ResolvedModule::reference)
@@ -207,16 +207,6 @@
     }
 
     /**
-     * Returns the modules that the given module can read
-     */
-    public Stream<Module> reads(Module module) {
-        return configuration.findModule(module.name()).get()
-            .reads().stream()
-            .map(ResolvedModule::name)
-            .map(nameToModule::get);
-    }
-
-    /**
      * Returns the list of packages that split between resolved module and
      * unnamed module
      */
@@ -267,16 +257,15 @@
         return nameToModule;
     }
 
-    public Stream<Module> resolve(Set<String> roots) {
-        if (roots.isEmpty()) {
-            return nameToModule.values().stream();
-        } else {
-            return Configuration.empty()
-                    .resolveRequires(finder, ModuleFinder.of(), roots)
-                    .modules().stream()
-                    .map(ResolvedModule::name)
-                    .map(nameToModule::get);
-        }
+    /**
+     * Returns Configuration with the given roots
+     */
+    public Configuration resolve(Set<String> roots) {
+        if (roots.isEmpty())
+            throw new IllegalArgumentException("empty roots");
+
+        return Configuration.empty()
+                    .resolve(finder, ModuleFinder.of(), roots);
     }
 
     public List<Archive> classPathArchives() {
@@ -422,18 +411,13 @@
         }
 
         private ModuleDescriptor dropHashes(ModuleDescriptor md) {
-            ModuleDescriptor.Builder builder = ModuleDescriptor.module(md.name());
+            ModuleDescriptor.Builder builder = ModuleDescriptor.newModule(md.name());
             md.requires().forEach(builder::requires);
             md.exports().forEach(builder::exports);
             md.opens().forEach(builder::opens);
             md.provides().stream().forEach(builder::provides);
             md.uses().stream().forEach(builder::uses);
-
-            Set<String> concealed = new HashSet<>(md.packages());
-            md.exports().stream().map(Exports::source).forEach(concealed::remove);
-            md.opens().stream().map(Opens::source).forEach(concealed::remove);
-            concealed.forEach(builder::contains);
-
+            builder.packages(md.packages());
             return builder.build();
         }
 
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/JdepsTask.java	Thu Mar 16 20:47:03 2017 +0000
@@ -721,9 +721,9 @@
             return run(config, writer, type);
         }
 
-        boolean run(JdepsConfiguration config, JdepsWriter writer, Type type) throws IOException {
-
-
+        boolean run(JdepsConfiguration config, JdepsWriter writer, Type type)
+            throws IOException
+        {
             // analyze the dependencies
             DepsAnalyzer analyzer = new DepsAnalyzer(config,
                                                      dependencyFilter(config),
@@ -1024,8 +1024,10 @@
         boolean run(JdepsConfiguration config) throws IOException {
             if ((options.showSummary || options.verbose == MODULE) &&
                 !options.addmods.isEmpty() && inputArgs.isEmpty()) {
-                // print module descriptor
-                return new ModuleAnalyzer(config, log).genDotFiles(dotOutputDir);
+                // generate dot graph from the resolved graph from module
+                // resolution.  No class dependency analysis is performed.
+                return new ModuleDotGraph(config, options.apiOnly)
+                        .genDotFiles(dotOutputDir);
             }
 
             Type type = getAnalyzerType();
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/Module.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,8 +26,6 @@
 package com.sun.tools.jdeps;
 
 import java.lang.module.ModuleDescriptor;
-import java.lang.module.ModuleDescriptor.Exports;
-import java.lang.module.ModuleDescriptor.Opens;
 import java.net.URI;
 import java.util.Collections;
 import java.util.HashMap;
@@ -55,6 +53,7 @@
 
     private final ModuleDescriptor descriptor;
     private final Map<String, Set<String>> exports;
+    private final Map<String, Set<String>> opens;
     private final boolean isSystem;
     private final URI location;
 
@@ -63,6 +62,7 @@
         this.descriptor = null;
         this.location = null;
         this.exports = Collections.emptyMap();
+        this.opens = Collections.emptyMap();
         this.isSystem = true;
     }
 
@@ -70,12 +70,14 @@
                    URI location,
                    ModuleDescriptor descriptor,
                    Map<String, Set<String>> exports,
+                   Map<String, Set<String>> opens,
                    boolean isSystem,
                    ClassFileReader reader) {
         super(name, location, reader);
         this.descriptor = descriptor;
         this.location = location;
         this.exports = Collections.unmodifiableMap(exports);
+        this.opens = Collections.unmodifiableMap(opens);
         this.isSystem = isSystem;
     }
 
@@ -124,35 +126,52 @@
         return descriptor.packages();
     }
 
-    /**
-     * Tests if the package of the given name is exported.
-     */
-    public boolean isExported(String pn) {
-        return exports.containsKey(pn) ? exports.get(pn).isEmpty() : false;
-    }
-
     public boolean isJDKUnsupported() {
         return JDK_UNSUPPORTED.equals(this.name());
     }
 
     /**
-     * Converts this module to a strict module with the given dependences
+     * Converts this module to a normal module with the given dependences
      *
      * @throws IllegalArgumentException if this module is not an automatic module
      */
-    public Module toStrictModule(Map<String, Boolean> requires) {
+    public Module toNormalModule(Map<String, Boolean> requires) {
         if (!isAutomatic()) {
-            throw new IllegalArgumentException(name() + " already a strict module");
+            throw new IllegalArgumentException(name() + " not an automatic module");
         }
-        return new StrictModule(this, requires);
+        return new NormalModule(this, requires);
+    }
+
+    /**
+     * Tests if the package of the given name is exported.
+     */
+    public boolean isExported(String pn) {
+        return exports.containsKey(pn) && exports.get(pn).isEmpty();
     }
 
     /**
-     * Tests if the package of the given name is qualifiedly exported
-     * to the target.
+     * Tests if the package of the given name is exported to the target
+     * in a qualified fashion.
      */
     public boolean isExported(String pn, String target) {
-        return isExported(pn) || exports.containsKey(pn) && exports.get(pn).contains(target);
+        return isExported(pn)
+                || exports.containsKey(pn) && exports.get(pn).contains(target);
+    }
+
+    /**
+     * Tests if the package of the given name is open.
+     */
+    public boolean isOpen(String pn) {
+        return opens.containsKey(pn) && opens.get(pn).isEmpty();
+    }
+
+    /**
+     * Tests if the package of the given name is open to the target
+     * in a qualified fashion.
+     */
+    public boolean isOpen(String pn, String target) {
+        return isOpen(pn)
+            || opens.containsKey(pn) && opens.get(pn).contains(target);
     }
 
     @Override
@@ -193,19 +212,28 @@
             }
 
             Map<String, Set<String>> exports = new HashMap<>();
+            Map<String, Set<String>> opens = new HashMap<>();
 
-            descriptor.exports().stream()
-                .forEach(exp -> exports.computeIfAbsent(exp.source(), _k -> new HashSet<>())
-                                    .addAll(exp.targets()));
-
-            return new Module(name, location, descriptor, exports, isSystem, reader);
+            if (descriptor.isAutomatic()) {
+                // ModuleDescriptor::exports and opens returns an empty set
+                descriptor.packages().forEach(pn -> exports.put(pn, Collections.emptySet()));
+                descriptor.packages().forEach(pn -> opens.put(pn, Collections.emptySet()));
+            } else {
+                descriptor.exports().stream()
+                          .forEach(exp -> exports.computeIfAbsent(exp.source(), _k -> new HashSet<>())
+                                                 .addAll(exp.targets()));
+                descriptor.opens().stream()
+                    .forEach(exp -> opens.computeIfAbsent(exp.source(), _k -> new HashSet<>())
+                        .addAll(exp.targets()));
+            }
+            return new Module(name, location, descriptor, exports, opens, isSystem, reader);
         }
     }
 
     private static class UnnamedModule extends Module {
         private UnnamedModule() {
             super("unnamed", null, null,
-                  Collections.emptyMap(),
+                  Collections.emptyMap(), Collections.emptyMap(),
                   false, null);
         }
 
@@ -230,19 +258,22 @@
         }
     }
 
-    private static class StrictModule extends Module {
+    /**
+     * A normal module has a module-info.class
+     */
+    private static class NormalModule extends Module {
         private final ModuleDescriptor md;
 
         /**
-         * Converts the given automatic module to a strict module.
+         * Converts the given automatic module to a normal module.
          *
          * Replace this module's dependences with the given requires and also
          * declare service providers, if specified in META-INF/services configuration file
          */
-        private StrictModule(Module m, Map<String, Boolean> requires) {
-            super(m.name(), m.location, m.descriptor, m.exports, m.isSystem, m.reader());
+        private NormalModule(Module m, Map<String, Boolean> requires) {
+            super(m.name(), m.location, m.descriptor, m.exports, m.opens, m.isSystem, m.reader());
 
-            ModuleDescriptor.Builder builder = ModuleDescriptor.module(m.name());
+            ModuleDescriptor.Builder builder = ModuleDescriptor.newModule(m.name());
             requires.keySet().forEach(mn -> {
                 if (requires.get(mn).equals(Boolean.TRUE)) {
                     builder.requires(Set.of(ModuleDescriptor.Requires.Modifier.TRANSITIVE), mn);
@@ -250,16 +281,10 @@
                     builder.requires(mn);
                 }
             });
-            m.descriptor.exports().forEach(e -> builder.exports(e));
-            m.descriptor.opens().forEach(o -> builder.opens(o));
-            m.descriptor.uses().forEach(s -> builder.uses(s));
-            m.descriptor.provides().forEach(p -> builder.provides(p));
-
-            Set<String> concealed = new HashSet<>(m.descriptor.packages());
-            m.descriptor.exports().stream().map(Exports::source).forEach(concealed::remove);
-            m.descriptor.opens().stream().map(Opens::source).forEach(concealed::remove);
-            concealed.forEach(builder::contains);
-
+            // exports all packages
+            m.descriptor.packages().forEach(builder::exports);
+            m.descriptor.uses().forEach(builder::uses);
+            m.descriptor.provides().forEach(builder::provides);
             this.md = builder.build();
         }
 
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleAnalyzer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleAnalyzer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -59,15 +59,10 @@
 
     private final JdepsConfiguration configuration;
     private final PrintWriter log;
-
     private final DependencyFinder dependencyFinder;
     private final Map<Module, ModuleDeps> modules;
 
     public ModuleAnalyzer(JdepsConfiguration config,
-                          PrintWriter log) {
-        this(config, log, Collections.emptySet());
-    }
-    public ModuleAnalyzer(JdepsConfiguration config,
                           PrintWriter log,
                           Set<String> names) {
         this.configuration = config;
@@ -150,7 +145,7 @@
         private ModuleDescriptor descriptor(Set<Module> requiresTransitive,
                                             Set<Module> requires) {
 
-            ModuleDescriptor.Builder builder = ModuleDescriptor.module(root.name());
+            ModuleDescriptor.Builder builder = ModuleDescriptor.newModule(root.name());
 
             if (!root.name().equals(JAVA_BASE))
                 builder.requires(Set.of(MANDATED), JAVA_BASE);
@@ -333,88 +328,6 @@
         return true;
     }
 
-    /**
-     * Generate dotfile from module descriptor
-     *
-     * @param dir output directory
-     */
-    public boolean genDotFiles(Path dir) throws IOException {
-        Files.createDirectories(dir);
-        for (Module m : modules.keySet()) {
-            genDotFile(dir, m.name());
-        }
-        return true;
-    }
-
-
-    private void genDotFile(Path dir, String name) throws IOException {
-        try (OutputStream os = Files.newOutputStream(dir.resolve(name + ".dot"));
-             PrintWriter out = new PrintWriter(os)) {
-            Set<Module> modules = configuration.resolve(Set.of(name))
-                .collect(Collectors.toSet());
-
-            // transitive reduction
-            Graph<String> graph = gengraph(modules);
-
-            out.format("digraph \"%s\" {%n", name);
-            DotGraph.printAttributes(out);
-            DotGraph.printNodes(out, graph);
-
-            modules.stream()
-                .map(Module::descriptor)
-                .sorted(Comparator.comparing(ModuleDescriptor::name))
-                .forEach(md -> {
-                    String mn = md.name();
-                    Set<String> requiresTransitive = md.requires().stream()
-                        .filter(d -> d.modifiers().contains(TRANSITIVE))
-                        .map(d -> d.name())
-                        .collect(toSet());
-
-                    DotGraph.printEdges(out, graph, mn, requiresTransitive);
-                });
-
-            out.println("}");
-        }
-    }
-
-    /**
-     * Returns a Graph of the given Configuration after transitive reduction.
-     *
-     * Transitive reduction of requires transitive edge and requires edge have
-     * to be applied separately to prevent the requires transitive edges
-     * (e.g. U -> V) from being reduced by a path (U -> X -> Y -> V)
-     * in which  V would not be re-exported from U.
-     */
-    private Graph<String> gengraph(Set<Module> modules) {
-        // build a Graph containing only requires transitive edges
-        // with transitive reduction.
-        Graph.Builder<String> rpgbuilder = new Graph.Builder<>();
-        for (Module module : modules) {
-            ModuleDescriptor md = module.descriptor();
-            String mn = md.name();
-            md.requires().stream()
-                    .filter(d -> d.modifiers().contains(TRANSITIVE))
-                    .map(d -> d.name())
-                    .forEach(d -> rpgbuilder.addEdge(mn, d));
-        }
-
-        Graph<String> rpg = rpgbuilder.build().reduce();
-
-        // build the readability graph
-        Graph.Builder<String> builder = new Graph.Builder<>();
-        for (Module module : modules) {
-            ModuleDescriptor md = module.descriptor();
-            String mn = md.name();
-            builder.addNode(mn);
-            configuration.reads(module)
-                    .map(Module::name)
-                    .forEach(d -> builder.addEdge(mn, d));
-        }
-
-        // transitive reduction of requires edges
-        return builder.build().reduce(rpg);
-    }
-
     // ---- for testing purpose
     public ModuleDescriptor[] descriptors(String name) {
         ModuleDeps moduleDeps = modules.keySet().stream()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleDotGraph.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,368 @@
+/*
+ * Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation.  Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+package com.sun.tools.jdeps;
+
+import static java.lang.module.ModuleDescriptor.Requires.Modifier.*;
+import static java.util.stream.Collectors.*;
+
+import java.io.BufferedWriter;
+import java.io.IOException;
+import java.io.PrintWriter;
+import java.lang.module.Configuration;
+import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleFinder;
+import java.lang.module.ModuleReference;
+import java.lang.module.ResolvedModule;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayDeque;
+import java.util.ArrayList;
+import java.util.Deque;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.TreeSet;
+import java.util.function.Function;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
+/**
+ * Generate dot graph for modules
+ */
+public class ModuleDotGraph {
+    private final Map<String, Configuration> configurations;
+    private final boolean apiOnly;
+    public ModuleDotGraph(JdepsConfiguration config, boolean apiOnly) {
+        this(config.rootModules().stream()
+                   .map(Module::name)
+                   .sorted()
+                   .collect(toMap(Function.identity(), mn -> config.resolve(Set.of(mn)))),
+             apiOnly);
+    }
+
+    public ModuleDotGraph(Map<String, Configuration> configurations, boolean apiOnly) {
+        this.configurations = configurations;
+        this.apiOnly = apiOnly;
+    }
+
+    /**
+     * Generate dotfile for all modules
+     *
+     * @param dir output directory
+     */
+    public boolean genDotFiles(Path dir) throws IOException {
+        Files.createDirectories(dir);
+        for (String mn : configurations.keySet()) {
+            Path path = dir.resolve(mn + ".dot");
+            genDotFile(path, mn, configurations.get(mn));
+        }
+        return true;
+    }
+
+    /**
+     * Generate dotfile of the given path
+     */
+    public void genDotFile(Path path, String name, Configuration configuration)
+        throws IOException
+    {
+        // transitive reduction
+        Graph<String> graph = apiOnly
+                ? requiresTransitiveGraph(configuration, Set.of(name))
+                : gengraph(configuration);
+
+        DotGraphBuilder builder = new DotGraphBuilder(name, graph);
+        builder.subgraph("se", "java", DotGraphBuilder.ORANGE,
+                         DotGraphBuilder.JAVA_SE_SUBGRAPH)
+               .subgraph("jdk", "jdk", DotGraphBuilder.BLUE,
+                         DotGraphBuilder.JDK_SUBGRAPH)
+               .descriptors(graph.nodes().stream()
+                                 .map(mn -> configuration.findModule(mn).get()
+                                                .reference().descriptor()));
+        // build dot file
+        builder.build(path);
+    }
+
+    /**
+     * Returns a Graph of the given Configuration after transitive reduction.
+     *
+     * Transitive reduction of requires transitive edge and requires edge have
+     * to be applied separately to prevent the requires transitive edges
+     * (e.g. U -> V) from being reduced by a path (U -> X -> Y -> V)
+     * in which  V would not be re-exported from U.
+     */
+    private Graph<String> gengraph(Configuration cf) {
+        Graph.Builder<String> builder = new Graph.Builder<>();
+        cf.modules().stream()
+            .forEach(resolvedModule -> {
+                String mn = resolvedModule.reference().descriptor().name();
+                builder.addNode(mn);
+                resolvedModule.reads().stream()
+                    .map(ResolvedModule::name)
+                    .forEach(target -> builder.addEdge(mn, target));
+            });
+
+        Graph<String> rpg = requiresTransitiveGraph(cf, builder.nodes);
+        return builder.build().reduce(rpg);
+    }
+
+
+    /**
+     * Returns a Graph containing only requires transitive edges
+     * with transitive reduction.
+     */
+    public Graph<String> requiresTransitiveGraph(Configuration cf,
+                                                 Set<String> roots)
+    {
+        Deque<String> deque = new ArrayDeque<>(roots);
+        Set<String> visited = new HashSet<>();
+        Graph.Builder<String> builder = new Graph.Builder<>();
+
+        while (deque.peek() != null) {
+            String mn = deque.pop();
+            if (visited.contains(mn))
+                continue;
+
+            visited.add(mn);
+            builder.addNode(mn);
+            ModuleDescriptor descriptor = cf.findModule(mn).get()
+                .reference().descriptor();
+            descriptor.requires().stream()
+                .filter(d -> d.modifiers().contains(TRANSITIVE)
+                                || d.name().equals("java.base"))
+                .map(d -> d.name())
+                .forEach(d -> {
+                    deque.add(d);
+                    builder.addEdge(mn, d);
+                });
+        }
+
+        return builder.build().reduce();
+    }
+
+    public static class DotGraphBuilder {
+        static final Set<String> JAVA_SE_SUBGRAPH = javaSE();
+        static final Set<String> JDK_SUBGRAPH = jdk();
+
+        private static Set<String> javaSE() {
+            String root = "java.se.ee";
+            ModuleFinder system = ModuleFinder.ofSystem();
+            if (system.find(root).isPresent()) {
+                return Stream.concat(Stream.of(root),
+                                     Configuration.empty().resolve(system,
+                                                                   ModuleFinder.of(),
+                                                                   Set.of(root))
+                                                  .findModule(root).get()
+                                                  .reads().stream()
+                                                  .map(ResolvedModule::name))
+                             .collect(toSet());
+            } else {
+                // approximation
+                return system.findAll().stream()
+                    .map(ModuleReference::descriptor)
+                    .map(ModuleDescriptor::name)
+                    .filter(name -> name.startsWith("java.") &&
+                                        !name.equals("java.smartcardio"))
+                    .collect(Collectors.toSet());
+            }
+        }
+
+        private static Set<String> jdk() {
+            return ModuleFinder.ofSystem().findAll().stream()
+                    .map(ModuleReference::descriptor)
+                    .map(ModuleDescriptor::name)
+                    .filter(name -> !JAVA_SE_SUBGRAPH.contains(name) &&
+                                        (name.startsWith("java.") ||
+                                            name.startsWith("jdk.") ||
+                                            name.startsWith("javafx.")))
+                    .collect(Collectors.toSet());
+        }
+
+        static class SubGraph {
+            final String name;
+            final String group;
+            final String color;
+            final Set<String> nodes;
+            SubGraph(String name, String group, String color, Set<String> nodes) {
+                this.name = Objects.requireNonNull(name);
+                this.group = Objects.requireNonNull(group);
+                this.color = Objects.requireNonNull(color);
+                this.nodes = Objects.requireNonNull(nodes);
+            }
+        }
+
+        static final String ORANGE = "#e76f00";
+        static final String BLUE = "#437291";
+        static final String GRAY = "#dddddd";
+        static final String BLACK = "#000000";
+
+        static final String FONT_NAME = "DejaVuSans";
+        static final int FONT_SIZE = 12;
+        static final int ARROW_SIZE = 1;
+        static final int ARROW_WIDTH = 2;
+        static final int RANK_SEP = 1;
+
+        static final String REEXPORTS = "";
+        static final String REQUIRES = "style=\"dashed\"";
+        static final String REQUIRES_BASE = "color=\"" + GRAY + "\"";
+
+        // can be configured
+        static double rankSep   = RANK_SEP;
+        static String fontColor = BLACK;
+        static String fontName  = FONT_NAME;
+        static int fontsize     = FONT_SIZE;
+        static int arrowWidth   = ARROW_WIDTH;
+        static int arrowSize    = ARROW_SIZE;
+        static final Map<String, Integer> weights = new HashMap<>();
+        static final List<Set<String>> ranks = new ArrayList<>();
+
+        private final String name;
+        private final Graph<String> graph;
+        private final Set<ModuleDescriptor> descriptors = new TreeSet<>();
+        private final List<SubGraph> subgraphs = new ArrayList<>();
+        public DotGraphBuilder(String name, Graph<String> graph) {
+            this.name = name;
+            this.graph = graph;
+        }
+
+        public DotGraphBuilder descriptors(Stream<ModuleDescriptor> descriptors) {
+            descriptors.forEach(this.descriptors::add);
+            return this;
+        }
+
+        public void build(Path filename) throws IOException {
+            try (BufferedWriter writer = Files.newBufferedWriter(filename);
+                 PrintWriter out = new PrintWriter(writer)) {
+
+                out.format("digraph \"%s\" {%n", name);
+                out.format("  nodesep=.5;%n");
+                out.format("  ranksep=%f;%n", rankSep);
+                out.format("  pencolor=transparent;%n");
+                out.format("  node [shape=plaintext, fontname=\"%s\", fontsize=%d, margin=\".2,.2\"];%n",
+                           fontName, fontsize);
+                out.format("  edge [penwidth=%d, color=\"#999999\", arrowhead=open, arrowsize=%d];%n",
+                           arrowWidth, arrowSize);
+
+                // same RANKS
+                ranks.stream()
+                     .map(nodes -> descriptors.stream()
+                                        .map(ModuleDescriptor::name)
+                                        .filter(nodes::contains)
+                                        .map(mn -> "\"" + mn + "\"")
+                                        .collect(joining(",")))
+                     .filter(group -> group.length() > 0)
+                     .forEach(group -> out.format("  {rank=same %s}%n", group));
+
+                subgraphs.forEach(subgraph -> {
+                    out.format("  subgraph %s {%n", subgraph.name);
+                    descriptors.stream()
+                        .map(ModuleDescriptor::name)
+                        .filter(subgraph.nodes::contains)
+                        .forEach(mn -> printNode(out, mn, subgraph.color, subgraph.group));
+                    out.format("  }%n");
+                });
+
+                descriptors.stream()
+                    .filter(md -> graph.contains(md.name()) &&
+                                    !graph.adjacentNodes(md.name()).isEmpty())
+                    .forEach(md -> printNode(out, md, graph.adjacentNodes(md.name())));
+
+                out.println("}");
+            }
+        }
+
+        public DotGraphBuilder subgraph(String name, String group, String color,
+                                 Set<String> nodes) {
+            subgraphs.add(new SubGraph(name, group, color, nodes));
+            return this;
+        }
+
+        public void printNode(PrintWriter out, String node, String color, String group) {
+            out.format("  \"%s\" [fontcolor=\"%s\", group=%s];%n",
+                       node, color, group);
+        }
+
+        public void printNode(PrintWriter out, ModuleDescriptor md, Set<String> edges) {
+            Set<String> requiresTransitive = md.requires().stream()
+                .filter(d -> d.modifiers().contains(TRANSITIVE))
+                .map(d -> d.name())
+                .collect(toSet());
+
+            String mn = md.name();
+            edges.stream().forEach(dn -> {
+                String attr = dn.equals("java.base") ? REQUIRES_BASE
+                    : (requiresTransitive.contains(dn) ? REEXPORTS : REQUIRES);
+
+                int w = weightOf(mn, dn);
+                if (w > 1) {
+                    if (!attr.isEmpty())
+                        attr += ", ";
+
+                    attr += "weight=" + w;
+                }
+                out.format("  \"%s\" -> \"%s\" [%s];%n", mn, dn, attr);
+            });
+        }
+
+        public int weightOf(String s, String t) {
+            int w = weights.getOrDefault(s + ":" + t, 1);
+            if (w != 1)
+                return w;
+            if (s.startsWith("java.") && t.startsWith("java."))
+                return 10;
+            return 1;
+        }
+
+        public static void sameRankNodes(Set<String> nodes) {
+            ranks.add(nodes);
+        }
+
+        public static void weight(String s, String t, int w) {
+            weights.put(s + ":" + t, w);
+        }
+
+        public static void setRankSep(double value) {
+            rankSep = value;
+        }
+
+        public static void setFontSize(int size) {
+            fontsize = size;
+        }
+
+        public static void setFontColor(String color) {
+            fontColor = color;
+        }
+
+        public static void setArrowSize(int size) {
+            arrowSize = size;
+        }
+
+        public static void setArrowWidth(int width) {
+            arrowWidth = width;
+        }
+    }
+}
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleExportsAnalyzer.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleExportsAnalyzer.java	Thu Mar 16 20:47:03 2017 +0000
@@ -181,7 +181,7 @@
         RootModule(String name) {
             super(name);
 
-            ModuleDescriptor.Builder builder = ModuleDescriptor.module(name);
+            ModuleDescriptor.Builder builder = ModuleDescriptor.newModule(name);
             this.descriptor = builder.build();
         }
 
--- a/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleInfoBuilder.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jdeps/share/classes/com/sun/tools/jdeps/ModuleInfoBuilder.java	Thu Mar 16 20:47:03 2017 +0000
@@ -43,10 +43,12 @@
 import java.util.Comparator;
 import java.util.HashMap;
 import java.util.List;
+import java.util.Locale;
 import java.util.Map;
 import java.util.Optional;
 import java.util.Set;
 import java.util.function.Function;
+import java.util.stream.Collectors;
 import java.util.stream.Stream;
 import static java.util.stream.Collectors.*;
 
@@ -60,8 +62,8 @@
     final Analyzer analyzer;
 
     // an input JAR file (loaded as an automatic module for analysis)
-    // maps to an explicit module to generate module-info.java
-    final Map<Module, Module> automaticToExplicitModule;
+    // maps to a normal module to generate module-info.java
+    final Map<Module, Module> automaticToNormalModule;
     public ModuleInfoBuilder(JdepsConfiguration configuration,
                              List<String> args,
                              Path outputdir,
@@ -78,20 +80,20 @@
             .map(fn -> Paths.get(fn))
             .collect(toList());
 
-        // automatic module to convert to explicit module
-        this.automaticToExplicitModule = ModuleFinder.of(paths.toArray(new Path[0]))
+        // automatic module to convert to normal module
+        this.automaticToNormalModule = ModuleFinder.of(paths.toArray(new Path[0]))
                 .findAll().stream()
                 .map(configuration::toModule)
                 .collect(toMap(Function.identity(), Function.identity()));
 
-        Optional<Module> om = automaticToExplicitModule.keySet().stream()
+        Optional<Module> om = automaticToNormalModule.keySet().stream()
                                     .filter(m -> !m.descriptor().isAutomatic())
                                     .findAny();
         if (om.isPresent()) {
             throw new UncheckedBadArgs(new BadArgs("err.genmoduleinfo.not.jarfile",
                                                    om.get().getPathName()));
         }
-        if (automaticToExplicitModule.isEmpty()) {
+        if (automaticToNormalModule.isEmpty()) {
             throw new UncheckedBadArgs(new BadArgs("err.invalid.path", args));
         }
     }
@@ -115,13 +117,13 @@
                 Path file = outputdir.resolve(m.name()).resolve("module-info.java");
 
                 // computes requires and requires transitive
-                Module explicitModule = toExplicitModule(m, apiDeps);
-                if (explicitModule != null) {
-                    automaticToExplicitModule.put(m, explicitModule);
+                Module normalModule = toNormalModule(m, apiDeps);
+                if (normalModule != null) {
+                    automaticToNormalModule.put(m, normalModule);
 
                     // generate module-info.java
                     System.out.format("writing to %s%n", file);
-                    writeModuleInfo(file,  explicitModule.descriptor());
+                    writeModuleInfo(file,  normalModule.descriptor());
                 } else {
                     // find missing dependences
                     System.out.format("Missing dependence: %s not generated%n", file);
@@ -139,7 +141,7 @@
         return m == NOT_FOUND || m == REMOVED_JDK_INTERNALS;
     }
 
-    private Module toExplicitModule(Module module, Set<Archive> requiresTransitive)
+    private Module toNormalModule(Module module, Set<Archive> requiresTransitive)
         throws IOException
     {
         // done analysis
@@ -159,21 +161,21 @@
             .map(Archive::getModule)
             .forEach(d -> requires.putIfAbsent(d.name(), Boolean.FALSE));
 
-        return module.toStrictModule(requires);
+        return module.toNormalModule(requires);
     }
 
     /**
      * Returns the stream of resulting modules
      */
     Stream<Module> modules() {
-        return automaticToExplicitModule.values().stream();
+        return automaticToNormalModule.values().stream();
     }
 
     /**
      * Returns the stream of resulting ModuleDescriptors
      */
     public Stream<ModuleDescriptor> descriptors() {
-        return automaticToExplicitModule.entrySet().stream()
+        return automaticToNormalModule.entrySet().stream()
                     .map(Map.Entry::getValue)
                     .map(Module::descriptor);
     }
@@ -205,13 +207,14 @@
         md.requires().stream()
           .filter(req -> !req.name().equals("java.base"))   // implicit requires
           .sorted(Comparator.comparing(Requires::name))
-          .forEach(req -> writer.format("    requires %s;%n", req));
+          .forEach(req -> writer.format("    requires %s;%n",
+                                        toString(req.modifiers(), req.name())));
 
         if (!open) {
             md.exports().stream()
               .peek(exp -> {
-                 if (exp.targets().size() > 0)
-                    throw new InternalError(md.name() + " qualified exports: " + exp);
+                  if (exp.isQualified())
+                      throw new InternalError(md.name() + " qualified exports: " + exp);
               })
               .sorted(Comparator.comparing(Exports::source))
               .forEach(exp -> writer.format("    exports %s;%n", exp.source()));
@@ -231,7 +234,16 @@
     }
 
     private Set<Module> automaticModules() {
-        return automaticToExplicitModule.keySet();
+        return automaticToNormalModule.keySet();
+    }
+
+    /**
+     * Returns a string containing the given set of modifiers and label.
+     */
+    private static <M> String toString(Set<M> mods, String what) {
+        return (Stream.concat(mods.stream().map(e -> e.toString().toLowerCase(Locale.US)),
+                              Stream.of(what)))
+                      .collect(Collectors.joining(" "));
     }
 
     /**
--- a/langtools/src/jdk.jdeps/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jdeps/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /** Defines tools for analysing dependencies in Java libraries and programs, including
  *  the <em>jdeps</em> and <em>javap</em> tools.
+ *
+ *  @since 9
  */
 module jdk.jdeps {
     requires java.base;
--- a/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/debug/InternalDebugControl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/debug/InternalDebugControl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -90,6 +90,17 @@
     }
 
     /**
+     * Release a JShell instance.
+     *
+     * @param state the JShell instance
+     */
+    public static void release(JShell state) {
+        if (debugMap != null) {
+            debugMap.remove(state);
+        }
+    }
+
+    /**
      * Tests if any of the specified debug flags are enabled.
      *
      * @param state the JShell instance
--- a/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ConsoleIOContext.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/ConsoleIOContext.java	Thu Mar 16 20:47:03 2017 +0000
@@ -310,6 +310,8 @@
                         int firstLine = 0;
 
                         PRINT_PAGE: while (true) {
+                            in.print(lastNote.replaceAll(".", " ") + ConsoleReader.RESET_LINE);
+
                             int toPrint = height - 1;
 
                             while (toPrint > 0 && firstLine < lines.length) {
--- a/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/Feedback.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/Feedback.java	Thu Mar 16 20:47:03 2017 +0000
@@ -116,6 +116,13 @@
                 name, type, value, unresolved, errorLines);
     }
 
+    public String format(String field, FormatCase fc, FormatAction fa, FormatWhen fw,
+                    FormatResolve fr, FormatUnresolved fu, FormatErrors fe,
+                    String name, String type, String value, String unresolved, List<String> errorLines) {
+        return mode.format(field, fc, fa, fw, fr, fu, fe,
+                name, type, value, unresolved, errorLines);
+    }
+
     public String truncateVarValue(String value) {
         return mode.truncateVarValue(value);
     }
@@ -463,6 +470,14 @@
         String format(FormatCase fc, FormatAction fa, FormatWhen fw,
                     FormatResolve fr, FormatUnresolved fu, FormatErrors fe,
                     String name, String type, String value, String unresolved, List<String> errorLines) {
+            return format("display", fc, fa, fw, fr, fu, fe,
+                name, type, value, unresolved, errorLines);
+        }
+
+        // Compute the display output given full context and values
+        String format(String field, FormatCase fc, FormatAction fa, FormatWhen fw,
+                    FormatResolve fr, FormatUnresolved fu, FormatErrors fe,
+                    String name, String type, String value, String unresolved, List<String> errorLines) {
             // Convert the context into a bit representation used as selectors for store field formats
             long bits = bits(fc, fa, fw, fr, fu, fe);
             String fname = name==null? "" : name;
@@ -476,7 +491,7 @@
                             fname, ftype, fvalue, funresolved, "*cannot-use-errors-here*", el))
                     .collect(joining());
             return String.format(
-                    format("display", bits),
+                    format(field, bits),
                     fname, ftype, fvalue, funresolved, errors, "*cannot-use-err-here*");
         }
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/JShellTool.java	Thu Mar 16 20:47:03 2017 +0000
@@ -36,12 +36,9 @@
 import java.io.PrintStream;
 import java.io.Reader;
 import java.io.StringReader;
-import java.net.URL;
 import java.nio.charset.Charset;
-import java.nio.file.AccessDeniedException;
 import java.nio.file.FileSystems;
 import java.nio.file.Files;
-import java.nio.file.NoSuchFileException;
 import java.nio.file.Path;
 import java.nio.file.Paths;
 import java.text.MessageFormat;
@@ -352,9 +349,56 @@
             }
         }
 
+        // check that the supplied string represent valid class/module paths
+        // converting any ~/ to user home
+        private Collection<String> validPaths(Collection<String> vals, String context, boolean isModulePath) {
+            Stream<String> result = vals.stream()
+                    .map(s -> Arrays.stream(s.split(File.pathSeparator))
+                        .map(sp -> toPathResolvingUserHome(sp))
+                        .filter(p -> checkValidPathEntry(p, context, isModulePath))
+                        .map(p -> p.toString())
+                        .collect(Collectors.joining(File.pathSeparator)));
+            if (failed) {
+                return Collections.emptyList();
+            } else {
+                return result.collect(toList());
+            }
+        }
+
+        // Adapted from compiler method Locations.checkValidModulePathEntry
+        private boolean checkValidPathEntry(Path p, String context, boolean isModulePath) {
+            if (!Files.exists(p)) {
+                msg("jshell.err.file.not.found", context, p);
+                failed = true;
+                return false;
+            }
+            if (Files.isDirectory(p)) {
+                // if module-path, either an exploded module or a directory of modules
+                return true;
+            }
+
+            String name = p.getFileName().toString();
+            int lastDot = name.lastIndexOf(".");
+            if (lastDot > 0) {
+                switch (name.substring(lastDot)) {
+                    case ".jar":
+                        return true;
+                    case ".jmod":
+                        if (isModulePath) {
+                            return true;
+                        }
+                }
+            }
+            msg("jshell.err.arg", context, p);
+            failed = true;
+            return false;
+        }
+
         Options parse(OptionSet options) {
-            addOptions(OptionKind.CLASS_PATH, options.valuesOf(argClassPath));
-            addOptions(OptionKind.MODULE_PATH, options.valuesOf(argModulePath));
+            addOptions(OptionKind.CLASS_PATH,
+                    validPaths(options.valuesOf(argClassPath), "--class-path", false));
+            addOptions(OptionKind.MODULE_PATH,
+                    validPaths(options.valuesOf(argModulePath), "--module-path", true));
             addOptions(OptionKind.ADD_MODULES, options.valuesOf(argAddModules));
             addOptions(OptionKind.ADD_EXPORTS, options.valuesOf(argAddExports).stream()
                     .map(mp -> mp.contains("=") ? mp : mp + "=ALL-UNNAMED")
@@ -812,6 +856,12 @@
         }
     }
 
+    /**
+     * The entry point into the JShell tool.
+     *
+     * @param args the command-line arguments
+     * @throws Exception catastrophic fatal exception
+     */
     public void start(String[] args) throws Exception {
         OptionParserCommandLine commandLineArgs = new OptionParserCommandLine();
         options = commandLineArgs.parse(args);
@@ -842,30 +892,33 @@
                 hardmsg("jshell.msg.welcome", version());
             }
             // Be sure history is always saved so that user code isn't lost
-            Runtime.getRuntime().addShutdownHook(new Thread() {
+            Thread shutdownHook = new Thread() {
                 @Override
                 public void run() {
                     replayableHistory.storeHistory(prefs);
                 }
-            });
+            };
+            Runtime.getRuntime().addShutdownHook(shutdownHook);
             // execute from user input
             try (IOContext in = new ConsoleIOContext(this, cmdin, console)) {
-                start(in);
+                while (regenerateOnDeath) {
+                    if (!live) {
+                        resetState();
+                    }
+                    run(in);
+                }
+            } finally {
+                replayableHistory.storeHistory(prefs);
+                closeState();
+                try {
+                    Runtime.getRuntime().removeShutdownHook(shutdownHook);
+                } catch (Exception ex) {
+                    // ignore, this probably caused by VM aready being shutdown
+                    // and this is the last act anyhow
+                }
             }
         }
-    }
-
-    private void start(IOContext in) {
-        try {
-            while (regenerateOnDeath) {
-                if (!live) {
-                    resetState();
-                }
-                run(in);
-            }
-        } finally {
-            closeState();
-        }
+        closeState();
     }
 
     private EditorSetting configEditor() {
@@ -1019,6 +1072,8 @@
         live = false;
         JShell oldState = state;
         if (oldState != null) {
+            state = null;
+            analysis = null;
             oldState.unsubscribe(shutdownSubscription); // No notification
             oldState.close();
         }
@@ -2006,7 +2061,6 @@
     private boolean cmdExit() {
         regenerateOnDeath = false;
         live = false;
-        replayableHistory.storeHistory(prefs);
         fluffmsg("jshell.msg.goodbye");
         return true;
     }
@@ -2614,9 +2668,16 @@
         if (stream == null) {
             return false;
         }
-        stream.forEachOrdered(mk
-                -> hard("  %s %s", mk.name(), mk.signature())
-        );
+        stream.forEachOrdered(meth -> {
+            String sig = meth.signature();
+            int i = sig.lastIndexOf(")") + 1;
+            if (i <= 0) {
+                hard("  %s", meth.name());
+            } else {
+                hard("  %s %s%s", sig.substring(i), meth.name(), sig.substring(0, i));
+            }
+            printSnippetStatus(meth, true);
+        });
         return true;
     }
 
@@ -2648,6 +2709,7 @@
                     break;
             }
             hard("  %s %s", kind, ck.name());
+            printSnippetStatus(ck, true);
         });
         return true;
     }
@@ -2837,7 +2899,8 @@
                         return true;
                     }
                 } else {
-                    new DisplayEvent(ste, false, ste.value(), diagnostics).displayDeclarationAndValue();
+                    new DisplayEvent(ste, FormatWhen.PRIMARY, ste.value(), diagnostics)
+                            .displayDeclarationAndValue();
                 }
             } else {
                 if (diagnostics.isEmpty()) {
@@ -2851,7 +2914,8 @@
                 List<Diag> other = errorsOnly(diagnostics);
 
                 // display update information
-                new DisplayEvent(ste, true, ste.value(), other).displayDeclarationAndValue();
+                new DisplayEvent(ste, FormatWhen.UPDATE, ste.value(), other)
+                        .displayDeclarationAndValue();
             }
         }
         return false;
@@ -2889,10 +2953,7 @@
     }
     //where
     void printUnresolvedException(UnresolvedReferenceException ex) {
-        DeclarationSnippet corralled =  ex.getSnippet();
-        List<Diag> otherErrors = errorsOnly(state.diagnostics(corralled).collect(toList()));
-        new DisplayEvent(corralled, state.status(corralled), FormatAction.USED, true, null, otherErrors)
-                .displayDeclarationAndValue();
+        printSnippetStatus(ex.getSnippet(), false);
     }
     //where
     void printEvalException(EvalException ex) {
@@ -2934,23 +2995,38 @@
         return act;
     }
 
+    void printSnippetStatus(DeclarationSnippet sn, boolean resolve) {
+        List<Diag> otherErrors = errorsOnly(state.diagnostics(sn).collect(toList()));
+        new DisplayEvent(sn, state.status(sn), resolve, otherErrors)
+                .displayDeclarationAndValue();
+    }
+
     class DisplayEvent {
         private final Snippet sn;
         private final FormatAction action;
-        private final boolean update;
+        private final FormatWhen update;
         private final String value;
         private final List<String> errorLines;
         private final FormatResolve resolution;
         private final String unresolved;
         private final FormatUnresolved unrcnt;
         private final FormatErrors errcnt;
+        private final boolean resolve;
 
-        DisplayEvent(SnippetEvent ste, boolean update, String value, List<Diag> errors) {
-            this(ste.snippet(), ste.status(), toAction(ste.status(), ste.previousStatus(), ste.isSignatureChange()), update, value, errors);
+        DisplayEvent(SnippetEvent ste, FormatWhen update, String value, List<Diag> errors) {
+            this(ste.snippet(), ste.status(), false,
+                    toAction(ste.status(), ste.previousStatus(), ste.isSignatureChange()),
+                    update, value, errors);
         }
 
-        DisplayEvent(Snippet sn, Status status, FormatAction action, boolean update, String value, List<Diag> errors) {
+        DisplayEvent(Snippet sn, Status status, boolean resolve, List<Diag> errors) {
+            this(sn, status, resolve, FormatAction.USED, FormatWhen.UPDATE, null, errors);
+        }
+
+        private DisplayEvent(Snippet sn, Status status, boolean resolve,
+                FormatAction action, FormatWhen update, String value, List<Diag> errors) {
             this.sn = sn;
+            this.resolve =resolve;
             this.action = action;
             this.update = update;
             this.value = value;
@@ -2958,6 +3034,12 @@
             for (Diag d : errors) {
                 displayDiagnostics(sn.source(), d, errorLines);
             }
+            if (resolve) {
+                // resolve needs error lines indented
+                for (int i = 0; i < errorLines.size(); ++i) {
+                    errorLines.set(i, "    " + errorLines.get(i));
+                }
+            }
             long unresolvedCount;
             if (sn instanceof DeclarationSnippet && (status == Status.RECOVERABLE_DEFINED || status == Status.RECOVERABLE_NOT_DEFINED)) {
                 resolution = (status == Status.RECOVERABLE_NOT_DEFINED)
@@ -3012,10 +3094,17 @@
         }
 
         private void custom(FormatCase fcase, String name, String type) {
-            String display = feedback.format(fcase, action, (update ? FormatWhen.UPDATE : FormatWhen.PRIMARY),
-                    resolution, unrcnt, errcnt,
-                    name, type, value, unresolved, errorLines);
-            if (interactive()) {
+            if (resolve) {
+                String resolutionErrors = feedback.format("resolve", fcase, action, update,
+                        resolution, unrcnt, errcnt,
+                        name, type, value, unresolved, errorLines);
+                if (!resolutionErrors.trim().isEmpty()) {
+                    hard("    %s", resolutionErrors);
+                }
+            } else if (interactive()) {
+                String display = feedback.format(fcase, action, update,
+                        resolution, unrcnt, errcnt,
+                        name, type, value, unresolved, errorLines);
                 cmdout.print(display);
             }
         }
--- a/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/resources/l10n.properties	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/internal/jshell/tool/resources/l10n.properties	Thu Mar 16 20:47:03 2017 +0000
@@ -650,7 +650,7 @@
    varinit    -- variable declaration with init\n\t\
    expression -- expression -- note: {name}==scratch-variable-name\n\t\
    varvalue   -- variable value expression\n\t\
-   assignment -- assign variable\n\t\
+   assignment -- assign variable\n\
 The action selector kind describes what happened to the snippet.  The values are:\n\t\
    added     -- snippet has been added\n\t\
    modified  -- an existing snippet has been modified\n\t\
@@ -845,12 +845,12 @@
 /set format verbose action '  update overwrote' overwrote-update    \n\
 /set format verbose action '  update dropped' dropped-update    \n\
 \n\
-/set format verbose until ', however, it cannot be instanciated or its methods invoked until'   defined-class-primary    \n\
+/set format verbose until ', however, it cannot be instantiated or its methods invoked until'   defined-class-primary    \n\
 /set format verbose until ', however, its methods cannot be invoked until'                      defined-interface-primary    \n\
 /set format verbose until ', however, it cannot be used until'                                  defined-enum,annotation-primary    \n\
 /set format verbose until ', however, it cannot be invoked until'                               defined-method-primary    \n\
 /set format verbose until ', however, it cannot be referenced until'                            notdefined-primary    \n\
-/set format verbose until ' which cannot be instanciated or its methods invoked until'          defined-class-update    \n\
+/set format verbose until ' which cannot be instantiated or its methods invoked until'          defined-class-update    \n\
 /set format verbose until ' whose methods cannot be invoked until'                              defined-interface-update    \n\
 /set format verbose until ' which cannot be invoked until'                                      defined-method-update    \n\
 /set format verbose until ' which cannot be referenced until'                                   notdefined-update    \n\
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/DeclarationSnippet.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/DeclarationSnippet.java	Thu Mar 16 20:47:03 2017 +0000
@@ -45,6 +45,8 @@
  * <code>DeclarationSnippet</code> is immutable: an access to
  * any of its methods will always return the same result.
  * and thus is thread-safe.
+ *
+ * @since 9
  */
 public abstract class DeclarationSnippet extends PersistentSnippet {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/Diag.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/Diag.java	Thu Mar 16 20:47:03 2017 +0000
@@ -30,6 +30,8 @@
 
 /**
  * Diagnostic information for a Snippet.
+ *
+ * @since 9
  * @see jdk.jshell.JShell#diagnostics(jdk.jshell.Snippet)
  */
 public abstract class Diag {
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/ErroneousSnippet.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/ErroneousSnippet.java	Thu Mar 16 20:47:03 2017 +0000
@@ -34,6 +34,8 @@
  * <code>ErroneousSnippet</code> is immutable: an access to
  * any of its methods will always return the same result.
  * and thus is thread-safe.
+ *
+ * @since 9
  */
 public class ErroneousSnippet extends Snippet {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/EvalException.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/EvalException.java	Thu Mar 16 20:47:03 2017 +0000
@@ -38,6 +38,8 @@
  * the Snippet id and for snippets without a method name (for example an
  * expression) <code>StackTraceElement.getMethodName()</code> will be the
  * empty string.
+ *
+ * @since 9
  */
 @SuppressWarnings("serial")             // serialVersionUID intentionally omitted
 public class EvalException extends JShellException {
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/ExpressionSnippet.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/ExpressionSnippet.java	Thu Mar 16 20:47:03 2017 +0000
@@ -34,6 +34,8 @@
  * <code>ExpressionSnippet</code> is immutable: an access to
  * any of its methods will always return the same result.
  * and thus is thread-safe.
+ *
+ * @since 9
  * @jls 15: Expression.
  */
 public class ExpressionSnippet extends Snippet {
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/ImportSnippet.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/ImportSnippet.java	Thu Mar 16 20:47:03 2017 +0000
@@ -34,6 +34,8 @@
  * {@code ImportSnippet} is immutable: an access to
  * any of its methods will always return the same result.
  * and thus is thread-safe.
+ *
+ * @since 9
  * @jls 8.3: importDeclaration.
  */
 public class ImportSnippet extends PersistentSnippet {
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/JShell.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/JShell.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017 Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -44,8 +44,10 @@
 import java.util.function.BiFunction;
 import java.util.function.Consumer;
 
+import java.util.function.Function;
 import java.util.function.Supplier;
 import java.util.stream.Stream;
+import javax.tools.StandardJavaFileManager;
 import jdk.internal.jshell.debug.InternalDebugControl;
 import jdk.jshell.Snippet.Status;
 import jdk.jshell.spi.ExecutionControl.EngineTerminationException;
@@ -77,7 +79,9 @@
  * <p>
  * This class is not thread safe, except as noted, all access should be through
  * a single thread.
+ *
  * @author Robert Field
+ * @since 9
  */
 public class JShell implements AutoCloseable {
 
@@ -92,6 +96,7 @@
     final BiFunction<Snippet, Integer, String> idGenerator;
     final List<String> extraRemoteVMOptions;
     final List<String> extraCompilerOptions;
+    final Function<StandardJavaFileManager, StandardJavaFileManager> fileManagerMapping;
 
     private int nextKeyIndex = 1;
 
@@ -115,6 +120,7 @@
         this.idGenerator = b.idGenerator;
         this.extraRemoteVMOptions = b.extraRemoteVMOptions;
         this.extraCompilerOptions = b.extraCompilerOptions;
+        this.fileManagerMapping = b.fileManagerMapping;
         try {
             if (b.executionControlProvider != null) {
                 executionControl = b.executionControlProvider.generate(new ExecutionEnvImpl(),
@@ -171,6 +177,7 @@
         ExecutionControlProvider executionControlProvider;
         Map<String,String> executionControlParameters;
         String executionControlSpec;
+        Function<StandardJavaFileManager, StandardJavaFileManager> fileManagerMapping;
 
         Builder() { }
 
@@ -365,6 +372,28 @@
         }
 
         /**
+         * Configure the {@code FileManager} to be used by compilation and
+         * source analysis.
+         * If not set or passed null, the compiler's standard file manager will
+         * be used (identity mapping).
+         * For use in special applications where the compiler's normal file
+         * handling needs to be overridden.  See the file manager APIs for more
+         * information.
+         * The file manager input enables forwarding file managers, if this
+         * is not needed, the incoming file manager can be ignored (constant
+         * function).
+         *
+         * @param mapping a function that given the compiler's standard file
+         * manager, returns a file manager to use
+         * @return the {@code Builder} instance (for use in chained
+         * initialization)
+         */
+        public Builder fileManager(Function<StandardJavaFileManager, StandardJavaFileManager> mapping) {
+            this.fileManagerMapping = mapping;
+            return this;
+        }
+
+        /**
          * Builds a JShell state engine. This is the entry-point to all JShell
          * functionality. This creates a remote process for execution. It is
          * thus important to close the returned instance.
@@ -501,6 +530,7 @@
      * @throws IllegalStateException if this {@code JShell} instance is closed.
      */
     public void addToClasspath(String path) {
+        checkIfAlive();
         // Compiler
         taskFactory.addToClasspath(path);
         // Runtime
@@ -543,17 +573,7 @@
      */
     @Override
     public void close() {
-        if (!closed) {
-            closeDown();
-            try {
-                executionControl().close();
-            } catch (Throwable ex) {
-                // don't care about exceptions on close
-            }
-            if (sourceCodeAnalysis != null) {
-                sourceCodeAnalysis.close();
-            }
-        }
+        closeDown();
     }
 
     /**
@@ -826,6 +846,15 @@
             } catch (Throwable thr) {
                 // Don't care about dying exceptions
             }
+            try {
+                executionControl().close();
+            } catch (Throwable ex) {
+                // don't care about exceptions on close
+            }
+            if (sourceCodeAnalysis != null) {
+                sourceCodeAnalysis.close();
+            }
+            InternalDebugControl.release(this);
         }
     }
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/JShellException.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/JShellException.java	Thu Mar 16 20:47:03 2017 +0000
@@ -27,6 +27,8 @@
 
 /**
  * The superclass of JShell generated exceptions
+ *
+ * @since 9
  */
 @SuppressWarnings("serial")             // serialVersionUID intentionally omitted
 public class JShellException extends Exception {
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/MemoryFileManager.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/MemoryFileManager.java	Thu Mar 16 20:47:03 2017 +0000
@@ -30,8 +30,6 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.io.OutputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
 import java.net.URI;
 import java.nio.file.FileSystems;
 import java.nio.file.Files;
@@ -71,10 +69,6 @@
 
     private final JShell proc;
 
-    // Upcoming Jigsaw
-    private Method inferModuleNameMethod = null;
-    private Method listLocationsForModulesMethod = null;
-
     Iterable<? extends Path> getLocationAsPaths(Location loc) {
         return this.stdFileManager.getLocationAsPaths(loc);
     }
@@ -165,7 +159,9 @@
     }
 
     public MemoryFileManager(StandardJavaFileManager standardManager, JShell proc) {
-        this.stdFileManager = standardManager;
+        this.stdFileManager = proc.fileManagerMapping != null
+                ? proc.fileManagerMapping.apply(standardManager)
+                : standardManager;
         this.proc = proc;
     }
 
@@ -184,43 +180,6 @@
         return new SourceMemoryJavaFileObject(origin, name, code);
     }
 
-    // Make compatible with Jigsaw
-    public String inferModuleName(Location location) {
-        try {
-            if (inferModuleNameMethod == null) {
-                inferModuleNameMethod = JavaFileManager.class.getDeclaredMethod("inferModuleName", Location.class);
-            }
-            @SuppressWarnings("unchecked")
-            String result = (String) inferModuleNameMethod.invoke(stdFileManager, location);
-            return result;
-        } catch (NoSuchMethodException | SecurityException ex) {
-            throw new InternalError("Cannot lookup JavaFileManager method", ex);
-        } catch (IllegalAccessException |
-                IllegalArgumentException |
-                InvocationTargetException ex) {
-            throw new InternalError("Cannot invoke JavaFileManager method", ex);
-        }
-    }
-
-    // Make compatible with Jigsaw
-    public Iterable<Set<Location>> listLocationsForModules(Location location) throws IOException {
-        try {
-            if (listLocationsForModulesMethod == null) {
-                listLocationsForModulesMethod = JavaFileManager.class.getDeclaredMethod("listLocationsForModules", Location.class);
-            }
-            @SuppressWarnings("unchecked")
-            Iterable<Set<Location>> result = (Iterable<Set<Location>>) listLocationsForModulesMethod.invoke(stdFileManager, location);
-            return result;
-        } catch (NoSuchMethodException | SecurityException ex) {
-            throw new InternalError("Cannot lookup JavaFileManager method", ex);
-        } catch (IllegalAccessException |
-                IllegalArgumentException |
-                InvocationTargetException ex) {
-            throw new InternalError("Cannot invoke JavaFileManager method", ex);
-        }
-    }
-
-
     /**
      * Returns a class loader for loading plug-ins from the given location. For
      * example, to load annotation processors, a compiler will request a class
@@ -580,6 +539,26 @@
                 ", sibling: " + sibling);
     }
 
+    @Override
+    public Location getLocationForModule(Location location, String moduleName) throws IOException {
+        return stdFileManager.getLocationForModule(location, moduleName);
+    }
+
+    @Override
+    public Location getLocationForModule(Location location, JavaFileObject fo, String pkgName) throws IOException {
+        return stdFileManager.getLocationForModule(location, fo, pkgName);
+    }
+
+    @Override
+    public String inferModuleName(Location location) throws IOException {
+        return stdFileManager.inferModuleName(location);
+    }
+
+    @Override
+    public Iterable<Set<Location>> listLocationsForModules(Location location) throws IOException {
+        return stdFileManager.listLocationsForModules(location);
+    }
+
     /**
      * Flushes any resources opened for output by this file manager
      * directly or indirectly.  Flushing a closed file manager has no
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/MethodSnippet.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/MethodSnippet.java	Thu Mar 16 20:47:03 2017 +0000
@@ -35,6 +35,8 @@
  * <code>MethodSnippet</code> is immutable: an access to
  * any of its methods will always return the same result.
  * and thus is thread-safe.
+ *
+ * @since 9
  * @jls 8.4: MethodDeclaration.
  */
 public class MethodSnippet extends DeclarationSnippet {
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/OuterImportSnippetWrap.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/OuterImportSnippetWrap.java	Thu Mar 16 20:47:03 2017 +0000
@@ -32,7 +32,7 @@
  * The outer wrap for a set of snippets wrapped in a generated class
  * @author Robert Field
  */
-public class OuterImportSnippetWrap extends OuterWrap {
+class OuterImportSnippetWrap extends OuterWrap {
 
     private final Snippet snippet;
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/OuterSnippetsClassWrap.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/OuterSnippetsClassWrap.java	Thu Mar 16 20:47:03 2017 +0000
@@ -35,7 +35,7 @@
  * The outer wrap for a set of snippets wrapped in a generated class
  * @author Robert Field
  */
-public class OuterSnippetsClassWrap extends OuterWrap {
+class OuterSnippetsClassWrap extends OuterWrap {
 
     private final String className;
     private final LinkedHashMap<Wrap, Snippet> wrapToSnippet;
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/OuterWrapMap.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/OuterWrapMap.java	Thu Mar 16 20:47:03 2017 +0000
@@ -44,7 +44,7 @@
  *
  * @author Robert Field
  */
-public class OuterWrapMap {
+class OuterWrapMap {
 
     private final JShell state;
     private final Map<String,OuterSnippetsClassWrap> classOuters = new HashMap<>();
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/PersistentSnippet.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/PersistentSnippet.java	Thu Mar 16 20:47:03 2017 +0000
@@ -34,6 +34,8 @@
  * <code>PersistentSnippet</code> is immutable: an access to
  * any of its methods will always return the same result.
  * and thus is thread-safe.
+ *
+ * @since 9
  */
 public abstract class PersistentSnippet extends Snippet {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/Snippet.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/Snippet.java	Thu Mar 16 20:47:03 2017 +0000
@@ -39,7 +39,9 @@
  * state engine, query {@code JShell} passing the Snippet.
  * <p>
  * Because it is immutable, {@code Snippet} (and subclasses) is thread-safe.
+ *
  * @author Robert Field
+ * @since 9
  * @see jdk.jshell.JShell#status
  */
 public abstract class Snippet {
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/SnippetEvent.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/SnippetEvent.java	Thu Mar 16 20:47:03 2017 +0000
@@ -38,7 +38,9 @@
  * {@code SnippetEvent} is immutable: an access to
  * any of its methods will always return the same result.
  * and thus is thread-safe.
+ *
  * @author Robert Field
+ * @since 9
  */
 public class SnippetEvent {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/SourceCodeAnalysis.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/SourceCodeAnalysis.java	Thu Mar 16 20:47:03 2017 +0000
@@ -39,6 +39,7 @@
  * etc.
  * Also includes completion suggestions, as might be used in tab-completion.
  *
+ * @since 9
  */
 public abstract class SourceCodeAnalysis {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/StatementSnippet.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/StatementSnippet.java	Thu Mar 16 20:47:03 2017 +0000
@@ -34,6 +34,8 @@
  * <code>StatementSnippet</code> is immutable: an access to
  * any of its methods will always return the same result.
  * and thus is thread-safe.
+ *
+ * @since 9
  * @jls 14.5: Statement.
  */
 public class StatementSnippet extends Snippet {
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/TypeDeclSnippet.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/TypeDeclSnippet.java	Thu Mar 16 20:47:03 2017 +0000
@@ -36,6 +36,8 @@
  * <code>TypeDeclSnippet</code> is immutable: an access to
  * any of its methods will always return the same result.
  * and thus is thread-safe.
+ *
+ * @since 9
  */
 public class TypeDeclSnippet extends DeclarationSnippet {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/UnresolvedReferenceException.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/UnresolvedReferenceException.java	Thu Mar 16 20:47:03 2017 +0000
@@ -36,6 +36,8 @@
  * the Snippet id and for snippets without a method name (for example an
  * expression) <code>StackTraceElement.getName()</code> will be the
  * empty string.
+ *
+ * @since 9
  */
 @SuppressWarnings("serial")             // serialVersionUID intentionally omitted
 public class UnresolvedReferenceException extends JShellException {
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/VarSnippet.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/VarSnippet.java	Thu Mar 16 20:47:03 2017 +0000
@@ -35,6 +35,8 @@
  * <code>VarSnippet</code> is immutable: an access to
  * any of its methods will always return the same result.
  * and thus is thread-safe.
+ *
+ * @since 9
  * @jls 8.3: FieldDeclaration.
  */
 public class VarSnippet extends DeclarationSnippet {
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/DirectExecutionControl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/DirectExecutionControl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -39,6 +39,7 @@
  *
  * @author Robert Field
  * @author Jan Lahoda
+ * @since 9
  */
 public class DirectExecutionControl implements ExecutionControl {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/FailOverExecutionControlProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/FailOverExecutionControlProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -37,6 +37,8 @@
 
 /**
  * Tries other providers in sequence until one works.
+ *
+ * @since 9
  */
 public class FailOverExecutionControlProvider  implements ExecutionControlProvider{
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiDefaultExecutionControl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -33,6 +33,7 @@
 import java.net.ServerSocket;
 import java.net.Socket;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -60,6 +61,7 @@
  *
  * @author Robert Field
  * @author Jan Lahoda
+ * @since 9
  */
 public class JdiDefaultExecutionControl extends JdiExecutionControl {
 
@@ -97,7 +99,8 @@
 
             // Set-up the JDI connection
             JdiInitiator jdii = new JdiInitiator(port,
-                    env.extraRemoteVMOptions(), remoteAgent, isLaunch, host, timeout);
+                    env.extraRemoteVMOptions(), remoteAgent, isLaunch, host,
+                    timeout, Collections.emptyMap());
             VirtualMachine vm = jdii.vm();
             Process process = jdii.process();
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiExecutionControl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiExecutionControl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -37,7 +37,9 @@
 import static java.util.stream.Collectors.toMap;
 
 /**
- * Abstract JDI implementation of {@link jdk.jshell.spi.ExecutionControl}
+ * Abstract JDI implementation of {@link jdk.jshell.spi.ExecutionControl}.
+ *
+ * @since 9
  */
 public abstract class JdiExecutionControl extends StreamingExecutionControl implements ExecutionControl {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiExecutionControlProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiExecutionControlProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -35,7 +35,9 @@
 
 /**
  * A provider of remote JDI-controlled execution engines.
+ *
  * @author Robert Field
+ * @since 9
  */
 public class JdiExecutionControlProvider implements ExecutionControlProvider {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiInitiator.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/JdiInitiator.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016,2017 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
@@ -47,6 +47,8 @@
 /**
  * Sets up a JDI connection, providing the resulting JDI {@link VirtualMachine}
  * and the {@link Process} the remote agent is running in.
+ *
+ * @since 9
  */
 public class JdiInitiator {
 
@@ -66,16 +68,20 @@
      * Start the remote agent and establish a JDI connection to it.
      *
      * @param port the socket port for (non-JDI) commands
-     * @param remoteVMOptions any user requested VM options
+     * @param remoteVMOptions any user requested VM command-line options
      * @param remoteAgent full class name of remote agent to launch
      * @param isLaunch does JDI do the launch? That is, LaunchingConnector,
      * otherwise we start explicitly and use ListeningConnector
      * @param host explicit hostname to use, if null use discovered
      * hostname, applies to listening only (!isLaunch)
-     * @param timeout the start-up time-out in milliseconds
+     * @param timeout the start-up time-out in milliseconds. If zero or negative,
+     * will not wait thus will timeout immediately if not already started.
+     * @param customConnectorArgs custom arguments passed to the connector.
+     * These are JDI com.sun.jdi.connect.Connector arguments.
      */
     public JdiInitiator(int port, List<String> remoteVMOptions, String remoteAgent,
-            boolean isLaunch, String host, int timeout) {
+            boolean isLaunch, String host, int timeout,
+            Map<String, String> customConnectorArgs) {
         this.remoteAgent = remoteAgent;
         this.connectTimeout = (int) (timeout * CONNECT_TIMEOUT_FACTOR);
         String connectorName
@@ -96,6 +102,7 @@
                 argumentName2Value.put("localAddress", host);
             }
         }
+        argumentName2Value.putAll(customConnectorArgs);
         this.connectorArgs = mergeConnectorArgs(connector, argumentName2Value);
         this.vm = isLaunch
                 ? launchTarget()
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/LoaderDelegate.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/LoaderDelegate.java	Thu Mar 16 20:47:03 2017 +0000
@@ -34,6 +34,8 @@
  * This interface specifies the loading specific subset of
  * {@link jdk.jshell.spi.ExecutionControl}.  For use in encapsulating the
  * {@link java.lang.ClassLoader} implementation.
+ *
+ * @since 9
  */
 public interface LoaderDelegate {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/LocalExecutionControl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/LocalExecutionControl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -33,6 +33,7 @@
  * in the same JVM as the JShell-core.
  *
  * @author Grigory Ptashko
+ * @since 9
  */
 public class LocalExecutionControl extends DirectExecutionControl {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/LocalExecutionControlProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/LocalExecutionControlProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -32,7 +32,9 @@
 
 /**
  * A provider of execution engines which run in the same process as JShell.
+ *
  * @author Robert Field
+ * @since 9
  */
 public class LocalExecutionControlProvider implements ExecutionControlProvider{
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/RemoteExecutionControl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/RemoteExecutionControl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -45,6 +45,7 @@
  *
  * @author Jan Lahoda
  * @author Robert Field
+ * @since 9
  */
 public class RemoteExecutionControl extends DirectExecutionControl implements ExecutionControl {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/StreamingExecutionControl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/StreamingExecutionControl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -37,6 +37,7 @@
  * execution takes place.
  *
  * @author Robert Field
+ * @since 9
  */
 public class StreamingExecutionControl implements ExecutionControl {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/Util.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/Util.java	Thu Mar 16 20:47:03 2017 +0000
@@ -53,6 +53,7 @@
  *
  * @author Jan Lahoda
  * @author Robert Field
+ * @since 9
  */
 public class Util {
 
@@ -60,7 +61,7 @@
     private static final int TAG_CLOSED = 1;
     private static final int TAG_EXCEPTION = 2;
 
-    // never instanciated
+    // never instantiated
     private Util() {}
 
     /**
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/package-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/execution/package-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -30,5 +30,7 @@
  * Also, provides related communication utilities.
  * This package may be used to define alternative execution engines.
  * The default JShell execution engine is included.
+ *
+ * @since 9
  */
 package jdk.jshell.execution;
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/package-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/package-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -140,6 +140,8 @@
  * provide source boundary and completeness analysis to address cases like
  * those.  <code>SourceCodeAnalysis</code> also provides suggested completions
  * of input, as might be used in tab-completion.
+ *
+ * @since 9
  */
 
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/spi/ExecutionControl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/spi/ExecutionControl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -45,6 +45,8 @@
  * <p>
  * Methods defined in this interface should only be called by the core JShell
  * implementation.
+ *
+ * @since 9
  */
 public interface ExecutionControl extends AutoCloseable {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/spi/ExecutionControlProvider.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/spi/ExecutionControlProvider.java	Thu Mar 16 20:47:03 2017 +0000
@@ -33,7 +33,9 @@
  * evaluate Snippets.  Alternate execution engines can be created by
  * implementing this interface, then configuring JShell with the provider or
  * the providers name and parameter specifier.
+ *
  * @author Robert Field
+ * @since 9
  */
 public interface ExecutionControlProvider {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/spi/ExecutionEnv.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/spi/ExecutionEnv.java	Thu Mar 16 20:47:03 2017 +0000
@@ -36,6 +36,7 @@
  * This interface is designed to provide the access to core JShell functionality
  * needed to implement ExecutionControl.
  *
+ * @since 9
  * @see ExecutionControl
  */
 public interface ExecutionEnv {
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/spi/SPIResolutionException.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/spi/SPIResolutionException.java	Thu Mar 16 20:47:03 2017 +0000
@@ -33,6 +33,8 @@
  * <p>
  * This exception is seen by the execution engine, but not seen by
  * the end user nor through the JShell API.
+ *
+ * @since 9
  */
 @SuppressWarnings("serial")             // serialVersionUID intentionally omitted
 public class SPIResolutionException extends RuntimeException {
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/spi/package-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/spi/package-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -66,6 +66,7 @@
  *   <li>failover:1(jdi),2(jdi:launch(true),timeout(3000)),3(local)</li>
  * </ul>
  *
+ * @since 9
  * @see jdk.jshell.execution for execution implementation support
  */
 package jdk.jshell.spi;
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/tool/JavaShellToolBuilder.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/tool/JavaShellToolBuilder.java	Thu Mar 16 20:47:03 2017 +0000
@@ -40,6 +40,8 @@
  * configuration methods have sensible defaults which will be used if they are
  * not called.. After zero or more calls to configuration methods, the tool is
  * launched with a call to {@link #run(java.lang.String...) }.
+ *
+ * @since 9
  */
 public interface JavaShellToolBuilder {
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/tool/package-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/tool/package-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -47,6 +47,8 @@
  *             .run("--feedback", "silent", "MyStart");
  * }
  * </pre>
+ *
+ * @since 9
  */
 
 
--- a/langtools/src/jdk.jshell/share/classes/jdk/jshell/tool/resources/PRINTING.jsh	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/jdk/jshell/tool/resources/PRINTING.jsh	Thu Mar 16 20:47:03 2017 +0000
@@ -17,5 +17,5 @@
 void println(char s[]) { System.out.println(s); }
 void println(String s) { System.out.println(s); }
 void println(Object obj) { System.out.println(obj); }
-void printf(Locale l, String format, Object... args) { System.out.printf(l, format, args); }
+void printf(java.util.Locale l, String format, Object... args) { System.out.printf(l, format, args); }
 void printf(String format, Object... args) { System.out.printf(format, args); }
--- a/langtools/src/jdk.jshell/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/src/jdk.jshell/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -51,6 +51,8 @@
  *     independent, operate at different levels, and do not share functionality or
  *     definitions.
  * </p>
+ *
+ * @since 9
  */
 module jdk.jshell {
     requires transitive java.compiler;
--- a/langtools/test/ProblemList.txt	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/ProblemList.txt	Thu Mar 16 20:47:03 2017 +0000
@@ -36,7 +36,7 @@
 #
 # jshell
 
-jdk/jshell/UserJdiUserRemoteTest.java                                           8173204    linux-all
+jdk/jshell/UserJdiUserRemoteTest.java                                           8173079    linux-all
 jdk/jshell/UserInputTest.java                                                   8169536    generic-all   
 
 ###########################################################################
--- a/langtools/test/com/sun/javadoc/testNonInlineHtmlTagRemoval/C.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/com/sun/javadoc/testNonInlineHtmlTagRemoval/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -71,4 +71,9 @@
      * caseA <ul type='"a">b'> <li> end of sentence. <li> more </ul>
      */
     public void caseA() {}
+
+    /**
+     * caseB <blockquote>A block quote example:</blockquote>
+     */
+    public void caseB() {}
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/com/sun/javadoc/testNonInlineHtmlTagRemoval/Negative.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+
+public class Negative {
+    /**
+     * case1: A hanging &lt;  : <blockquote>xx</blockquote><
+     */
+    public void case1() {}
+}
--- a/langtools/test/com/sun/javadoc/testNonInlineHtmlTagRemoval/TestNonInlineHtmlTagRemoval.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/com/sun/javadoc/testNonInlineHtmlTagRemoval/TestNonInlineHtmlTagRemoval.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug      8048628
+ * @bug      8048628 8174715
  * @summary  Verify html inline tags are removed correctly in the first sentence.
  * @library  ../lib
  * @modules jdk.javadoc
@@ -39,22 +39,34 @@
     }
 
     @Test
-    void test() {
-        javadoc("-d", "out",
+    void testPositive() {
+        javadoc("-d", "out1",
                 "-sourcepath", testSrc,
                 testSrc("C.java"));
         checkExit(Exit.OK);
 
         checkOutput("C.html", true,
-                "<div class=\"block\">case1 end of sentence.</div>",
-                "<div class=\"block\">case2 end of sentence.</div>",
-                "<div class=\"block\">case3 end of sentence.</div>",
-                "<div class=\"block\">case4 end of sentence.</div>",
-                "<div class=\"block\">case5 end of sentence.</div>",
-                "<div class=\"block\">case6 end of sentence.</div>",
-                "<div class=\"block\">case7 end of sentence.</div>",
-                "<div class=\"block\">case8 end of sentence.</div>",
-                "<div class=\"block\">case9 end of sentence.</div>",
-                "<div class=\"block\">caseA end of sentence.</div>");
+                "<div class=\"block\">case1   end of sentence.</div>",
+                "<div class=\"block\">case2   end of sentence.</div>",
+                "<div class=\"block\">case3   end of sentence.</div>",
+                "<div class=\"block\">case4   end of sentence.</div>",
+                "<div class=\"block\">case5   end of sentence.</div>",
+                "<div class=\"block\">case6   end of sentence.</div>",
+                "<div class=\"block\">case7   end of sentence.</div>",
+                "<div class=\"block\">case8   end of sentence.</div>",
+                "<div class=\"block\">case9   end of sentence.</div>",
+                "<div class=\"block\">caseA   end of sentence.</div>",
+                "<div class=\"block\">caseB A block quote example:</div>");
+    }
+
+    @Test
+    void testNegative() {
+        javadoc("-d", "out2",
+                "-sourcepath", testSrc,
+                testSrc("Negative.java"));
+        checkExit(Exit.FAILED);
+
+        checkOutput("Negative.html", true,
+                "<div class=\"block\">case1: A hanging &lt;  : xx<</div>");
     }
 }
--- a/langtools/test/jdk/javadoc/doclet/testHtmlVersion/TestHtmlVersion.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testHtmlVersion/TestHtmlVersion.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8072945 8081854 8141492 8148985 8150188 4649116 8173707
+ * @bug 8072945 8081854 8141492 8148985 8150188 4649116 8173707 8151743
  * @summary Test the version of HTML generated by the javadoc tool.
  * @author bpatel
  * @library ../lib
@@ -710,6 +710,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">",
                 "<table class=\"constantsSummary\" summary=\"Constant Field Values table, listing constant fields, and values\">");
 
@@ -723,6 +727,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">\n"
                 + "<h1 title=\"Deprecated API\" class=\"title\">Deprecated API</h1>\n"
                 + "<h2 title=\"Contents\">Contents</h2>",
@@ -747,6 +755,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">",
                 "<li class=\"blockList\">\n"
                 + "<h2 title=\"Package\">Package&nbsp;pkg</h2>");
@@ -761,6 +773,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">",
                 "<div class=\"contentContainer\">\n"
                 + "<h2 title=\"Class Hierarchy\">Class Hierarchy</h2>",
@@ -779,6 +795,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"contentContainer\">");
 
         // Negated test for src-html page
@@ -797,6 +817,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">",
                 "<ul class=\"blockList\">\n"
                 + "<li class=\"blockList\">\n"
@@ -1005,6 +1029,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">",
                 "<table class=\"useSummary\" summary=\"Use table, listing packages, and an explanation\">",
                 "<li class=\"blockList\"><a name=\"pkg\">\n"
@@ -1123,6 +1151,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">",
                 "<table class=\"constantsSummary\" summary=\"Constant Field Values table, listing constant fields, and values\">");
 
@@ -1136,6 +1168,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">\n"
                 + "<h1 title=\"Deprecated API\" class=\"title\">Deprecated API</h1>\n"
                 + "<h2 title=\"Contents\">Contents</h2>",
@@ -1160,6 +1196,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">",
                 "<li class=\"blockList\">\n"
                 + "<h2 title=\"Package\">Package&nbsp;pkg</h2>");
@@ -1175,6 +1215,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">",
                 "<h1 class=\"title\">Hierarchy For All Packages</h1>\n"
                 + "<span class=\"packageHierarchyLabel\">Package Hierarchies:</span>",
@@ -1195,6 +1239,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"contentContainer\">");
 
         // Test for src-html page
@@ -1213,6 +1261,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">",
                 "<ul class=\"blockList\">\n"
                 + "<li class=\"blockList\">\n"
@@ -1421,6 +1473,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">",
                 "<table class=\"useSummary\" summary=\"Use table, listing packages, and an explanation\">",
                 "<li class=\"blockList\"><a name=\"pkg\">\n"
--- a/langtools/test/jdk/javadoc/doclet/testJavascript/TestJavascript.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testJavascript/TestJavascript.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2017, 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      4665566 4855876 7025314 8012375 8015997 8016328 8024756 8148985 8151921
+ * @bug      4665566 4855876 7025314 8012375 8015997 8016328 8024756 8148985 8151921 8151743
  * @summary  Verify that the output has the right javascript.
  * @author   jamieh
  * @library  ../lib
@@ -47,7 +47,11 @@
         checkExit(Exit.OK);
 
         checkOutput("pkg/C.html", true,
-                "<a href=\"../index.html?pkg/C.html\" target=\"_top\">Frames</a>");
+                "<a href=\"../index.html?pkg/C.html\" target=\"_top\">Frames</a>",
+                "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>");
 
         checkOutput("TestJavascript.html", true,
                 "<a href=\"index.html?TestJavascript.html\" target=\"_top\">Frames</a>");
@@ -119,5 +123,10 @@
                 + "    }\n"
                 + "    catch(err) {\n"
                 + "    }");
+
+        checkOutput("script.js", true,
+                "$(window).resize(function() {\n"
+                + "        $('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "    });");
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testMissingType/TestMissingType.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,50 @@
+/*
+ * Copyright (c) 2017, 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      8173804
+ * @summary  make sure doclet can handle missing types
+ * @library  ../lib
+ * @modules jdk.javadoc/jdk.javadoc.internal.tool
+ * @build    JavadocTester
+ * @run main TestMissingType
+ */
+
+public class TestMissingType extends JavadocTester {
+
+    public static void main(String... args) throws Exception {
+        TestMissingType tester = new TestMissingType();
+        tester.runTests();
+    }
+
+    @Test
+    void test() {
+        javadoc("-d", "out",
+                "-use",
+                "-sourcepath", testSrc,
+                "p");
+        checkExit(Exit.OK);
+        checkFiles(true, "p/class-use/MissingType.html");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testMissingType/p/MissingType.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,32 @@
+/*
+ * Copyright (c) 2017, 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 p;
+
+public final class MissingType  {
+    /**
+     * Do something with a missing type.
+     *
+     * @param out use the missing type
+     */
+    public void encode(MissingMe out) {}
+}
--- a/langtools/test/jdk/javadoc/doclet/testNavigation/TestNavigation.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testNavigation/TestNavigation.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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      4131628 4664607 7025314 8023700 7198273 8025633 8026567 8081854 8150188
+ * @bug      4131628 4664607 7025314 8023700 7198273 8025633 8026567 8081854 8150188 8151743
  * @summary  Make sure the Next/Prev Class links iterate through all types.
  *           Make sure the navagation is 2 columns, not 3.
  * @author   jamieh
@@ -77,12 +77,20 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<!-- ======== START OF CLASS DATA ======== -->");
 
         checkOutput("pkg/package-summary.html", true,
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">");
     }
 
@@ -98,6 +106,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "</nav>\n"
                 + "</header>\n"
                 + "<!-- ======== START OF CLASS DATA ======== -->");
@@ -106,6 +118,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "</nav>");
     }
 
@@ -121,12 +137,20 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<!-- ======== START OF CLASS DATA ======== -->");
 
         checkOutput("pkg/package-summary.html", false,
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "<div class=\"header\">");
     }
 
@@ -142,6 +166,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "</nav>\n"
                 + "</header>\n"
                 + "<!-- ======== START OF CLASS DATA ======== -->");
@@ -150,6 +178,10 @@
                 "<!-- ========= END OF TOP NAVBAR ========= -->\n"
                 + "</div>\n"
                 + "<div class=\"navPadding\">&nbsp;</div>\n"
+                + "<script type=\"text/javascript\"><!--\n"
+                + "$('.navPadding').css('padding-top', $('.fixedNav').css(\"height\"));\n"
+                + "//-->\n"
+                + "</script>\n"
                 + "</nav>");
     }
 }
--- a/langtools/test/jdk/javadoc/doclet/testNonInlineHtmlTagRemoval/C.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testNonInlineHtmlTagRemoval/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -71,4 +71,9 @@
      * caseA <ul type='"a">b'> <li> end of sentence. <li> more </ul>
      */
     public void caseA() {}
+
+    /**
+     * caseB <blockquote>A block quote example:</blockquote>
+     */
+    public void caseB() {}
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testNonInlineHtmlTagRemoval/Negative.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,29 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+
+public class Negative {
+    /**
+     * case1: A hanging &lt;  : <blockquote>xx</blockquote><
+     */
+    public void case1() {}
+}
--- a/langtools/test/jdk/javadoc/doclet/testNonInlineHtmlTagRemoval/TestNonInlineHtmlTagRemoval.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testNonInlineHtmlTagRemoval/TestNonInlineHtmlTagRemoval.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug      8048628
+ * @bug      8048628 8174715
  * @summary  Verify html inline tags are removed correctly in the first sentence.
  * @library  ../lib
  * @modules jdk.javadoc/jdk.javadoc.internal.tool
@@ -39,8 +39,8 @@
     }
 
     @Test
-    void test() {
-        javadoc("-d", "out",
+    void testPositive() {
+        javadoc("-d", "out1",
                 "-sourcepath", testSrc,
                 testSrc("C.java"));
         checkExit(Exit.OK);
@@ -55,6 +55,18 @@
                 "<div class=\"block\">case7   end of sentence.</div>",
                 "<div class=\"block\">case8   end of sentence.</div>",
                 "<div class=\"block\">case9   end of sentence.</div>",
-                "<div class=\"block\">caseA   end of sentence.</div>");
+                "<div class=\"block\">caseA   end of sentence.</div>",
+                "<div class=\"block\">caseB A block quote example:</div>");
+    }
+
+    @Test
+    void testNegative() {
+        javadoc("-d", "out2",
+                "-sourcepath", testSrc,
+                testSrc("Negative.java"));
+        checkExit(Exit.ERROR);
+
+        checkOutput("Negative.html", true,
+                "<div class=\"block\">case1: A hanging &lt;  : xx<</div>");
     }
 }
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testOverridenMethods/TestBadOverride.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2017, 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      8174839
+ * @summary  Bad overriding method should not crash
+ * @library  ../lib
+ * @modules jdk.javadoc/jdk.javadoc.internal.tool
+ * @build    JavadocTester
+ * @run main TestBadOverride
+ */
+
+public class TestBadOverride extends JavadocTester {
+
+    /**
+     * The entry point of the test.
+     * @param args the array of command line arguments.
+     */
+    public static void main(String... args) throws Exception {
+        TestBadOverride tester = new TestBadOverride();
+        tester.runTests();
+    }
+
+    @Test
+    void test() {
+        javadoc("-d", "out",
+                "-sourcepath", testSrc,
+                "pkg4");
+        checkExit(Exit.OK);
+
+        checkOutput("pkg4/Foo.html", true,
+                "<li class=\"blockList\">\n"
+                + "<h4>toString</h4>\n"
+                + "<pre>public&nbsp;void&nbsp;toString()</pre>\n"
+                + "<div class=\"block\">Why can't I do this ?</div>\n"
+                + "</li>");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testOverridenMethods/pkg4/Foo.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2017, 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 pkg4;
+
+public class Foo {
+    /**
+     * Why can't I do this ?
+     */
+    public void toString() {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testOverview/TestOverview.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,81 @@
+/*
+ * Copyright (c) 2017, 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 8173302
+ * @summary make sure the overview-summary and module-summary pages don't
+ *          don't have the See link, and the overview is copied correctly.
+ * @library ../lib
+ * @modules jdk.javadoc/jdk.javadoc.internal.tool
+ * @build JavadocTester
+ * @run main TestOverview
+ */
+
+public class TestOverview extends JavadocTester {
+
+    public static void main(String... args) throws Exception {
+        TestOverview tester = new TestOverview();
+        tester.runTests();
+    }
+
+    @Test
+    void test1() {
+        javadoc("-d", "out-1",
+                    "-doctitle", "Document Title",
+                    "-windowtitle", "Window Title",
+                    "-overview", testSrc("overview.html"),
+                    "-sourcepath", testSrc("src"),
+                    "p1", "p2");
+        checkExit(Exit.OK);
+        checkOutput("overview-summary.html", true,
+                "<div class=\"header\">\n"
+                + "<h1 class=\"title\">Document Title</h1>\n"
+                + "</div>\n"
+                + "<div class=\"contentContainer\">\n"
+                + "<div class=\"block\">This is line1. This is line 2.</div>\n"
+                + "</div>\n"
+                + "<div class=\"contentContainer\">"
+        );
+    }
+
+    @Test
+    void test2() {
+        javadoc("-d", "out-2",
+                    "-doctitle", "Document Title",
+                    "-windowtitle", "Window Title",
+                    "-overview", testSrc("overview.html"),
+                    "-sourcepath", testSrc("msrc"),
+                    "p1", "p2");
+        checkExit(Exit.OK);
+        checkOutput("overview-summary.html", true,
+                "<div class=\"header\">\n"
+                + "<h1 class=\"title\">Document Title</h1>\n"
+                + "</div>\n"
+                + "<div class=\"contentContainer\">\n"
+                + "<div class=\"block\">This is line1. This is line 2.</div>\n"
+                + "</div>\n"
+                + "<div class=\"contentContainer\">"
+        );
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testOverview/msrc/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,31 @@
+/*
+ * Copyright (c) 2017, 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 module acme.
+  */
+module acme {
+    exports p1;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testOverview/msrc/p1/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2017, 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 p1;
+
+public class C {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testOverview/msrc/p2/C2.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2017, 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 p2;
+
+public class C2 {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testOverview/overview.html	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,6 @@
+<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
+<html>
+<body bgcolor="white">
+    This is line1. This is line 2.
+</body>
+</html>
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testOverview/src/p1/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2017, 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 p1;
+
+public class C {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testOverview/src/p2/C2.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2017, 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 p2;
+
+public class C2 {}
--- a/langtools/test/jdk/javadoc/doclet/testSearch/TestSearch.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testSearch/TestSearch.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8141492 8071982 8141636 8147890 8166175
+ * @bug 8141492 8071982 8141636 8147890 8166175 8168965
  * @summary Test the search feature of javadoc.
  * @author bpatel
  * @library ../lib
@@ -486,6 +486,9 @@
         checkOutput("search.js", true,
                 "camelCaseRegexp = ($.ui.autocomplete.escapeRegex(request.term)).split(/(?=[A-Z])/).join(\"([a-z0-9_$]*?)\");",
                 "var camelCaseMatcher = new RegExp(\"^\" + camelCaseRegexp);",
-                "camelCaseMatcher.test(item.l)");
+                "camelCaseMatcher.test(item.l)",
+                "var secondaryresult = new Array();",
+                "function nestedName(e) {",
+                "function sortAndConcatResults(a1, a2) {");
     }
 }
--- a/langtools/test/jdk/javadoc/doclet/testStylesheet/TestStylesheet.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testStylesheet/TestStylesheet.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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      4494033 7028815 7052425 8007338 8023608 8008164 8016549 8072461 8154261 8162363 8160196
+ * @bug      4494033 7028815 7052425 8007338 8023608 8008164 8016549 8072461 8154261 8162363 8160196 8151743
  * @summary  Run tests on doclet stylesheet.
  * @author   jamieh
  * @library  ../lib
@@ -159,7 +159,10 @@
                 + "    float:none;\n"
                 + "    display:inline;\n"
                 + "}",
-                "@import url('resources/fonts/dejavu.css');");
+                "@import url('resources/fonts/dejavu.css');",
+                ".navPadding {\n"
+                + "    padding-top: 107px;\n"
+                + "}");
 
         // Test whether a link to the stylesheet file is inserted properly
         // in the class documentation.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testTypeVariableLinks/TestTypeVariableLinks.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,55 @@
+/*
+ * Copyright (c) 2017, 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 8174805
+ * @summary JavacTrees should use Types.skipTypeVars() to get the upper bound of type variables
+ * @library ../lib
+ * @modules jdk.javadoc/jdk.javadoc.internal.tool
+ * @build JavadocTester
+ * @run main TestTypeVariableLinks
+ */
+
+public class TestTypeVariableLinks extends JavadocTester {
+
+    public static void main(String... args) throws Exception {
+        TestTypeVariableLinks tester = new TestTypeVariableLinks();
+        tester.runTests();
+    }
+
+    @Test
+    void test1() {
+        javadoc("-d", "out", "-sourcepath", testSrc, "-package", "pkg1");
+        checkExit(Exit.OK);
+
+        checkOutput("pkg1/C.html", true,
+                "<div class=\"block\">Linking to Object.equals() <code>Object.equals(Object)</code></div>");
+        checkOutput("pkg1/C.html", true,
+                "<div class=\"block\">Linking to List.clear() <code>List.clear()</code></div>");
+        checkOutput("pkg1/C.html", true,
+                "<div class=\"block\">Linking to Additional.doAction() <a href=\"../pkg1/Additional.html#doAction--\"><code>Additional.doAction()</code></a></div>");
+        checkOutput("pkg1/C.html", true,
+                "<div class=\"block\">Linking to I.abstractAction() <a href=\"../pkg1/I.html#abstractAction--\"><code>I.abstractAction()</code></a></div>");
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testTypeVariableLinks/pkg1/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2017, 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 pkg1;
+
+import java.util.List;
+
+public class C<T, F extends List<String>, G extends Additional & I> {
+    /**
+     * Linking to Object.equals() {@link T#equals(Object)}
+     */
+    public void m1() {}
+    /**
+     * Linking to List.clear() {@link F#clear()}
+     */
+    public void m2() {}
+    /**
+     * Linking to Additional.doAction() {@link G#doAction()}
+     */
+    public void m3() {}
+    /**
+     * Linking to I.abstractAction() {@link G#abstractAction()}
+     */
+    public void m4() {}
+}
+
+class Additional {
+    public void doAction() {}
+}
+
+interface I {
+    void abstractAction();
+}
--- a/langtools/test/jdk/javadoc/doclet/testXOption/TestXOption.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/javadoc/doclet/testXOption/TestXOption.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2017, 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
@@ -62,6 +62,16 @@
     }
 
     @Test
+    void testWithHelpExtraOption() {
+        javadoc("-d", "out1",
+                "-sourcepath", testSrc,
+                "--help-extra",
+                testSrc("TestXOption.java"));
+        checkExit(Exit.OK);
+        checkOutput(true);
+    }
+
+    @Test
     void testWithOption() {
         javadoc("-d", "out1",
                 "-sourcepath", testSrc,
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/javadoc/tool/api/basic/AddModulesTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,142 @@
+/*
+ * Copyright (c) 2012, 2017, 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 8173596
+ * @summary DocumentationTool.DocumentationTask should support addModules
+ * @modules jdk.compiler/com.sun.tools.javac.api
+ *          jdk.compiler/com.sun.tools.javac.main
+ * @library /tools/lib
+ * @build APITest toolbox.JavacTask toolbox.ToolBox
+ * @run main AddModulesTest
+ */
+
+import java.io.StringWriter;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+
+import javax.tools.DocumentationTool;
+import javax.tools.DocumentationTool.DocumentationTask;
+import javax.tools.DocumentationTool.Location;
+import javax.tools.JavaFileObject;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.StandardLocation;
+import javax.tools.ToolProvider;
+
+import toolbox.Assert;
+import toolbox.JavacTask;
+import toolbox.ToolBox;
+
+/**
+ * Tests for DocumentationTask.addModules method.
+ */
+public class AddModulesTest extends APITest {
+    public static void main(String... args) throws Exception {
+        new AddModulesTest().run();
+    }
+
+    private final ToolBox tb = new ToolBox();
+
+    /**
+     * Verify that addModules works as expected.
+     */
+    @Test
+    public void testAddModules() throws Exception {
+        Path base = Paths.get("testAddModules");
+        Path src = base.resolve("src");
+
+        // setup some utility modules
+        Path src_m1 = src.resolve("m1x");
+        tb.writeJavaFiles(src_m1,
+                          "module m1x { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2x");
+        tb.writeJavaFiles(src_m2,
+                          "module m2x { exports p2; }",
+                          "package p2; public class C2 { }");
+        Path modules = base.resolve("modules");
+        tb.createDirectories(modules);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString())
+                .outdir(modules)
+                .files(tb.findJavaFiles(src))
+                .run()
+                .writeAll();
+
+        // now test access to the modules
+        Path src2 = base.resolve("src2");
+        tb.writeJavaFiles(src2,
+                          "public class Dummy { p1.C1 c1; p2.C2 c2; }");
+        Path api = base.resolve("api");
+        tb.createDirectories(api);
+
+        DocumentationTool tool = ToolProvider.getSystemDocumentationTool();
+        try (StandardJavaFileManager fm = tool.getStandardFileManager(null, null, null)) {
+            fm.setLocationFromPaths(StandardLocation.MODULE_PATH, Arrays.asList(modules));
+            fm.setLocationFromPaths(Location.DOCUMENTATION_OUTPUT, Arrays.asList(api));
+            Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(tb.findJavaFiles(src2));
+
+            for (boolean useOption : new boolean[] { false, true }) {
+                System.err.println("Use --add-modules option: " + useOption);
+                StringWriter sw = new StringWriter();
+                DocumentationTask t = tool.getTask(sw, fm, null, null, null, files);
+                if (useOption) {
+                    t.addModules(Arrays.asList("m1x", "m2x"));
+                }
+                String out;
+                boolean ok;
+                try {
+                    ok = t.call();
+                } finally {
+                    out = sw.toString();
+                    System.err.println(out);
+                }
+                System.err.println("ok: " + ok);
+                boolean expectErrors = !useOption;
+                check(out, "package p1 is not visible", expectErrors);
+                check(out, "package p2 is not visible", expectErrors);
+                System.err.println();
+            }
+        }
+    }
+
+    void check(String out, String text, boolean expected) {
+        System.err.println("Checking for "
+            + (expected ? "expected" : "unexpected")
+            + " text: " + text);
+
+        if (expected) {
+            if (!out.contains(text)) {
+                error("expected text not found: " + text);
+            }
+        } else {
+            if (out.contains(text)) {
+                error("unexpected text found: " + text);
+            }
+        }
+    }
+}
+
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/jdk/jshell/FileManagerTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,114 @@
+/*
+ * Copyright (c) 2017, 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 8173845
+ * @summary test custom file managers
+ * @build KullaTesting TestingInputStream
+ * @run testng FileManagerTest
+ */
+
+
+import java.io.File;
+import java.io.IOException;
+
+import java.util.Set;
+import javax.tools.ForwardingJavaFileManager;
+import javax.tools.JavaFileObject;
+import javax.tools.JavaFileObject.Kind;
+import javax.tools.StandardJavaFileManager;
+import org.testng.annotations.BeforeMethod;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertTrue;
+
+@Test
+public class FileManagerTest extends KullaTesting {
+
+    boolean encountered;
+
+    class MyFileManager extends ForwardingJavaFileManager<StandardJavaFileManager>
+            implements StandardJavaFileManager {
+
+        protected MyFileManager(StandardJavaFileManager fileManager) {
+            super(fileManager);
+        }
+
+        @Override
+        public Iterable<JavaFileObject> list(Location location,
+                String packageName,
+                Set<Kind> kinds,
+                boolean recurse)
+                throws IOException {
+            //System.out.printf("list(%s, %s, %s, %b)\n",
+            //        location, packageName, kinds, recurse);
+            if (packageName.equals("java.lang.reflect")) {
+                encountered = true;
+            }
+            return fileManager.list(location, packageName, kinds, recurse);
+        }
+
+        @Override
+        public Iterable<? extends JavaFileObject> getJavaFileObjectsFromFiles(Iterable<? extends File> files) {
+            return fileManager.getJavaFileObjectsFromFiles(files);
+        }
+
+        @Override
+        public Iterable<? extends JavaFileObject> getJavaFileObjects(File... files) {
+            return fileManager.getJavaFileObjects(files);
+        }
+
+        @Override
+        public Iterable<? extends JavaFileObject> getJavaFileObjectsFromStrings(Iterable<String> names) {
+            return fileManager.getJavaFileObjectsFromStrings(names);
+        }
+
+        @Override
+        public Iterable<? extends JavaFileObject> getJavaFileObjects(String... names) {
+            return fileManager.getJavaFileObjects(names);
+        }
+
+        @Override
+        public void setLocation(Location location, Iterable<? extends File> files) throws IOException {
+            fileManager.setLocation(location, files);
+        }
+
+        @Override
+        public Iterable<? extends File> getLocation(Location location) {
+            return fileManager.getLocation(location);
+        }
+
+    }
+
+    @BeforeMethod
+    @Override
+    public void setUp() {
+        setUp(b -> b.fileManager(fm -> new MyFileManager(fm)));
+    }
+
+    public void testSnippetMemberAssignment() {
+        assertEval("java.lang.reflect.Array.get(new String[1], 0) == null");
+        assertTrue(encountered, "java.lang.reflect not encountered");
+    }
+
+}
--- a/langtools/test/jdk/jshell/JavadocTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/jshell/JavadocTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8131019 8169561
+ * @bug 8131019 8169561 8174245
  * @summary Test Javadoc
  * @library /tools/lib
  * @modules jdk.compiler/com.sun.tools.javac.api
@@ -107,4 +107,51 @@
         addToClasspath(compiler.getClassDir());
     }
 
+    public void testCollectionsMin() {
+        prepareJavaUtilZip();
+        assertJavadoc("java.util.Collections.min(|",
+                      "T java.util.Collections.<T>min(java.util.Collection<? extends T> coll, java.util.Comparator<? super T> comp)\n" +
+                       " min comparator\n",
+                       "T java.util.Collections.<T extends Object & Comparable<? super T>>min(java.util.Collection<? extends T> coll)\n" +
+                       " min comparable\n");
+    }
+
+    private void prepareJavaUtilZip() {
+        String clazz =
+                "package java.util;\n" +
+                "/**Top level." +
+                " */\n" +
+                "public class Collections {\n" +
+                "    /**\n" +
+                "     * min comparable\n" +
+                "     */\n" +
+                "    public static <T extends Object & Comparable<? super T>> T min(Collection<? extends T> coll) {" +
+                "        return null;\n" +
+                "    }\n" +
+                "    /**\n" +
+                "     * min comparator\n" +
+                "     */\n" +
+                "        public static <T> T min(Collection<? extends T> coll, Comparator<? super T> comp) {\n" +
+                "        return null;\n" +
+                "    }\n" +
+                "}\n";
+
+        Path srcZip = Paths.get("src.zip");
+
+        try (JarOutputStream out = new JarOutputStream(Files.newOutputStream(srcZip))) {
+            out.putNextEntry(new JarEntry("java/util/Collections.java"));
+            out.write(clazz.getBytes());
+        } catch (IOException ex) {
+            throw new IllegalStateException(ex);
+        }
+
+        try {
+            Field availableSources = getAnalysis().getClass().getDeclaredField("availableSources");
+            availableSources.setAccessible(true);
+            availableSources.set(getAnalysis(), Arrays.asList(srcZip));
+        } catch (NoSuchFieldException | IllegalArgumentException | IllegalAccessException ex) {
+            throw new IllegalStateException(ex);
+        }
+    }
+
 }
--- a/langtools/test/jdk/jshell/KullaTesting.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/jshell/KullaTesting.java	Thu Mar 16 20:47:03 2017 +0000
@@ -213,7 +213,7 @@
         ModuleFinder finder = ModuleFinder.of(modPath);
         Layer parent = Layer.boot();
         Configuration cf = parent.configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of(moduleName));
+                .resolve(finder, ModuleFinder.of(), Set.of(moduleName));
         ClassLoader scl = ClassLoader.getSystemClassLoader();
         Layer layer = parent.defineModulesWithOneLoader(cf, scl);
         ClassLoader loader = layer.findLoader(moduleName);
--- a/langtools/test/jdk/jshell/MyExecutionControl.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/jshell/MyExecutionControl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -29,6 +29,7 @@
 import java.net.ServerSocket;
 import java.net.Socket;
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
@@ -78,7 +79,7 @@
                     + System.getProperty("path.separator")
                     + System.getProperty("user.dir"));
             JdiInitiator jdii = new JdiInitiator(port,
-                    opts, REMOTE_AGENT, true, null, TIMEOUT);
+                    opts, REMOTE_AGENT, true, null, TIMEOUT, Collections.emptyMap());
             VirtualMachine vm = jdii.vm();
             Process process = jdii.process();
 
--- a/langtools/test/jdk/jshell/ReplToolTesting.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/jshell/ReplToolTesting.java	Thu Mar 16 20:47:03 2017 +0000
@@ -72,27 +72,27 @@
     final static List<String> START_UP_CMD_METHOD = Stream.<String>of()
                     .collect(toList());
     final static List<String> PRINTING_CMD_METHOD = Stream.of(
-            "|    print (boolean)void",
-            "|    print (char)void",
-            "|    print (int)void",
-            "|    print (long)void",
-            "|    print (float)void",
-            "|    print (double)void",
-            "|    print (char s[])void",
-            "|    print (String)void",
-            "|    print (Object)void",
-            "|    println ()void",
-            "|    println (boolean)void",
-            "|    println (char)void",
-            "|    println (int)void",
-            "|    println (long)void",
-            "|    println (float)void",
-            "|    println (double)void",
-            "|    println (char s[])void",
-            "|    println (String)void",
-            "|    println (Object)void",
-            "|    printf (Locale,String,Object...)void",
-            "|    printf (String,Object...)void")
+            "|    void print(boolean)",
+            "|    void print(char)",
+            "|    void print(int)",
+            "|    void print(long)",
+            "|    void print(float)",
+            "|    void print(double)",
+            "|    void print(char s[])",
+            "|    void print(String)",
+            "|    void print(Object)",
+            "|    void println()",
+            "|    void println(boolean)",
+            "|    void println(char)",
+            "|    void println(int)",
+            "|    void println(long)",
+            "|    void println(float)",
+            "|    void println(double)",
+            "|    void println(char s[])",
+            "|    void println(String)",
+            "|    void println(Object)",
+            "|    void printf(java.util.Locale,String,Object...)",
+            "|    void printf(String,Object...)")
             .collect(toList());
     final static List<String> START_UP = Collections.unmodifiableList(
             Stream.concat(START_UP_IMPORTS.stream(), START_UP_METHODS.stream())
@@ -152,6 +152,7 @@
         return s -> {
             List<String> lines = Stream.of(s.split("\n"))
                     .filter(l -> !l.isEmpty())
+                    .filter(l -> !l.startsWith("|     ")) // error/unresolved info
                     .collect(Collectors.toList());
             assertEquals(lines.size(), set.size(), message + " : expected: " + set.keySet() + "\ngot:\n" + lines);
             for (String line : lines) {
@@ -664,7 +665,12 @@
 
         @Override
         public String toString() {
-            return String.format("%s %s", name, signature);
+            int i = signature.lastIndexOf(")") + 1;
+            if (i <= 0) {
+                return String.format("%s", name);
+            } else {
+                return String.format("%s %s%s", signature.substring(i), name, signature.substring(0, i));
+            }
         }
     }
 
--- a/langtools/test/jdk/jshell/ToolBasicTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/jshell/ToolBasicTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8143037 8142447 8144095 8140265 8144906 8146138 8147887 8147886 8148316 8148317 8143955 8157953 8080347 8154714 8166649 8167643 8170162 8172102 8165405
+ * @bug 8143037 8142447 8144095 8140265 8144906 8146138 8147887 8147886 8148316 8148317 8143955 8157953 8080347 8154714 8166649 8167643 8170162 8172102 8165405 8174796 8174797
  * @summary Tests for Basic tests for REPL tool
  * @modules jdk.compiler/com.sun.tools.javac.api
  *          jdk.compiler/com.sun.tools.javac.main
@@ -35,6 +35,7 @@
  * @run testng/timeout=600 ToolBasicTest
  */
 
+import java.io.File;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.io.StringWriter;
@@ -272,23 +273,58 @@
         );
     }
 
-    public void testClasspathJar() {
+    private String makeSimpleJar() {
         Compiler compiler = new Compiler();
         Path outDir = Paths.get("testClasspathJar");
         compiler.compile(outDir, "package pkg; public class A { public String toString() { return \"A\"; } }");
         String jarName = "test.jar";
         compiler.jar(outDir, jarName, "pkg/A.class");
-        Path jarPath = compiler.getPath(outDir).resolve(jarName);
+        return compiler.getPath(outDir).resolve(jarName).toString();
+    }
+
+    public void testClasspathJar() {
+        String jarPath = makeSimpleJar();
         test(
                 (a) -> assertCommand(a, "/env --class-path " + jarPath,
                         "|  Setting new options and restoring state."),
                 (a) -> evaluateExpression(a, "pkg.A", "new pkg.A();", "A")
         );
-        test(new String[] { "--class-path", jarPath.toString() },
+        test(new String[] { "--class-path", jarPath },
                 (a) -> evaluateExpression(a, "pkg.A", "new pkg.A();", "A")
         );
     }
 
+    public void testClasspathUserHomeExpansion() {
+        String jarPath = makeSimpleJar();
+        String tilde = "~" + File.separator;
+        test(
+                (a) -> assertCommand(a, "/env --class-path " + tilde + "forblato",
+                        "|  File '" + System.getProperty("user.home") + File.separator
+                                + "forblato' for '--class-path' is not found."),
+                (a) -> assertCommand(a, "/env --class-path " + jarPath + File.pathSeparator
+                                                            + tilde + "forblato",
+                        "|  File '" + System.getProperty("user.home") + File.separator
+                                + "forblato' for '--class-path' is not found.")
+        );
+    }
+
+    public void testBadClasspath() {
+        String jarPath = makeSimpleJar();
+        Compiler compiler = new Compiler();
+        Path t1 = compiler.getPath("whatever/thing.zip");
+        compiler.writeToFile(t1, "");
+        Path t2 = compiler.getPath("whatever/thing.jmod");
+        compiler.writeToFile(t2, "");
+        test(
+                (a) -> assertCommand(a, "/env --class-path " + t1.toString(),
+                        "|  Invalid '--class-path' argument: " + t1.toString()),
+                (a) -> assertCommand(a, "/env --class-path " + jarPath + File.pathSeparator + t1.toString(),
+                        "|  Invalid '--class-path' argument: " + t1.toString()),
+                (a) -> assertCommand(a, "/env --class-path " + t2.toString(),
+                        "|  Invalid '--class-path' argument: " + t2.toString())
+        );
+    }
+
     public void testModulePath() {
         Compiler compiler = new Compiler();
         Path modsDir = Paths.get("mods");
@@ -304,6 +340,25 @@
         );
     }
 
+    public void testModulePathUserHomeExpansion() {
+        String tilde = "~" + File.separatorChar;
+        test(
+                (a) -> assertCommand(a, "/env --module-path " + tilde + "snardugol",
+                        "|  File '" + System.getProperty("user.home")
+                                + File.separatorChar + "snardugol' for '--module-path' is not found.")
+        );
+    }
+
+    public void testBadModulePath() {
+        Compiler compiler = new Compiler();
+        Path t1 = compiler.getPath("whatever/thing.zip");
+        compiler.writeToFile(t1, "");
+        test(
+                (a) -> assertCommand(a, "/env --module-path " + t1.toString(),
+                        "|  Invalid '--module-path' argument: " + t1.toString())
+        );
+    }
+
     public void testStartupFileOption() {
         Compiler compiler = new Compiler();
         Path startup = compiler.getPath("StartupFileOption/startup.txt");
--- a/langtools/test/jdk/jshell/ToolReloadTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/jshell/ToolReloadTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -92,8 +92,8 @@
         test(false, new String[]{"--no-startup"},
                 a -> assertVariable(a, "int", "a"),
                 a -> dropVariable(a, "/dr 1", "int a = 0", "|  dropped variable a"),
-                a -> assertMethod(a, "int b() { return 0; }", "()I", "b"),
-                a -> dropMethod(a, "/drop b", "b ()I", "|  dropped method b()"),
+                a -> assertMethod(a, "int b() { return 0; }", "()int", "b"),
+                a -> dropMethod(a, "/drop b", "int b()", "|  dropped method b()"),
                 a -> assertClass(a, "class A {}", "class", "A"),
                 a -> dropClass(a, "/dr A", "class A", "|  dropped class A"),
                 a -> assertCommand(a, "/reload",
@@ -115,8 +115,8 @@
         test(false, new String[]{"--no-startup"},
                 a -> assertVariable(a, "int", "a"),
                 a -> dropVariable(a, "/dr 1", "int a = 0", "|  dropped variable a"),
-                a -> assertMethod(a, "int b() { return 0; }", "()I", "b"),
-                a -> dropMethod(a, "/drop b", "b ()I", "|  dropped method b()"),
+                a -> assertMethod(a, "int b() { return 0; }", "()int", "b"),
+                a -> dropMethod(a, "/drop b", "int b()", "|  dropped method b()"),
                 a -> assertClass(a, "class A {}", "class", "A"),
                 a -> dropClass(a, "/dr A", "class A", "|  dropped class A"),
                 a -> assertCommand(a, "/reload -quiet",
--- a/langtools/test/jdk/jshell/ToolSimpleTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/jdk/jshell/ToolSimpleTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8153716 8143955 8151754 8150382 8153920 8156910 8131024 8160089 8153897 8167128 8154513 8170015 8170368 8172102 8172103  8165405 8173073 8173848
+ * @bug 8153716 8143955 8151754 8150382 8153920 8156910 8131024 8160089 8153897 8167128 8154513 8170015 8170368 8172102 8172103  8165405 8173073 8173848 8174041 8173916 8174028 8174262 8174797
  * @summary Simple jshell tool tests
  * @modules jdk.compiler/com.sun.tools.javac.api
  *          jdk.compiler/com.sun.tools.javac.main
@@ -212,6 +212,14 @@
     }
 
     @Test
+    public void testInvalidClassPath() {
+        test(
+                a -> assertCommand(a, "/env --class-path snurgefusal",
+                        "|  File 'snurgefusal' for '--class-path' is not found.")
+        );
+    }
+
+    @Test
     public void testNoArgument() {
         test(
                 (a) -> assertCommand(a, "/save",
@@ -238,8 +246,8 @@
         test(false, new String[]{"--no-startup"},
                 a -> assertVariable(a, "int", "a"),
                 a -> dropVariable(a, "/drop 1", "int a = 0", "|  dropped variable a"),
-                a -> assertMethod(a, "int b() { return 0; }", "()I", "b"),
-                a -> dropMethod(a, "/drop 2", "b ()I", "|  dropped method b()"),
+                a -> assertMethod(a, "int b() { return 0; }", "()int", "b"),
+                a -> dropMethod(a, "/drop 2", "int b()", "|  dropped method b()"),
                 a -> assertClass(a, "class A {}", "class", "A"),
                 a -> dropClass(a, "/drop 3", "class A", "|  dropped class A"),
                 a -> assertImport(a, "import java.util.stream.*;", "", "java.util.stream.*"),
@@ -255,8 +263,8 @@
         test(false, new String[]{"--no-startup"},
                 a -> assertVariable(a, "int", "a"),
                 a -> dropVariable(a, "/drop a", "int a = 0", "|  dropped variable a"),
-                a -> assertMethod(a, "int b() { return 0; }", "()I", "b"),
-                a -> dropMethod(a, "/drop b", "b ()I", "|  dropped method b()"),
+                a -> assertMethod(a, "int b() { return 0; }", "()int", "b"),
+                a -> dropMethod(a, "/drop b", "int b()", "|  dropped method b()"),
                 a -> assertClass(a, "class A {}", "class", "A"),
                 a -> dropClass(a, "/drop A", "class A", "|  dropped class A"),
                 a -> assertCommandCheckOutput(a, "/vars", assertVariables()),
@@ -466,10 +474,50 @@
                 a -> assertCommandCheckOutput(a, "/methods print println printf",
                         s -> checkLineToList(s, printingMethodList)),
                 a -> assertCommandOutputStartsWith(a, "/methods g",
-                        "|    g ()void"),
+                        "|    void g()"),
                 a -> assertCommandOutputStartsWith(a, "/methods f",
-                        "|    f ()int\n" +
-                        "|    f (int)void")
+                        "|    int f()\n" +
+                        "|    void f(int)")
+        );
+    }
+
+    @Test
+    public void testMethodsWithErrors() {
+        test(new String[]{"--no-startup"},
+                a -> assertCommand(a, "double m(int x) { return x; }",
+                        "|  created method m(int)"),
+                a -> assertCommand(a, "GARBAGE junk() { return TRASH; }",
+                        "|  created method junk(), however, it cannot be referenced until class GARBAGE, and variable TRASH are declared"),
+                a -> assertCommand(a, "int w = 5;",
+                        "w ==> 5"),
+                a -> assertCommand(a, "int tyer() { return w; }",
+                        "|  created method tyer()"),
+                a -> assertCommand(a, "String w = \"hi\";",
+                        "w ==> \"hi\""),
+                a -> assertCommand(a, "/methods",
+                        "|    double m(int)\n" +
+                        "|    GARBAGE junk()\n" +
+                        "|       which cannot be referenced until class GARBAGE, and variable TRASH are declared\n" +
+                        "|    int tyer()\n" +
+                        "|       which cannot be invoked until this error is corrected: \n" +
+                        "|          incompatible types: java.lang.String cannot be converted to int\n" +
+                        "|          int tyer() { return w; }\n" +
+                        "|                              ^\n")
+        );
+    }
+
+    @Test
+    public void testTypesWithErrors() {
+        test(new String[]{"--no-startup"},
+                a -> assertCommand(a, "class C extends NONE { int x; }",
+                        "|  created class C, however, it cannot be referenced until class NONE is declared"),
+                a -> assertCommand(a, "class D { void m() { System.out.println(nada); } }",
+                        "|  created class D, however, it cannot be instantiated or its methods invoked until variable nada is declared"),
+                a -> assertCommand(a, "/types",
+                        "|    class C\n" +
+                        "|       which cannot be referenced until class NONE is declared\n" +
+                        "|    class D\n" +
+                        "|       which cannot be instantiated or its methods invoked until variable nada is declared\n")
         );
     }
 
--- a/langtools/test/tools/javac/6627362/T6627362.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/6627362/T6627362.java	Thu Mar 16 20:47:03 2017 +0000
@@ -68,9 +68,9 @@
         // compile and disassemble E.java, using modified Object.java,
         // check for reference to System.arraycopy
         File x = new File(testSrc, "x");
-        String[] jcArgs = { "-d", ".", "-Xmodule:java.base",
+        String[] jcArgs = { "-d", ".", "--patch-module", "java.base=" + x.getAbsolutePath(),
                             new File(x, "E.java").getPath(),
-                            new File(x, "Object.java").getPath()};
+                            new File(new File(new File(x, "java"), "lang"), "Object.java").getPath()};
         compile(jcArgs);
 
         String[] jpArgs = { "-classpath", ".", "-c", "E" };
--- a/langtools/test/tools/javac/6627362/x/Object.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,30 +0,0 @@
-/*
- * Copyright (c) 2007, 2008, 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 java.lang;
-
-/*
- * Object, without clone()
- */
-public class Object {
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/6627362/x/java/lang/Object.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2007, 2008, 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 java.lang;
+
+/*
+ * Object, without clone()
+ */
+public class Object {
+}
--- a/langtools/test/tools/javac/T4093617/T4093617.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/T4093617/T4093617.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 2017, 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
@@ -26,6 +26,6 @@
  * @bug     4093617
  * @summary Object has no superclass
  * @author  Peter von der Ah\u00e9
- * @compile/module=java.base/fail/ref=T4093617.out -XDrawDiagnostics Object.java
+ * @compile/module=java.base/fail/ref=T4093617.out -XDrawDiagnostics java/lang/Object.java
  */
 
--- a/langtools/test/tools/javac/T4093617/java.base/Object.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,10 +0,0 @@
-/*
- * /nodynamiccopyright/
- * See ../T4093617.java
- */
-
-package java.lang;
-
-class Object {
-    Object() { super(); }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/T4093617/java.base/java/lang/Object.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,10 @@
+/*
+ * /nodynamiccopyright/
+ * See ../T4093617.java
+ */
+
+package java.lang;
+
+class Object {
+    Object() { super(); }
+}
--- a/langtools/test/tools/javac/T6234077.out	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/T6234077.out	Thu Mar 16 20:47:03 2017 +0000
@@ -1,2 +1,2 @@
-T6234077.java:7:8: compiler.err.class.public.should.be.in.file: Foo
+T6234077.java:7:8: compiler.err.class.public.should.be.in.file: kindname.class, Foo
 1 error
--- a/langtools/test/tools/javac/T8003967/DetectMutableStaticFields.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/T8003967/DetectMutableStaticFields.java	Thu Mar 16 20:47:03 2017 +0000
@@ -107,7 +107,7 @@
         // by reflective lookup, to avoid explicit references that are not available
         // when running javac on JDK 8.
         ignore("com/sun/tools/javac/util/JDK9Wrappers$Configuration",
-                "resolveRequiresAndUsesMethod", "configurationClass");
+                "resolveAndBindMethod", "configurationClass");
         ignore("com/sun/tools/javac/util/JDK9Wrappers$Layer",
                 "bootMethod", "defineModulesWithOneLoaderMethod", "configurationMethod", "layerClass");
         ignore("com/sun/tools/javac/util/JDK9Wrappers$Module",
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/T8173955/MessageForClassTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,8 @@
+/*
+ * @test  /nodynamiccopyright/
+ * @bug 8174027
+ * @summary error message should adapt to the corresponding top level element
+ * @compile/fail/ref=MessageForClassTest.out -XDrawDiagnostics MessageForClassTest.java
+ */
+
+public class MessageForClassTest_ {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/T8173955/MessageForClassTest.out	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,2 @@
+MessageForClassTest.java:8:8: compiler.err.class.public.should.be.in.file: kindname.class, MessageForClassTest_
+1 error
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/T8173955/MessageForEnumTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,8 @@
+/*
+ * @test  /nodynamiccopyright/
+ * @bug 8174027
+ * @summary error message should adapt to the corresponding top level element
+ * @compile/fail/ref=MessageForEnumTest.out -XDrawDiagnostics MessageForEnumTest.java
+ */
+
+public enum MessageForEnumTest_ {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/T8173955/MessageForEnumTest.out	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,2 @@
+MessageForEnumTest.java:8:8: compiler.err.class.public.should.be.in.file: kindname.enum, MessageForEnumTest_
+1 error
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/T8173955/MessageForInterfaceTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,8 @@
+/*
+ * @test  /nodynamiccopyright/
+ * @bug 8174027
+ * @summary error message should adapt to the corresponding top level element
+ * @compile/fail/ref=MessageForInterfaceTest.out -XDrawDiagnostics MessageForInterfaceTest.java
+ */
+
+public interface MessageForInterfaceTest_ {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/T8173955/MessageForInterfaceTest.out	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,2 @@
+MessageForInterfaceTest.java:8:8: compiler.err.class.public.should.be.in.file: kindname.interface, MessageForInterfaceTest_
+1 error
--- a/langtools/test/tools/javac/api/T6265137.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/api/T6265137.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2017, 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
@@ -52,7 +52,7 @@
             String srcdir = System.getProperty("test.src");
             Iterable<? extends JavaFileObject> files =
                 fm.getJavaFileObjectsFromFiles(Arrays.asList(new File(srcdir, "T6265137a.java")));
-            javac.getTask(null, fm, dl, Arrays.asList("-target","9"), null, files).call();
+            javac.getTask(null, fm, dl, Arrays.asList("-target","10"), null, files).call();
         }
     }
 }
--- a/langtools/test/tools/javac/api/T6395981.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/api/T6395981.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2017, 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     6395981 6458819 7025784 8028543
+ * @bug     6395981 6458819 7025784 8028543 8028544
  * @summary JavaCompilerTool and Tool must specify version of JLS and JVMS
  * @author  Peter von der Ah\u00e9
  * @modules java.compiler
@@ -31,7 +31,7 @@
  * @run main/fail T6395981
  * @run main/fail T6395981 RELEASE_3 RELEASE_5 RELEASE_6
  * @run main/fail T6395981 RELEASE_0 RELEASE_1 RELEASE_2 RELEASE_3 RELEASE_4 RELEASE_5 RELEASE_6
- * @run main T6395981 RELEASE_3 RELEASE_4 RELEASE_5 RELEASE_6 RELEASE_7 RELEASE_8 RELEASE_9
+ * @run main T6395981 RELEASE_3 RELEASE_4 RELEASE_5 RELEASE_6 RELEASE_7 RELEASE_8 RELEASE_9 RELEASE_10
  */
 
 import java.util.EnumSet;
--- a/langtools/test/tools/javac/diags/Example.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/diags/Example.java	Thu Mar 16 20:47:03 2017 +0000
@@ -63,6 +63,7 @@
         procFiles = new ArrayList<File>();
         srcPathFiles = new ArrayList<File>();
         moduleSourcePathFiles = new ArrayList<File>();
+        patchModulePathFiles = new ArrayList<File>();
         modulePathFiles = new ArrayList<File>();
         classPathFiles = new ArrayList<File>();
         additionalFiles = new ArrayList<File>();
@@ -88,6 +89,9 @@
                 } else if (files == srcFiles && c.getName().equals("modulesourcepath")) {
                     moduleSourcePathDir = c;
                     findFiles(c, moduleSourcePathFiles);
+                } else if (files == srcFiles && c.getName().equals("patchmodule")) {
+                    patchModulePathDir = c;
+                    findFiles(c, patchModulePathFiles);
                 } else if (files == srcFiles && c.getName().equals("additional")) {
                     additionalFilesDir = c;
                     findFiles(c, additionalFiles);
@@ -272,6 +276,16 @@
             files.addAll(nonEmptySrcFiles); // srcFiles containing declarations
         }
 
+        if (patchModulePathDir != null) {
+            for (File mod : patchModulePathDir.listFiles()) {
+                opts.add("--patch-module");
+                opts.add(mod.getName() + "=" + mod.getPath());
+            }
+            files = new ArrayList<>();
+            files.addAll(patchModulePathFiles);
+            files.addAll(nonEmptySrcFiles); // srcFiles containing declarations
+        }
+
         if (additionalFiles.size() > 0) {
             List<String> sOpts = Arrays.asList("-d", classesDir.getPath());
             new Jsr199Compiler(verbose).run(null, null, false, sOpts, additionalFiles);
@@ -343,9 +357,11 @@
     List<File> procFiles;
     File srcPathDir;
     File moduleSourcePathDir;
+    File patchModulePathDir;
     File additionalFilesDir;
     List<File> srcPathFiles;
     List<File> moduleSourcePathFiles;
+    List<File> patchModulePathFiles;
     List<File> modulePathFiles;
     List<File> classPathFiles;
     List<File> additionalFiles;
--- a/langtools/test/tools/javac/diags/examples.not-yet.txt	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/diags/examples.not-yet.txt	Thu Mar 16 20:47:03 2017 +0000
@@ -5,6 +5,7 @@
 compiler.err.cant.read.file                             # (apt.JavaCompiler?)
 compiler.err.cant.select.static.class.from.param.type
 compiler.err.dc.unterminated.string                     # cannot happen
+compiler.err.file.patched.and.msp                       # needs the same dir on --module-source-path and --patch-module
 compiler.err.illegal.char.for.encoding
 compiler.err.invalid.repeatable.annotation              # should not happen
 compiler.err.invalid.repeatable.annotation.invalid.value # "can't" happen
--- a/langtools/test/tools/javac/diags/examples/IllegalArgumentForOption/IllegalArgumentForOption.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/diags/examples/IllegalArgumentForOption/IllegalArgumentForOption.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,7 +22,7 @@
  */
 
 // key: compiler.err.illegal.argument.for.option
-// options: --module-path doesNotExist
+// options: --module-source-path=abc*def
 // run: simple
 
 class X {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/ModuleInfoWithPatchedModuleClassoutput/ModuleInfoWithPatchedModuleClassoutput.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2016, 2017, 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.
+ */
+
+// key: compiler.err.module-info.with.patched.module.classoutput
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/ModuleInfoWithPatchedModuleClassoutput/additional/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2016, 2017, 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.
+ */
+
+module mod {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/ModuleInfoWithPatchedModuleClassoutput/patchmodule/java.compiler/javax/lang/model/element/Extra.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2016, 2017, 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 javax.lang.model.element;
+
+public interface Extra {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/ModuleInfoWithPatchedModuleSourcepath/ModuleInfoWithPatchedModule.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2016, 2017, 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.
+ */
+
+// key: compiler.err.module-info.with.patched.module.sourcepath
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/ModuleInfoWithPatchedModuleSourcepath/patchmodule/java.compiler/javax/lang/model/element/Extra.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,26 @@
+/*
+ * Copyright (c) 2016, 2017, 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 javax.lang.model.element;
+
+public interface Extra {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/ModuleInfoWithPatchedModuleSourcepath/patchmodule/java.compiler/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2016, 2017, 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.
+ */
+
+module java.compiler {}
--- a/langtools/test/tools/javac/diags/examples/ModuleInfoWithXModuleSourcePath/Extra.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,29 +0,0 @@
-/*
- * 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.
- */
-
-// key: compiler.err.module-info.with.xmodule.sourcepath
-// options: -Xmodule:java.compiler
-
-package javax.lang.model.element;
-
-public interface Extra {}
--- a/langtools/test/tools/javac/diags/examples/ModuleInfoWithXModuleSourcePath/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,24 +0,0 @@
-/*
- * 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.
- */
-
-module java.compiler {}
--- a/langtools/test/tools/javac/diags/examples/ModuleInfoWithXmoduleClasspath/ModuleInfoWithXmoduleClasspath.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,29 +0,0 @@
-/*
- * 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.
- */
-
-// key: compiler.err.module-info.with.xmodule.classpath
-// options: -Xmodule:java.compiler
-
-package javax.lang.model.element;
-
-public interface ModuleInfoWithXModuleClasspath {}
--- a/langtools/test/tools/javac/diags/examples/ModuleInfoWithXmoduleClasspath/additional/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,24 +0,0 @@
-/*
- * 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.
- */
-
-module mod {}
--- a/langtools/test/tools/javac/diags/examples/NoSuperclass.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,33 +0,0 @@
-/*
- * Copyright (c) 2010, 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.
- */
-
-// key: compiler.err.no.superclass
-// options: -Xmodule:java.base
-
-package java.lang;
-
-class Object {
-    public Object() {
-        super();
-    }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/NoSuperclass/NoSuperclass.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2010, 2017, 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.
+ */
+
+// key: compiler.err.no.superclass
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/NoSuperclass/patchmodule/java.base/java/lang/Object.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2010, 2017, 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 java.lang;
+
+class Object {
+    public Object() {
+        super();
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/ServiceImplNotPublic/ServiceImplNotPublic.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+
+// key: compiler.err.not.def.public
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/ServiceImplNotPublic/example/ServiceImpl.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2017, 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 example;
+class ServiceImpl implements example.SomeService {
+    public ServiceImpl() {}
+    public void foo() {}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/ServiceImplNotPublic/example/SomeService.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2017, 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 example;
+public interface SomeService {
+    public void foo();
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/ServiceImplNotPublic/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,27 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+
+module m {
+    exports example;
+    provides example.SomeService with example.ServiceImpl;
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/TooManyPatchedModules/TooManyPatchedModules.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,24 @@
+/*
+ * Copyright (c) 2017, 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.
+ */
+
+// key: compiler.err.too.many.patched.modules
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/TooManyPatchedModules/patchmodule/java.compiler/p/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2017, 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 p;
+
+class C {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/diags/examples/TooManyPatchedModules/patchmodule/jdk.compiler/p/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,25 @@
+/*
+ * Copyright (c) 2017, 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 p;
+
+class C {}
--- a/langtools/test/tools/javac/diags/examples/XModuleWithModulePath/XModuleWithModulePath.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,27 +0,0 @@
-/*
- * 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.
- */
-
-// key: compiler.err.xmodule.no.module.sourcepath
-// options: -Xmodule:java.compiler --module-source-path src
-
-class XModuleWithModulePath {}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/doclint/NPEDuplicateClassNamesTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,97 @@
+/*
+ * Copyright (c) 2017, 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 8174073
+ * @summary NPE caused by link reference to class
+ * @modules jdk.compiler/com.sun.tools.javac.api
+ *          jdk.compiler/com.sun.tools.javac.main
+ * @library /tools/lib
+ * @build toolbox.JavacTask toolbox.TestRunner toolbox.ToolBox
+ * @run main NPEDuplicateClassNamesTest
+ */
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Objects;
+
+import toolbox.JavacTask;
+import toolbox.Task;
+import toolbox.TestRunner;
+import toolbox.ToolBox;
+
+public class NPEDuplicateClassNamesTest extends TestRunner {
+
+    public static void main(String... args) throws Exception {
+        NPEDuplicateClassNamesTest t = new NPEDuplicateClassNamesTest();
+        t.runTests();
+    }
+
+    private final ToolBox tb = new ToolBox();
+    private final String class1 =
+            "package com;\n" +
+            "/***/\n" +
+            "public class MyClass {}";
+    private final String class2 =
+            "package com;\n" +
+            "/**\n" +
+            " * The following link tag causes a NullPointerException: {@link Requirements}. \n" +
+            " */\n" +
+            "public class MyClass {}";
+
+    NPEDuplicateClassNamesTest() throws IOException {
+        super(System.err);
+    }
+
+    @Test
+    public void testDuplicateClassNames() throws IOException {
+        Path src = Paths.get("src");
+        Path one = src.resolve("one");
+        Path two = src.resolve("two");
+        Path classes = Paths.get("classes");
+        Files.createDirectories(classes);
+        tb.writeJavaFiles(one, class1);
+        tb.writeJavaFiles(two, class2);
+
+        List<String> expected = Arrays.asList(
+                "MyClass.java:5:8: compiler.err.duplicate.class: com.MyClass",
+                "MyClass.java:3:65: compiler.err.proc.messager: reference not found",
+                "2 errors");
+        List<String> output = new JavacTask(tb)
+                  .outdir(classes)
+                  .options("-XDrawDiagnostics", "-Xdoclint:all", "-XDdev")
+                  .files(tb.findJavaFiles(src))
+                  .run(Task.Expect.FAIL)
+                  .writeAll()
+                  .getOutputLines(Task.OutputKind.DIRECT);
+
+        if (!Objects.equals(output, expected)) {
+            throw new IllegalStateException("incorrect output; actual=" + output + "; expected=" + expected);
+        }
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/generics/inference/8174249/T8174249a.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,54 @@
+/*
+ * Copyright (c) 2017, 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 8174249
+ * @summary Regression in generic method unchecked calls
+ * @compile T8174249a.java
+ */
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+class T8174249a {
+    static <T> T foo(Class<T> c, Collection<? super T> baz) {
+return null;
+    }
+
+    static void bar(String c) { }
+
+    void test() {
+        // this works
+        bar(foo(String.class, new ArrayList<String>()));
+
+        // this works with a warning
+        String s = foo(String.class, new ArrayList());
+        bar(s);
+
+        // this causes an error on JDK9 but should work
+        bar(foo(String.class, new ArrayList()));
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/generics/inference/8174249/T8174249b.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,59 @@
+/*
+ * Copyright (c) 2017, 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 8174249
+ * @summary Regression in generic method unchecked calls
+ * @compile T8174249b.java
+ */
+
+import java.util.*;
+
+class T8174249b {
+
+    static void cs(Collection<String> cs) {}
+
+    void test1(Collection c) {
+        cs(rawCollection((Class)null));
+        Collection<String> cs1 = rawCollection((Class)null);
+    }
+
+    void test2(Collection c) {
+        cs(rawCollection2((Class)null));
+        Collection<String> cs2 = rawCollection2((Class)null);
+    }
+
+    void test3(Collection c) {
+        cs(rawCollection3((Class)null));
+        Collection<String> cs3 = rawCollection2((Class)null);
+    }
+
+    Collection<Integer> rawCollection(Class<String> cs) { return null; }
+
+    <Z> Collection<Integer> rawCollection2(Class<Z> cs) { return null; }
+
+    <Z> Collection<Z> rawCollection3(Class<Z> cs) { return null; }
+}
--- a/langtools/test/tools/javac/lambda/intersection/IntersectionTargetTypeTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/lambda/intersection/IntersectionTargetTypeTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,6 +26,7 @@
  * @bug 8002099 8010822
  * @summary Add support for intersection types in cast expression
  * @modules jdk.compiler/com.sun.tools.javac.util
+ * @run main/othervm IntersectionTargetTypeTest
  */
 
 import com.sun.source.util.JavacTask;
--- a/langtools/test/tools/javac/lib/combo/ComboTask.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/lib/combo/ComboTask.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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,9 +25,9 @@
 
 import com.sun.source.tree.CompilationUnitTree;
 import com.sun.source.util.JavacTask;
-import com.sun.source.util.TaskEvent.Kind;
 import com.sun.source.util.TaskListener;
 import com.sun.tools.javac.api.JavacTool;
+import com.sun.tools.javac.util.Assert;
 import com.sun.tools.javac.util.List;
 import combo.ComboParameter.Resolver;
 
@@ -36,11 +36,18 @@
 import javax.tools.DiagnosticListener;
 import javax.tools.JavaFileObject;
 import javax.tools.SimpleJavaFileObject;
+
 import java.io.IOException;
 import java.io.Writer;
 import java.net.URI;
+import java.net.URL;
+import java.net.URLClassLoader;
+import java.util.ArrayList;
+import java.util.function.Consumer;
+import java.util.function.Function;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.Optional;
 import java.util.stream.Collectors;
 import java.util.stream.StreamSupport;
 
@@ -184,6 +191,28 @@
     }
 
     /**
+     * Parse, analyze, perform code generation for the sources associated with this task and finally
+     * executes them
+     */
+    public <Z> Optional<Z> execute(Function<ExecutionTask, Z> executionFunc) throws IOException {
+        Result<Iterable<? extends JavaFileObject>> generationResult = generate();
+        Iterable<? extends JavaFileObject> jfoIterable = generationResult.get();
+        if (generationResult.hasErrors()) {
+            // we have nothing else to do
+            return Optional.empty();
+        }
+        java.util.List<URL> urlList = new ArrayList<>();
+        for (JavaFileObject jfo : jfoIterable) {
+            String urlStr = jfo.toUri().toURL().toString();
+            urlStr = urlStr.substring(0, urlStr.length() - jfo.getName().length());
+            urlList.add(new URL(urlStr));
+        }
+        return Optional.of(
+                executionFunc.apply(
+                        new ExecutionTask(new URLClassLoader(urlList.toArray(new URL[urlList.size()])))));
+    }
+
+    /**
      * Fork a new compilation task; if possible the compilation context from previous executions is
      * retained (see comments in ReusableContext as to when it's safe to do so); otherwise a brand
      * new context is created.
@@ -215,6 +244,80 @@
     }
 
     /**
+     * This class represents an execution task. It allows the execution of one or more classes previously
+     * added to a given class loader. This class uses reflection to execute any given static public method
+     * in any given class. It's not restricted to the execution of the {@code main} method
+     */
+    public class ExecutionTask {
+        private ClassLoader classLoader;
+        private String methodName = "main";
+        private Class<?>[] parameterTypes = new Class<?>[]{String[].class};
+        private Object[] args = new String[0];
+        private Consumer<Throwable> handler;
+        private Class<?> c;
+
+        private ExecutionTask(ClassLoader classLoader) {
+            this.classLoader = classLoader;
+        }
+
+        /**
+         * Set the name of the class to be loaded.
+         */
+        public ExecutionTask withClass(String className) {
+            Assert.check(className != null, "class name value is null, impossible to proceed");
+            try {
+                c = classLoader.loadClass(className);
+            } catch (Throwable t) {
+                throw new IllegalStateException(t);
+            }
+            return this;
+        }
+
+        /**
+         * Set the name of the method to be executed along with the parameter types to
+         * reflectively obtain the method.
+         */
+        public ExecutionTask withMethod(String methodName, Class<?>... parameterTypes) {
+            this.methodName = methodName;
+            this.parameterTypes = parameterTypes;
+            return this;
+        }
+
+        /**
+         * Set the arguments to be passed to the method.
+         */
+        public ExecutionTask withArguments(Object... args) {
+            this.args = args;
+            return this;
+        }
+
+        /**
+         * Set a handler to handle any exception thrown.
+         */
+        public ExecutionTask withHandler(Consumer<Throwable> handler) {
+            this.handler = handler;
+            return this;
+        }
+
+        /**
+         * Executes the given method in the given class. Returns true if the execution was
+         * successful, false otherwise.
+         */
+        public Object run() {
+            try {
+                java.lang.reflect.Method meth = c.getMethod(methodName, parameterTypes);
+                meth.invoke(null, (Object)args);
+                return true;
+            } catch (Throwable t) {
+                if (handler != null) {
+                    handler.accept(t);
+                }
+                return false;
+            }
+        }
+    }
+
+    /**
      * This class is used to help clients accessing the results of a given compilation task.
      * Contains several helper methods to inspect diagnostics generated during the task execution.
      */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/main/EnvVariableTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,151 @@
+/*
+ * Copyright (c) 2017, 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 8173308
+ * @summary Check JDK_JAVA_OPTIONS parsing behavior
+ * @library /tools/lib
+ * @modules jdk.compiler/com.sun.tools.javac.main
+ * @build toolbox.ToolBox toolbox.TestRunner
+ * @run main EnvVariableTest
+ */
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.PrintStream;
+import java.nio.file.Path;
+
+import toolbox.*;
+
+import com.sun.tools.javac.main.CommandLine;
+
+public class EnvVariableTest extends TestRunner {
+    final String testClasses;
+    final ToolBox tb;
+    final Path javaExePath;
+    final ExecTask task;
+    final PrintStream ostream;
+    final ByteArrayOutputStream baos;
+
+    public EnvVariableTest() {
+        super(System.err);
+        ostream = System.err;
+        baos = new ByteArrayOutputStream();
+        testClasses = System.getProperty("test.classes");
+        tb = new ToolBox();
+        javaExePath = tb.getJDKTool("java");
+        task = new ExecTask(tb, javaExePath);
+    }
+
+    public static void main(String... args) throws Exception {
+        EnvVariableTest t = new EnvVariableTest();
+        t.runTests();
+    }
+
+    @Test
+    public void testDoubleQuote() throws Exception {
+        // white space quoted with double quotes
+        test("-version -cp \"c:\\\\java libs\\\\one.jar\" \n",
+                "-version", "-cp", "c:\\\\java libs\\\\one.jar");
+    }
+
+    @Test
+    public void testSingleQuote() throws Exception {
+        // white space quoted with single quotes
+        test("-version -cp \'c:\\\\java libs\\\\one.jar\' \n",
+                "-version", "-cp", "c:\\\\java libs\\\\one.jar");
+    }
+
+    @Test
+    public void testEscapeCharacters() throws Exception {
+        // escaped characters
+        test("escaped chars testing \"\\a\\b\\c\\f\\n\\r\\t\\v\\9\\6\\23\\82\\28\\377\\477\\278\\287\"",
+                "escaped", "chars", "testing", "\\a\\b\\c\\f\\n\\r\\t\\v\\9\\6\\23\\82\\28\\377\\477\\278\\287");
+    }
+
+    @Test
+    public void testMixedQuotes() throws Exception {
+        // more mixing of quote types
+        test("\"mix 'single quote' in double\" 'mix \"double quote\" in single' partial\"quote me\"this",
+                "mix 'single quote' in double", "mix \"double quote\" in single", "partialquote methis");
+    }
+
+    @Test
+    public void testWhiteSpaces() throws Exception {
+        // whitespace tests
+        test("line one #comment\n'line #2' #rest are comment\r\n#comment on line 3\fline 4 #comment to eof",
+                "line", "one", "#comment", "line #2", "#rest", "are", "comment", "#comment", "on", "line",
+                "3", "line", "4", "#comment", "to", "eof");
+    }
+
+    @Test
+    public void testMismatchedDoubleQuote() throws Exception {
+        // mismatched quote
+        test("This is an \"open quote \n    across line\n\t, note for WS.",
+                "Exception: JDK_JAVAC_OPTIONS");
+    }
+
+    @Test
+    public void testMismatchedSingleQuote() throws Exception {
+        // mismatched quote
+        test("This is an \'open quote \n    across line\n\t, note for WS.",
+                "Exception: JDK_JAVAC_OPTIONS");
+    }
+
+    void test(String full, String... expectedArgs) throws Exception {
+        task.envVar("JDK_JAVAC_OPTIONS", full);
+        task.args("--add-exports", "jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED",
+                "-cp", testClasses, "EnvVariableTest$Tester");
+        Task.Result tr = task.run(Task.Expect.SUCCESS);
+        String expected = Tester.arrayToString(expectedArgs);
+        String in = tr.getOutput(Task.OutputKind.STDOUT);
+        System.err.println("Matching...");
+        System.err.println("Obtained: " + in);
+        System.err.println("Expected: " + expected);
+        if (in.contains(expected)) {
+            System.err.println("....OK");
+            return;
+        }
+        throw new Exception("Expected strings not found");
+    }
+
+    /**
+     * A tester class that is invoked to invoke the CommandLine class, and
+     * print the result.
+     */
+    public static class Tester {
+        private static final String[] EMPTY_ARRAY = new String[0];
+        static String arrayToString(String... args) {
+            return String.join(", ", args);
+        }
+        public static void main(String... args) throws IOException {
+            try {
+                String[] argv = CommandLine.parse("JDK_JAVAC_OPTIONS", EMPTY_ARRAY);
+                System.out.print(arrayToString(argv));
+            } catch (CommandLine.UnmatchedQuote ex) {
+                System.out.print("Exception: " + ex.variableName);
+            }
+        }
+    }
+}
--- a/langtools/test/tools/javac/meth/BadPolySig.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,12 +0,0 @@
-/*
- * @test
- * @bug 8168774
- * @summary Polymorhic signature method check crashes javac
- * @compile -Xmodule:java.base BadPolySig.java
- */
-
-package java.lang.invoke;
-
-class MethodHandle {
-    native Object m();
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/meth/BadPolySig/BadPolySig.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,30 @@
+/*
+ * Copyright (c) 2016, 2017, 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 8168774
+ * @summary Polymorhic signature method check crashes javac
+ * @modules jdk.compiler
+ * @compile/module=java.base java/lang/invoke/MethodHandle.java
+ */
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/meth/BadPolySig/java.base/java/lang/invoke/MethodHandle.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,28 @@
+/*
+ * Copyright (c) 2016, 2017, 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 java.lang.invoke;
+
+class MethodHandle {
+    native Object m();
+}
--- a/langtools/test/tools/javac/modules/AddLimitMods.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/modules/AddLimitMods.java	Thu Mar 16 20:47:03 2017 +0000
@@ -293,7 +293,7 @@
         }
 
         actual = new JavacTask(tb)
-                   .options("-Xmodule:java.base",
+                   .options("--patch-module", "java.base=" + cpSrc.toString(),
                             "-XDrawDiagnostics",
                             "--add-modules", "ALL-MODULE-PATH")
                    .outdir(cpOut)
--- a/langtools/test/tools/javac/modules/AddModulesTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/modules/AddModulesTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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,17 +23,27 @@
 
 /*
  * @test
+ * @bug 8167975 8173596
  * @summary Test the --add-modules option
  * @library /tools/lib
  * @modules jdk.compiler/com.sun.tools.javac.api
  *          jdk.compiler/com.sun.tools.javac.main
- * @build toolbox.ToolBox toolbox.JavacTask ModuleTestBase
+ * @build toolbox.Assert toolbox.ToolBox toolbox.JavacTask ModuleTestBase
  * @run main AddModulesTest
  */
 
 
 import java.nio.file.Path;
+import java.util.Arrays;
 
+import javax.tools.JavaCompiler;
+import javax.tools.JavaCompiler.CompilationTask;
+import javax.tools.JavaFileObject;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.StandardLocation;
+import javax.tools.ToolProvider;
+
+import toolbox.Assert;
 import toolbox.JavacTask;
 import toolbox.Task;
 
@@ -227,5 +237,46 @@
                 .run()
                 .writeAll();
     }
+
+    @Test
+    public void testAddModulesAPI(Path base) throws Exception {
+        Path src = base.resolve("src");
+
+        // setup some utility modules
+        Path src_m1 = src.resolve("m1x");
+        tb.writeJavaFiles(src_m1,
+                          "module m1x { exports p1; }",
+                          "package p1; public class C1 { }");
+        Path src_m2 = src.resolve("m2x");
+        tb.writeJavaFiles(src_m2,
+                          "module m2x { exports p2; }",
+                          "package p2; public class C2 { }");
+        Path modules = base.resolve("modules");
+        tb.createDirectories(modules);
+
+        new JavacTask(tb)
+                .options("--module-source-path", src.toString())
+                .outdir(modules)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+
+        // now test access to the modules
+        Path src2 = base.resolve("src2");
+        tb.writeJavaFiles(src2,
+                          "class Dummy { p1.C1 c1; p2.C2 c2; }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        JavaCompiler c = ToolProvider.getSystemJavaCompiler();
+        try (StandardJavaFileManager fm = c.getStandardFileManager(null, null, null)) {
+            fm.setLocationFromPaths(StandardLocation.MODULE_PATH, Arrays.asList(modules));
+            fm.setLocationFromPaths(StandardLocation.CLASS_OUTPUT, Arrays.asList(classes));
+            Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects(findJavaFiles(src2));
+            CompilationTask t = c.getTask(null, fm, null, null, null, files);
+            t.addModules(Arrays.asList("m1x", "m2x"));
+            Assert.check(t.call());
+        }
+    }
 }
 
--- a/langtools/test/tools/javac/modules/AddReadsTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/modules/AddReadsTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -217,7 +217,7 @@
         new JavacTask(tb)
           .options("--class-path", jar.toString(),
                    "--add-reads", "java.base=ALL-UNNAMED",
-                   "-Xmodule:java.base")
+                   "--patch-module", "java.base=" + src)
           .outdir(classes)
           .files(src.resolve("impl").resolve("Impl.java"))
           .run()
@@ -237,7 +237,7 @@
         new JavacTask(tb)
           .options("--add-modules", "java.desktop",
                    "--add-reads", "java.base=java.desktop",
-                   "-Xmodule:java.base")
+                   "--patch-module", "java.base=" + src)
           .outdir(classes)
           .files(findJavaFiles(src))
           .run()
@@ -304,7 +304,7 @@
 
         new JavacTask(tb)
           .options("--add-reads", "m1x=ALL-UNNAMED",
-                   "-Xmodule:m1x",
+                   "--patch-module", "m1x=" + unnamedSrc,
                    "--module-path", classes.toString())
           .outdir(unnamedClasses)
           .files(findJavaFiles(unnamedSrc))
--- a/langtools/test/tools/javac/modules/AllDefaultTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/modules/AllDefaultTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,7 +23,7 @@
 
 /**
  * @test
- * @bug 0000000
+ * @bug 8164590 8170691
  * @summary Test use of ALL-DEFAULT token
  * @library /tools/lib
  * @modules
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/modules/CompileModulePatchTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,694 @@
+/*
+ * 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 8173777
+ * @summary tests for multi-module mode compilation
+ * @library /tools/lib
+ * @modules
+ *      jdk.compiler/com.sun.tools.javac.api
+ *      jdk.compiler/com.sun.tools.javac.code
+ *      jdk.compiler/com.sun.tools.javac.main
+ *      jdk.compiler/com.sun.tools.javac.processing
+ * @build toolbox.ToolBox toolbox.JavacTask toolbox.ModuleBuilder ModuleTestBase
+ * @run main CompileModulePatchTest
+ */
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+import javax.annotation.processing.AbstractProcessor;
+import javax.annotation.processing.RoundEnvironment;
+import javax.annotation.processing.SupportedAnnotationTypes;
+import javax.lang.model.SourceVersion;
+import javax.lang.model.element.ModuleElement;
+import javax.lang.model.element.TypeElement;
+import javax.lang.model.util.Elements;
+
+import com.sun.tools.javac.code.Symtab;
+import com.sun.tools.javac.processing.JavacProcessingEnvironment;
+import toolbox.JavacTask;
+import toolbox.ModuleBuilder;
+import toolbox.Task;
+import toolbox.Task.Expect;
+
+public class CompileModulePatchTest extends ModuleTestBase {
+
+    public static void main(String... args) throws Exception {
+        new CompileModulePatchTest().runTests();
+    }
+
+    @Test
+    public void testCorrectModulePatch(Path base) throws Exception {
+        //note: avoiding use of java.base, as that gets special handling on some places:
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "package javax.lang.model.element; public interface Extra extends Element { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb)
+                .options("--patch-module", "java.compiler=" + src.toString())
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.isEmpty())
+            throw new Exception("expected output not found: " + log);
+    }
+
+    @Test
+    public void testCorrectModulePatchMultiModule(Path base) throws Exception {
+        //note: avoiding use of java.base, as that gets special handling on some places:
+        Path src = base.resolve("src");
+        Path m1 = src.resolve("m1");
+        tb.writeJavaFiles(m1, "package javax.lang.model.element; public interface Extra extends Element { }");
+        Path m2 = src.resolve("m2");
+        tb.writeJavaFiles(m2, "package com.sun.source.tree; public interface Extra extends Tree { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb)
+                .options("--patch-module", "java.compiler=" + m1.toString(),
+                         "--patch-module", "jdk.compiler=" + m2.toString(),
+                         "--module-source-path", "dummy")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.isEmpty())
+            throw new Exception("expected output not found: " + log);
+
+        checkFileExists(classes, "java.compiler/javax/lang/model/element/Extra.class");
+        checkFileExists(classes, "jdk.compiler/com/sun/source/tree/Extra.class");
+    }
+
+    @Test
+    public void testCorrectModulePatchMultiModule2(Path base) throws Exception {
+        //note: avoiding use of java.base, as that gets special handling on some places:
+        Path src = base.resolve("src");
+        Path m1 = src.resolve("m1");
+        tb.writeJavaFiles(m1,
+                          "package javax.lang.model.element; public interface Extra extends Element { }");
+        Path m2 = src.resolve("m2");
+        tb.writeJavaFiles(m2,
+                          "package com.sun.source.tree; public interface Extra extends Tree { }");
+        Path msp = base.resolve("msp");
+        Path m3 = msp.resolve("m3x");
+        tb.writeJavaFiles(m3,
+                          "module m3x { }",
+                          "package m3; public class Test { }");
+        Path m4 = msp.resolve("m4x");
+        tb.writeJavaFiles(m4,
+                          "module m4x { }",
+                          "package m4; public class Test { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb)
+                .options("--patch-module", "java.compiler=" + m1.toString(),
+                         "--patch-module", "jdk.compiler=" + m2.toString(),
+                         "--module-source-path", msp.toString())
+                .outdir(classes)
+                .files(findJavaFiles(src, msp))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.isEmpty())
+            throw new Exception("expected output not found: " + log);
+
+        checkFileExists(classes, "java.compiler/javax/lang/model/element/Extra.class");
+        checkFileExists(classes, "jdk.compiler/com/sun/source/tree/Extra.class");
+        checkFileExists(classes, "m3x/m3/Test.class");
+        checkFileExists(classes, "m4x/m4/Test.class");
+    }
+
+    @Test
+    public void testPatchModuleModuleSourcePathConflict(Path base) throws Exception {
+        //note: avoiding use of java.base, as that gets special handling on some places:
+        Path src = base.resolve("src");
+        Path m1 = src.resolve("m1x");
+        tb.writeJavaFiles(m1,
+                          "module m1x { }",
+                          "package m1; public class Test { }");
+        Path m2 = src.resolve("m2x");
+        tb.writeJavaFiles(m2,
+                          "module m2x { }",
+                          "package m2; public class Test { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        List<String> log = new JavacTask(tb)
+                .options("--patch-module", "m1x=" + m2.toString(),
+                         "--module-source-path", src.toString(),
+                         "-XDrawDiagnostics")
+                .outdir(classes)
+                .files(findJavaFiles(src.resolve("m1x").resolve("m1"),
+                                     src.resolve("m2x").resolve("m2")))
+                .run(Expect.FAIL)
+                .writeAll()
+                .getOutputLines(Task.OutputKind.DIRECT);
+
+        List<String> expectedOut = Arrays.asList(
+                "Test.java:1:1: compiler.err.file.patched.and.msp: m1x, m2x",
+                "1 error"
+        );
+
+        if (!expectedOut.equals(log))
+            throw new Exception("expected output not found: " + log);
+    }
+
+    @Test
+    public void testSourcePath(Path base) throws Exception {
+        //note: avoiding use of java.base, as that gets special handling on some places:
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "package javax.lang.model.element; public interface Extra extends Element, Other { }");
+        Path srcPath = base.resolve("src-path");
+        tb.writeJavaFiles(srcPath, "package javax.lang.model.element; interface Other { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        List<String> log = new JavacTask(tb)
+                .options("--patch-module", "java.compiler=" + src.toString(),
+                         "-sourcepath", srcPath.toString(),
+                         "-XDrawDiagnostics")
+                .outdir(classes)
+                .files(src.resolve("javax/lang/model/element/Extra.java"))
+                .run(Expect.FAIL)
+                .writeAll()
+                .getOutputLines(Task.OutputKind.DIRECT);
+
+        List<String> expectedOut = Arrays.asList(
+                "Extra.java:1:75: compiler.err.cant.resolve: kindname.class, Other, , ",
+                "1 error"
+        );
+
+        if (!expectedOut.equals(log))
+            throw new Exception("expected output not found: " + log);
+    }
+
+    @Test
+    public void testClassPath(Path base) throws Exception {
+        Path cpSrc = base.resolve("cpSrc");
+        tb.writeJavaFiles(cpSrc, "package p; public interface Other { }");
+        Path cpClasses = base.resolve("cpClasses");
+        tb.createDirectories(cpClasses);
+
+        String cpLog = new JavacTask(tb)
+                .outdir(cpClasses)
+                .files(findJavaFiles(cpSrc))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!cpLog.isEmpty())
+            throw new Exception("expected output not found: " + cpLog);
+
+        Path src = base.resolve("src");
+        //note: avoiding use of java.base, as that gets special handling on some places:
+        tb.writeJavaFiles(src, "package javax.lang.model.element; public interface Extra extends Element, p.Other { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        List<String> log = new JavacTask(tb)
+                .options("--patch-module", "java.compiler=" + src.toString(),
+                         "--class-path", cpClasses.toString(),
+                         "-XDrawDiagnostics")
+                .outdir(classes)
+                .files(src.resolve("javax/lang/model/element/Extra.java"))
+                .run(Expect.FAIL)
+                .writeAll()
+                .getOutputLines(Task.OutputKind.DIRECT);
+
+        List<String> expectedOut = Arrays.asList(
+                "Extra.java:1:76: compiler.err.doesnt.exist: p",
+                "1 error"
+        );
+
+        if (!expectedOut.equals(log))
+            throw new Exception("expected output not found: " + log);
+    }
+
+    @Test
+    public void testNoModuleInfoOnSourcePath(Path base) throws Exception {
+        //note: avoiding use of java.base, as that gets special handling on some places:
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src,
+                          "module java.compiler {}",
+                          "package javax.lang.model.element; public interface Extra { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        List<String> log;
+        List<String> expected;
+
+        log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--patch-module", "java.compiler=" + src.toString())
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutputLines(Task.OutputKind.DIRECT);
+
+        expected = Arrays.asList("Extra.java:1:1: compiler.err.module-info.with.patched.module.sourcepath",
+                                 "1 error");
+
+        if (!expected.equals(log))
+            throw new Exception("expected output not found: " + log);
+
+        //multi-module mode:
+        log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--patch-module", "java.compiler=" + src.toString(),
+                         "--module-source-path", "dummy")
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutputLines(Task.OutputKind.DIRECT);
+
+        expected = Arrays.asList("- compiler.err.locn.module-info.not.allowed.on.patch.path: module-info.java",
+                                 "1 error");
+
+        if (!expected.equals(log))
+            throw new Exception("expected output not found: " + log);
+    }
+
+    @Test
+    public void testNoModuleInfoInClassOutput(Path base) throws Exception {
+        //note: avoiding use of java.base, as that gets special handling on some places:
+        Path srcMod = base.resolve("src-mod");
+        tb.writeJavaFiles(srcMod,
+                          "module mod {}");
+        Path classes = base.resolve("classes").resolve("java.compiler");
+        tb.createDirectories(classes);
+
+        String logMod = new JavacTask(tb)
+                .options()
+                .outdir(classes)
+                .files(findJavaFiles(srcMod))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!logMod.isEmpty())
+            throw new Exception("unexpected output found: " + logMod);
+
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src,
+                          "package javax.lang.model.element; public interface Extra { }");
+        tb.createDirectories(classes);
+
+        List<String> log;
+        List<String> expected;
+
+        log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--patch-module", "java.compiler=" + src.toString())
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutputLines(Task.OutputKind.DIRECT);
+
+        expected = Arrays.asList("Extra.java:1:1: compiler.err.module-info.with.patched.module.classoutput",
+                                 "1 error");
+
+        if (!expected.equals(log))
+            throw new Exception("expected output not found: " + log);
+
+        log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--patch-module", "java.compiler=" + src.toString(),
+                         "--module-source-path", "dummy")
+                .outdir(classes.getParent())
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutputLines(Task.OutputKind.DIRECT);
+
+        expected = Arrays.asList("- compiler.err.locn.module-info.not.allowed.on.patch.path: module-info.class",
+                                 "1 error");
+
+        if (!expected.equals(log))
+            throw new Exception("expected output not found: " + log);
+    }
+
+    @Test
+    public void testWithModulePath(Path base) throws Exception {
+        Path modSrc = base.resolve("modSrc");
+        Path modules = base.resolve("modules");
+        new ModuleBuilder(tb, "m1")
+                .classes("package pkg1; public interface E { }")
+                .build(modSrc, modules);
+
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "package p; interface A extends pkg1.E { }");
+
+        new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("--module-path", modules.toString(),
+                        "--patch-module", "m1=" + src.toString())
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+
+        //checks module bounds still exist
+        new ModuleBuilder(tb, "m2")
+                .classes("package pkg2; public interface D { }")
+                .build(modSrc, modules);
+
+        Path src2 = base.resolve("src2");
+        tb.writeJavaFiles(src2, "package p; interface A extends pkg2.D { }");
+
+        List<String> log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("-XDrawDiagnostics",
+                        "--module-path", modules.toString(),
+                        "--patch-module", "m1=" + src2.toString())
+                .files(findJavaFiles(src2))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutputLines(Task.OutputKind.DIRECT);
+
+        List<String> expected = Arrays.asList("A.java:1:32: compiler.err.package.not.visible: pkg2, (compiler.misc.not.def.access.does.not.read: m1, pkg2, m2)",
+                "1 error");
+
+        if (!expected.equals(log))
+            throw new Exception("expected output not found: " + log);
+    }
+
+    @Test
+    public void testWithUpgradeModulePath(Path base) throws Exception {
+        Path modSrc = base.resolve("modSrc");
+        Path modules = base.resolve("modules");
+        new ModuleBuilder(tb, "m1")
+                .classes("package pkg1; public interface E { }")
+                .build(modSrc, modules);
+
+        Path upgrSrc = base.resolve("upgradeSrc");
+        Path upgrade = base.resolve("upgrade");
+        new ModuleBuilder(tb, "m1")
+                .classes("package pkg1; public interface D { }")
+                .build(upgrSrc, upgrade);
+
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "package p; interface A extends pkg1.D { }");
+
+        new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("--module-path", modules.toString(),
+                        "--upgrade-module-path", upgrade.toString(),
+                        "--patch-module", "m1=" + src.toString())
+                .files(findJavaFiles(src))
+                .run()
+                .writeAll();
+    }
+
+    @Test
+    public void testUnnamedIsolation(Path base) throws Exception {
+        //note: avoiding use of java.base, as that gets special handling on some places:
+        Path sourcePath = base.resolve("source-path");
+        tb.writeJavaFiles(sourcePath, "package src; public class Src {}");
+
+        Path classPathSrc = base.resolve("class-path-src");
+        tb.writeJavaFiles(classPathSrc, "package cp; public class CP { }");
+        Path classPath = base.resolve("classPath");
+        tb.createDirectories(classPath);
+
+        String cpLog = new JavacTask(tb)
+                .outdir(classPath)
+                .files(findJavaFiles(classPathSrc))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!cpLog.isEmpty())
+            throw new Exception("expected output not found: " + cpLog);
+
+        Path modulePathSrc = base.resolve("module-path-src");
+        tb.writeJavaFiles(modulePathSrc,
+                          "module m {}",
+                          "package m; public class M {}");
+        Path modulePath = base.resolve("modulePath");
+        tb.createDirectories(modulePath.resolve("m"));
+
+        String modLog = new JavacTask(tb)
+                .outdir(modulePath.resolve("m"))
+                .files(findJavaFiles(modulePathSrc))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!modLog.isEmpty())
+            throw new Exception("expected output not found: " + modLog);
+
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "package m; public class Extra { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        String log = new JavacTask(tb)
+                .options("--patch-module", "m=" + sourcePath.toString(),
+                         "--class-path", classPath.toString(),
+                         "--source-path", sourcePath.toString(),
+                         "--module-path", modulePath.toString(),
+                         "--processor-path", System.getProperty("test.classes"),
+                         "-XDaccessInternalAPI=true",
+                         "-processor", CheckModuleContentProcessing.class.getName())
+                .outdir(classes)
+                .files(findJavaFiles(sourcePath))
+                .run()
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.isEmpty())
+            throw new Exception("expected output not found: " + log);
+    }
+
+    @SupportedAnnotationTypes("*")
+    public static final class CheckModuleContentProcessing extends AbstractProcessor {
+
+        @Override
+        public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
+            Symtab syms = Symtab.instance(((JavacProcessingEnvironment) processingEnv).getContext());
+            Elements elements = processingEnv.getElementUtils();
+            ModuleElement unnamedModule = syms.unnamedModule;
+            ModuleElement mModule = elements.getModuleElement("m");
+
+            assertNonNull("mModule found", mModule);
+            assertNonNull("src.Src from m", elements.getTypeElement(mModule, "src.Src"));
+            assertNull("cp.CP not from m", elements.getTypeElement(mModule, "cp.CP"));
+            assertNull("src.Src not from unnamed", elements.getTypeElement(unnamedModule, "src.Src"));
+            assertNonNull("cp.CP from unnamed", elements.getTypeElement(unnamedModule, "cp.CP"));
+
+            return false;
+        }
+
+        @Override
+        public SourceVersion getSupportedSourceVersion() {
+            return SourceVersion.latest();
+        }
+
+        private static void assertNonNull(String msg, Object val) {
+            if (val == null) {
+                throw new AssertionError(msg);
+            }
+        }
+
+        private static void assertNull(String msg, Object val) {
+            if (val != null) {
+                throw new AssertionError(msg);
+            }
+        }
+    }
+
+    @Test
+    public void testSingleModeIncremental(Path base) throws Exception {
+        //note: avoiding use of java.base, as that gets special handling on some places:
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src,
+                          "package javax.lang.model.element; public interface Extra extends Element { }",
+                          "package javax.lang.model.element; public interface Extra2 extends Extra { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        Thread.sleep(2000); //ensure newer timestamps on classfiles:
+
+        new JavacTask(tb)
+            .options("--patch-module", "java.compiler=" + src.toString())
+            .outdir(classes)
+            .files(findJavaFiles(src))
+            .run()
+            .writeAll()
+            .getOutput(Task.OutputKind.DIRECT);
+
+        List<String> log = new JavacTask(tb)
+            .options("--patch-module", "java.compiler=" + src.toString(),
+                     "-verbose")
+            .outdir(classes)
+            .files(findJavaFiles(src.resolve("javax/lang/model/element/Extra2.java"
+                                    .replace("/", src.getFileSystem().getSeparator()))))
+            .run()
+            .writeAll()
+            .getOutputLines(Task.OutputKind.DIRECT)
+            .stream()
+            .filter(l -> l.contains("parsing"))
+            .collect(Collectors.toList());
+
+        boolean parsesExtra2 = log.stream()
+                                  .anyMatch(l -> l.contains("Extra2.java"));
+        boolean parsesExtra = log.stream()
+                              .anyMatch(l -> l.contains("Extra.java"));
+
+        if (!parsesExtra2 || parsesExtra) {
+            throw new AssertionError("Unexpected output: " + log);
+        }
+    }
+
+    @Test
+    public void testComplexMSPAndPatch(Path base) throws Exception {
+        //note: avoiding use of java.base, as that gets special handling on some places:
+        Path src1 = base.resolve("src1");
+        Path src1ma = src1.resolve("ma");
+        tb.writeJavaFiles(src1ma,
+                          "module ma { exports ma; }",
+                          "package ma; public class C1 { public static void method() { } }",
+                          "package ma.impl; public class C2 { }");
+        Path src1mb = src1.resolve("mb");
+        tb.writeJavaFiles(src1mb,
+                          "module mb { requires ma; }",
+                          "package mb.impl; public class C2 { public static void method() { } }");
+        Path src1mc = src1.resolve("mc");
+        tb.writeJavaFiles(src1mc,
+                          "module mc { }");
+        Path classes1 = base.resolve("classes1");
+        tb.createDirectories(classes1);
+        tb.cleanDirectory(classes1);
+
+        new JavacTask(tb)
+            .options("--module-source-path", src1.toString())
+            .files(findJavaFiles(src1))
+            .outdir(classes1)
+            .run()
+            .writeAll();
+
+        //patching:
+        Path src2 = base.resolve("src2");
+        Path src2ma = src2.resolve("ma");
+        tb.writeJavaFiles(src2ma,
+                          "package ma.impl; public class C2 { public static void extra() { ma.C1.method(); } }",
+                          "package ma.impl; public class C3 { public void test() { C2.extra(); } }");
+        Path src2mb = src2.resolve("mb");
+        tb.writeJavaFiles(src2mb,
+                          "package mb.impl; public class C3 { public void test() { C2.method(); ma.C1.method(); ma.impl.C2.extra(); } }");
+        Path src2mc = src2.resolve("mc");
+        tb.writeJavaFiles(src2mc,
+                          "package mc.impl; public class C2 { public static void test() { } }",
+                          //will require --add-reads ma:
+                          "package mc.impl; public class C3 { public static void test() { ma.impl.C2.extra(); } }");
+        Path src2mt = src2.resolve("mt");
+        tb.writeJavaFiles(src2mt,
+                          "module mt { requires ma; requires mb; }",
+                          "package mt.impl; public class C2 { public static void test() { mb.impl.C2.method(); ma.impl.C2.extra(); } }",
+                          "package mt.impl; public class C3 { public static void test() { C2.test(); mc.impl.C2.test(); } }");
+        Path classes2 = base.resolve("classes2");
+        tb.createDirectories(classes2);
+        tb.cleanDirectory(classes2);
+
+        Thread.sleep(2000); //ensure newer timestamps on classfiles:
+
+        new JavacTask(tb)
+            .options("--module-path", classes1.toString(),
+                     "--patch-module", "ma=" + src2ma.toString(),
+                     "--patch-module", "mb=" + src2mb.toString(),
+                     "--add-exports", "ma/ma.impl=mb",
+                     "--patch-module", "mc=" + src2mc.toString(),
+                     "--add-reads", "mc=ma",
+                     "--add-exports", "ma/ma.impl=mc",
+                     "--add-exports", "ma/ma.impl=mt",
+                     "--add-exports", "mb/mb.impl=mt",
+                     "--add-exports", "mc/mc.impl=mt",
+                     "--add-reads", "mt=mc",
+                     "--module-source-path", src2.toString())
+            .outdir(classes2)
+            .files(findJavaFiles(src2))
+            .run()
+            .writeAll();
+
+        //incremental compilation (C2 mustn't be compiled, C3 must):
+        tb.writeJavaFiles(src2ma,
+                          "package ma.impl; public class C3 { public void test() { ma.C1.method(); C2.extra(); } }");
+        tb.writeJavaFiles(src2mt,
+                          "package mt.impl; public class C3 { public static void test() { mc.impl.C2.test(); C2.test(); } }");
+
+        List<String> log = new JavacTask(tb)
+            .options("--module-path", classes1.toString(),
+                     "--patch-module", "ma=" + src2ma.toString(),
+                     "--patch-module", "mb=" + src2mb.toString(),
+                     "--add-exports", "ma/ma.impl=mb",
+                     "--patch-module", "mc=" + src2mc.toString(),
+                     "--add-reads", "mc=ma",
+                     "--add-exports", "ma/ma.impl=mc",
+                     "--add-exports", "ma/ma.impl=mt",
+                     "--add-exports", "mb/mb.impl=mt",
+                     "--add-exports", "mc/mc.impl=mt",
+                     "--add-reads", "mt=mc",
+                     "--module-source-path", src2.toString(),
+                     "--add-modules", "mc",
+                     "-verbose")
+            .outdir(classes2)
+            .files(src2ma.resolve("ma").resolve("impl").resolve("C3.java"),
+                   src2mt.resolve("mt").resolve("impl").resolve("C3.java"))
+            .run()
+            .writeAll()
+            .getOutputLines(Task.OutputKind.DIRECT)
+            .stream()
+            .filter(l -> l.contains("parsing"))
+            .collect(Collectors.toList());
+
+        boolean parsesC3 = log.stream()
+                              .anyMatch(l -> l.contains("C3.java"));
+        boolean parsesC2 = log.stream()
+                              .anyMatch(l -> l.contains("C2.java"));
+
+        if (!parsesC3 || parsesC2) {
+            throw new AssertionError("Unexpected output: " + log);
+        }
+    }
+
+    private void checkFileExists(Path dir, String path) {
+        Path toCheck = dir.resolve(path.replace("/", dir.getFileSystem().getSeparator()));
+
+        if (!Files.exists(toCheck)) {
+            throw new AssertionError(toCheck.toString() + " does not exist!");
+        }
+    }
+}
--- a/langtools/test/tools/javac/modules/ConvenientAccessErrorsTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/modules/ConvenientAccessErrorsTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8169197 8172668 8173117
+ * @bug 8169197 8172668 8173117 8175007
  * @summary Check convenient errors are produced for inaccessible classes.
  * @library /tools/lib
  * @modules jdk.compiler/com.sun.tools.javac.api
@@ -704,4 +704,44 @@
             throw new Exception("Expected names not generated: " + actual);
         }
     }
+
+    @Test
+    public void testInaccessibleInVisible(Path base) throws Exception {
+        Path src = base.resolve("src");
+        Path src_ma = src.resolve("ma");
+        tb.writeJavaFiles(src_ma,
+                          "module ma { exports ma; }",
+                          "package ma; class NotApi { public static class Inner { } }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new JavacTask(tb)
+            .outdir(classes)
+            .files(findJavaFiles(src_ma))
+            .run()
+            .writeAll();
+
+        Path src_mb = src.resolve("mb");
+        tb.writeJavaFiles(src_mb,
+                          "module mb { requires ma; }",
+                          "package mb.a; public class Test { ma.NotApi.Inner i1; mb.b.NotApi.Inner i2; }",
+                          "package mb.b; class NotApi { public static class Inner { } }");
+
+        List<String> log = new JavacTask(tb)
+                .options("-XDrawDiagnostics",
+                         "--module-path", classes.toString())
+                .outdir(classes)
+                .files(findJavaFiles(src_mb))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutputLines(Task.OutputKind.DIRECT);
+
+        List<String> expected = Arrays.asList(
+                "Test.java:1:44: compiler.err.not.def.access.class.intf.cant.access: ma.NotApi.Inner, ma.NotApi",
+                "Test.java:1:66: compiler.err.not.def.access.class.intf.cant.access: mb.b.NotApi.Inner, mb.b.NotApi",
+                "2 errors");
+
+        if (!expected.equals(log))
+            throw new Exception("expected output not found; actual: " + log);
+    }
 }
--- a/langtools/test/tools/javac/modules/EnvVarTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/modules/EnvVarTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -24,7 +24,7 @@
 /*
  * @test
  * @bug 8156962
- * @summary Tests use of _JAVAC_OPTIONS env variable
+ * @summary Tests use of JDK_JAVAC_OPTIONS env variable
  * @library /tools/lib
  * @modules jdk.compiler/com.sun.tools.javac.api
  *          jdk.compiler/com.sun.tools.javac.main
@@ -71,7 +71,7 @@
 
         tb.out.println("test that addExports can be provided with env variable");
         new JavacTask(tb, Mode.EXEC)
-                .envVar("_JAVAC_OPTIONS", "--add-exports jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED")
+                .envVar("JDK_JAVAC_OPTIONS", "--add-exports jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED")
                 .outdir(classes)
                 .files(findJavaFiles(src))
                 .run(Expect.SUCCESS)
@@ -83,7 +83,7 @@
                 "--add-exports jdk.compiler/com.sun.tools.javac.jvm=ALL-UNNAMED");
 
         new JavacTask(tb, Mode.EXEC)
-                .envVar("_JAVAC_OPTIONS", "@" + atFile)
+                .envVar("JDK_JAVAC_OPTIONS", "@" + atFile)
                 .outdir(classes)
                 .files(findJavaFiles(src))
                 .run(Expect.SUCCESS)
--- a/langtools/test/tools/javac/modules/InheritRuntimeEnvironmentTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/modules/InheritRuntimeEnvironmentTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -177,7 +177,7 @@
         Files.createDirectories(patch);
 
         new JavacTask(tb)
-                .options("-Xmodule:java.base")
+                .options("--patch-module", "java.base=" + patchSrc.toString())
                 .outdir(patch)
                 .sourcepath(patchSrc)
                 .files(findJavaFiles(patchSrc))
@@ -238,7 +238,7 @@
                 Arrays.asList("--add-exports", "jdk.compiler/com.sun.tools.javac.main=ALL-UNNAMED");
         List<Path> files = Arrays.asList(findJavaFiles(src));
 
-        String envName = "_JAVAC_OPTIONS";
+        String envName = "JDK_JAVAC_OPTIONS";
         String envValue = String.join(" ", testOpts);
 
         out.println("  javac:");
--- a/langtools/test/tools/javac/modules/ModuleInfoTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/modules/ModuleInfoTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -94,7 +94,7 @@
                 .writeAll()
                 .getOutput(Task.OutputKind.DIRECT);
 
-        if (!log.contains("module-info.java:1:8: compiler.err.class.public.should.be.in.file: C"))
+        if (!log.contains("module-info.java:1:8: compiler.err.class.public.should.be.in.file: kindname.class, C"))
             throw new Exception("expected output not found");
     }
 
@@ -557,4 +557,187 @@
                 throw new Exception("expected output not found for: " + moduleInfo + "; actual: " + log);
         }
     }
-}
+
+    @Test
+    public void testMalformedModuleNames(Path base) throws Exception {
+        testMalformedName(base, "m1.package", "module-info.java:1:11: compiler.err.expected: token.identifier");
+        testMalformedName(base, "m1/package", "module-info.java:1:10: compiler.err.expected: '{'");
+        testMalformedName(base, "m1->long", "module-info.java:1:10: compiler.err.expected: '{'");
+        testMalformedName(base, "m1::long", "module-info.java:1:10: compiler.err.expected: '{'");
+        testMalformedName(base, "m1&long", "module-info.java:1:10: compiler.err.expected: '{'");
+        testMalformedName(base, "m1%long", "module-info.java:1:10: compiler.err.expected: '{'");
+        testMalformedName(base, "m1@long", "module-info.java:1:10: compiler.err.expected: '{'");
+        testMalformedName(base, "@m1", "module-info.java:1:7: compiler.err.expected: token.identifier");
+        testMalformedName(base, "!", "module-info.java:1:7: compiler.err.expected: token.identifier");
+        testMalformedName(base, "m1#long", "module-info.java:1:10: compiler.err.illegal.char: #");
+        testMalformedName(base, "m1\\long", "module-info.java:1:10: compiler.err.illegal.char: \\");
+        testMalformedName(base, "module.", "module-info.java:1:15: compiler.err.expected: token.identifier");
+        testMalformedName(base, ".module", "module-info.java:1:7: compiler.err.expected: token.identifier");
+        testMalformedName(base, "1module", "module-info.java:1:7: compiler.err.expected: token.identifier");
+        testMalformedName(base, "module module", "module-info.java:1:14: compiler.err.expected: '{'");
+    }
+
+    private void testMalformedName(Path base, String name, String expected) throws Exception {
+        Path src = base.resolve("src");
+        Path src_m1 = src.resolve("m1");
+        tb.writeJavaFiles(src_m1, "module " + name + " { }");
+
+        Path classes = base.resolve("classes");
+        Files.createDirectories(classes);
+
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics", "--module-source-path", src.toString())
+                .outdir(classes)
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains(expected))
+            throw new Exception("expected output not found. Name: " + name + " Expected: " + expected);
+    }
+
+    @Test
+    public void testWrongOpensTransitiveFlag(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "module M { opens transitive p1; }",
+                "package p1; public class A { }");
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("module-info.java:1:28: compiler.err.expected: ';'"))
+            throw new Exception("expected output not found");
+    }
+
+    @Test
+    public void testWrongOpensStaticFlag(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "module M { opens static p1; }",
+                "package p1; public class A { }");
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("module-info.java:1:17: compiler.err.expected: token.identifier"))
+            throw new Exception("expected output not found");
+    }
+
+    @Test
+    public void testSeveralOpensDirectives(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "module M { opens opens p1; }",
+                "package p1; public class A { }");
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("module-info.java:1:23: compiler.err.expected: ';'"))
+            throw new Exception("expected output not found");
+    }
+
+    @Test
+    public void testUnknownDirective(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "module M { boolean p1; }",
+                "package p1; public class A { }");
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("module-info.java:1:11: compiler.err.expected: '}'"))
+            throw new Exception("expected output not found");
+    }
+
+    @Test
+    public void testUnknownModuleFlag(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "private module M { }",
+                "package p1; public class A { }");
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("module-info.java:1:9: compiler.err.mod.not.allowed.here: private"))
+            throw new Exception("expected output not found");
+    }
+
+    @Test
+    public void testDirectiveOnModuleDeclaration(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "opens module M { }",
+                "package p1; public class A { }");
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("module-info.java:1:1: compiler.err.expected.module.or.open"))
+            throw new Exception("expected output not found");
+    }
+
+    @Test
+    public void testTooOpenModule(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "open open module M { }",
+                "package p1; public class A { }");
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("module-info.java:1:6: compiler.err.expected.module"))
+            throw new Exception("expected output not found");
+    }
+
+    @Test
+    public void testEnumAsModuleFlag(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "enum module M { }",
+                "package p1; public class A { }");
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("module-info.java:1:12: compiler.err.expected: '{'"))
+            throw new Exception("expected output not found");
+    }
+
+    @Test
+    public void testClassInModule(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "module M { class B { } }",
+                "package p1; public class A { }");
+        String log = new JavacTask(tb)
+                .options("-XDrawDiagnostics")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("module-info.java:1:11: compiler.err.expected: '}'"))
+            throw new Exception("expected output not found");
+    }
+}
\ No newline at end of file
--- a/langtools/test/tools/javac/modules/ModulePathTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/modules/ModulePathTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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,6 +23,7 @@
 
 /*
  * @test
+ * @bug 8142968 8174104
  * @summary tests for --module-path
  * @library /tools/lib
  * @modules
@@ -57,7 +58,7 @@
     }
 
     @Test
-    public void testNotExistsOnPath(Path base) throws Exception {
+    public void testNotExistsOnPath_noWarn(Path base) throws Exception {
         Path src = base.resolve("src");
         tb.writeJavaFiles(src, "class C { }");
 
@@ -65,11 +66,29 @@
                 .options("-XDrawDiagnostics",
                         "--module-path", "doesNotExist")
                 .files(findJavaFiles(src))
-                .run(Task.Expect.FAIL)
+                .run(Task.Expect.SUCCESS)
                 .writeAll()
                 .getOutput(Task.OutputKind.DIRECT);
 
-        if (!log.contains("- compiler.err.illegal.argument.for.option: --module-path, doesNotExist"))
+        if (!log.isEmpty())
+            throw new Exception("unexpected output");
+    }
+
+    @Test
+    public void testNotExistsOnPath_warn(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src, "class C { }");
+
+        String log = new JavacTask(tb, Task.Mode.CMDLINE)
+                .options("-XDrawDiagnostics",
+                        "-Xlint:path",
+                        "--module-path", "doesNotExist")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.SUCCESS)
+                .writeAll()
+                .getOutput(Task.OutputKind.DIRECT);
+
+        if (!log.contains("- compiler.warn.path.element.not.found: doesNotExist"))
             throw new Exception("expected output not found");
     }
 
--- a/langtools/test/tools/javac/modules/PatchModulesTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/modules/PatchModulesTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -28,7 +28,7 @@
  * @library /tools/lib
  * @modules
  *      jdk.compiler/com.sun.tools.javac.api
- *      jdk.compiler/com.sun.tools.javac.file:+open
+ *      jdk.compiler/com.sun.tools.javac.file
  *      jdk.compiler/com.sun.tools.javac.main
  * @build toolbox.ToolBox toolbox.JavacTask toolbox.ModuleBuilder ModuleTestBase
  * @run main PatchModulesTest
@@ -38,21 +38,26 @@
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.io.StringWriter;
-import java.lang.reflect.Field;
+import java.nio.file.Files;
 import java.nio.file.Path;
 import java.nio.file.Paths;
+import java.util.AbstractMap.SimpleEntry;
 import java.util.List;
 import java.util.Map;
+import java.util.Map.Entry;
+import java.util.TreeMap;
 import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
 
+import javax.tools.JavaFileManager.Location;
 import javax.tools.JavaFileObject;
 import javax.tools.ToolProvider;
+import javax.tools.StandardJavaFileManager;
+import javax.tools.StandardLocation;
 
 import com.sun.source.util.JavacTask;
 import com.sun.tools.javac.api.JavacTool;
-import com.sun.tools.javac.file.BaseFileManager;
 import com.sun.tools.javac.file.JavacFileManager;
-import com.sun.tools.javac.file.Locations;
 
 import static java.util.Arrays.asList;
 
@@ -115,21 +120,29 @@
     void test(List<String> patches, boolean expectOK, String expect) throws Exception {
         JavacTool tool = (JavacTool) ToolProvider.getSystemJavaCompiler();
         StringWriter sw = new StringWriter();
-        try (PrintWriter pw = new PrintWriter(sw)) {
-            JavacFileManager fm = tool.getStandardFileManager(null, null, null);
+        try (PrintWriter pw = new PrintWriter(sw);
+            JavacFileManager fm = tool.getStandardFileManager(null, null, null)) {
             List<String> opts = patches.stream()
                 .map(p -> "--patch-module=" + p.replace(":", PS))
                 .collect(Collectors.toList());
             Iterable<? extends JavaFileObject> files = fm.getJavaFileObjects("C.java");
             JavacTask task = tool.getTask(pw, fm, null, opts, null, files);
 
-            Field locationsField = BaseFileManager.class.getDeclaredField("locations");
-            locationsField.setAccessible(true);
-            Object locations = locationsField.get(fm);
+            Map<String, List<Location>> mod2Location =
+                    StreamSupport.stream(fm.listLocationsForModules(StandardLocation.PATCH_MODULE_PATH)
+                                           .spliterator(),
+                                        false)
+                                 .flatMap(sl -> sl.stream())
+                                 .collect(Collectors.groupingBy(l -> fm.inferModuleName(l)));
 
-            Field patchMapField = Locations.class.getDeclaredField("patchMap");
-            patchMapField.setAccessible(true);
-            Map<?,?> patchMap = (Map<?,?>) patchMapField.get(locations);
+            Map<String, List<String>> patchMap = mod2Location.entrySet()
+                    .stream()
+                    .map(e -> new SimpleEntry<>(e.getKey(), e.getValue().get(0)))
+                    .map(e -> new SimpleEntry<>(e.getKey(), locationPaths(fm, e.getValue())))
+                    .collect(Collectors.toMap(Entry :: getKey,
+                                              Entry :: getValue,
+                                              (v1, v2) -> {throw new IllegalStateException();},
+                                              TreeMap::new));
             String found = patchMap.toString();
 
             if (!found.equals(expect)) {
@@ -150,5 +163,34 @@
             }
         }
     }
+
+    static List<String> locationPaths(StandardJavaFileManager fm, Location loc) {
+        return StreamSupport.stream(fm.getLocationAsPaths(loc).spliterator(), false)
+                            .map(p -> p.toString())
+                            .collect(Collectors.toList());
+    }
+
+    @Test
+    public void testPatchWithSource(Path base) throws Exception {
+        Path patch = base.resolve("patch");
+        tb.writeJavaFiles(patch, "package javax.lang.model.element; public interface Extra { }");
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src,
+                          "module m { requires java.compiler; }",
+                          "package test; public interface Test extends javax.lang.model.element.Extra { }");
+        Path classes = base.resolve("classes");
+        tb.createDirectories(classes);
+
+        new toolbox.JavacTask(tb)
+            .options("--patch-module", "java.compiler=" + patch.toString())
+            .outdir(classes)
+            .files(findJavaFiles(src))
+            .run()
+            .writeAll();
+
+        if (Files.exists(classes.resolve("javax"))) {
+            throw new AssertionError();
+        }
+    }
 }
 
--- a/langtools/test/tools/javac/modules/ProvidesTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/modules/ProvidesTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -377,7 +377,7 @@
                 .writeAll()
                 .getOutputLines(Task.OutputKind.DIRECT);
 
-        List<String> expected = Arrays.asList("module-info.java:1:34: compiler.err.not.def.public.cant.access: p2.C2, p2",
+        List<String> expected = Arrays.asList("module-info.java:1:34: compiler.err.not.def.public: p2.C2, p2",
                 "1 error");
         if (!output.containsAll(expected)) {
             throw new Exception("Expected output not found");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/modules/WrongErrorMessageForNestedServiceProviderTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,181 @@
+/*
+ * Copyright (c) 2017, 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 8174243
+ * @summary incorrect error message for nested service provider
+ * @library /tools/lib
+ * @modules
+ *      jdk.compiler/com.sun.tools.javac.api
+ *      jdk.compiler/com.sun.tools.javac.main
+ * @build toolbox.ToolBox toolbox.JavacTask ModuleTestBase
+ * @run main WrongErrorMessageForNestedServiceProviderTest
+ */
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.Arrays;
+import java.util.List;
+
+import toolbox.JavacTask;
+import toolbox.Task;
+import toolbox.ToolBox;
+
+public class WrongErrorMessageForNestedServiceProviderTest extends ModuleTestBase {
+    public static void main(String... args) throws Exception {
+        WrongErrorMessageForNestedServiceProviderTest t = new WrongErrorMessageForNestedServiceProviderTest();
+        t.runTests();
+    }
+
+    private static final String twoServicesModuleDef =
+            "module m {\n" +
+            "    exports example;\n" +
+            "    provides example.SomeService with example.ServiceImpl;\n" +
+            "    provides example.SomeServiceOuter with example.Outer.ServiceImplOuter;\n" +
+            "}";
+
+    private static final String someServiceInt =
+            "package example;\n" +
+            "public interface SomeService {\n" +
+            "    public void foo();\n" +
+            "}";
+
+    private static final String someServiceIntOuter =
+            "package example;\n" +
+            "public interface SomeServiceOuter {\n" +
+            "    public void foo();\n" +
+            "}";
+
+    @Test
+    public void testPositive(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src,
+                twoServicesModuleDef,
+                someServiceInt,
+                someServiceIntOuter,
+                "package example;\n" +
+                "public class ServiceImpl implements example.SomeService {\n" +
+                "    public ServiceImpl() {}\n" +
+                "    public void foo() {}\n" +
+                "}",
+
+                "package example;\n" +
+                "class Outer {\n" +
+                "    public static class ServiceImplOuter implements example.SomeServiceOuter {\n" +
+                "        public ServiceImplOuter() {}\n" +
+                "        public void foo() {}\n" +
+                "    }\n" +
+                "}");
+        Path classes = base.resolve("classes");
+        Files.createDirectories(classes);
+
+        List<String> output = new JavacTask(tb)
+                .outdir(classes)
+                .options("-Werror", "-XDrawDiagnostics")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.SUCCESS)
+                .writeAll()
+                .getOutputLines(Task.OutputKind.DIRECT);
+        List<String> expected = Arrays.asList("");
+        if (!output.containsAll(expected)) {
+            throw new Exception("Expected output not found");
+        }
+    }
+
+    @Test
+    public void testNegative(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src,
+                twoServicesModuleDef,
+                someServiceInt,
+                someServiceIntOuter,
+
+                "package example;\n" +
+                "class ServiceImpl implements example.SomeService {\n" +
+                "    public ServiceImpl() {}\n" +
+                "    public void foo() {}\n" +
+                "}",
+
+                "package example;\n" +
+                "class Outer {\n" +
+                "    static class ServiceImplOuter implements example.SomeServiceOuter {\n" +
+                "        public ServiceImplOuter() {}\n" +
+                "        public void foo() {}\n" +
+                "    }\n" +
+                "}");
+        Path classes = base.resolve("classes");
+        Files.createDirectories(classes);
+
+        List<String> output = new JavacTask(tb)
+                .outdir(classes)
+                .options("-Werror", "-XDrawDiagnostics")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.FAIL)
+                .writeAll()
+                .getOutputLines(Task.OutputKind.DIRECT);
+        List<String> expected = Arrays.asList(
+                "module-info.java:3:46: compiler.err.not.def.public: example.ServiceImpl, example",
+                "module-info.java:4:57: compiler.err.not.def.public: example.Outer.ServiceImplOuter, example.Outer",
+                "2 errors");
+        if (!output.containsAll(expected)) {
+            throw new Exception("Expected output not found");
+        }
+    }
+
+    @Test
+    public void testClassWrappedByPrivateClass(Path base) throws Exception {
+        Path src = base.resolve("src");
+        tb.writeJavaFiles(src,
+                "module m {\n" +
+                "    exports example;\n" +
+                "    provides example.SomeServiceOuter with example.Outer1.Outer2.ServiceImplOuter;\n" +
+                "}",
+
+                someServiceIntOuter,
+
+                "package example;\n" +
+                "class Outer1 {\n" +
+                "    static private class Outer2 {\n" +
+                "        public static class ServiceImplOuter implements example.SomeServiceOuter {\n" +
+                "            public ServiceImplOuter() {}\n" +
+                "            public void foo() {}\n" +
+                "        }\n" +
+                "    }\n" +
+                "}");
+        Path classes = base.resolve("classes");
+        Files.createDirectories(classes);
+
+        List<String> output = new JavacTask(tb)
+                .outdir(classes)
+                .options("-Werror", "-XDrawDiagnostics")
+                .files(findJavaFiles(src))
+                .run(Task.Expect.SUCCESS)
+                .writeAll()
+                .getOutputLines(Task.OutputKind.DIRECT);
+        List<String> expected = Arrays.asList("");
+        if (!output.containsAll(expected)) {
+            throw new Exception("Expected output not found");
+        }
+    }
+}
--- a/langtools/test/tools/javac/modules/XModuleTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,422 +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
- * @summary tests for multi-module mode compilation
- * @library /tools/lib
- * @modules
- *      jdk.compiler/com.sun.tools.javac.api
- *      jdk.compiler/com.sun.tools.javac.code
- *      jdk.compiler/com.sun.tools.javac.main
- *      jdk.compiler/com.sun.tools.javac.processing
- * @build toolbox.ToolBox toolbox.JavacTask toolbox.ModuleBuilder ModuleTestBase
- * @run main XModuleTest
- */
-
-import java.nio.file.Path;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Set;
-
-import javax.annotation.processing.AbstractProcessor;
-import javax.annotation.processing.RoundEnvironment;
-import javax.annotation.processing.SupportedAnnotationTypes;
-import javax.lang.model.SourceVersion;
-import javax.lang.model.element.ModuleElement;
-import javax.lang.model.element.TypeElement;
-import javax.lang.model.util.Elements;
-
-import com.sun.tools.javac.code.Symtab;
-import com.sun.tools.javac.processing.JavacProcessingEnvironment;
-import toolbox.JavacTask;
-import toolbox.ModuleBuilder;
-import toolbox.Task;
-import toolbox.Task.Expect;
-
-public class XModuleTest extends ModuleTestBase {
-
-    public static void main(String... args) throws Exception {
-        new XModuleTest().runTests();
-    }
-
-    @Test
-    public void testCorrectXModule(Path base) throws Exception {
-        //note: avoiding use of java.base, as that gets special handling on some places:
-        Path src = base.resolve("src");
-        tb.writeJavaFiles(src, "package javax.lang.model.element; public interface Extra extends Element { }");
-        Path classes = base.resolve("classes");
-        tb.createDirectories(classes);
-
-        String log = new JavacTask(tb)
-                .options("-Xmodule:java.compiler")
-                .outdir(classes)
-                .files(findJavaFiles(src))
-                .run()
-                .writeAll()
-                .getOutput(Task.OutputKind.DIRECT);
-
-        if (!log.isEmpty())
-            throw new Exception("expected output not found: " + log);
-    }
-
-    @Test
-    public void testSourcePath(Path base) throws Exception {
-        //note: avoiding use of java.base, as that gets special handling on some places:
-        Path src = base.resolve("src");
-        tb.writeJavaFiles(src, "package javax.lang.model.element; public interface Extra extends Element, Other { }", "package javax.lang.model.element; interface Other { }");
-        Path classes = base.resolve("classes");
-        tb.createDirectories(classes);
-
-        String log = new JavacTask(tb)
-                .options("-Xmodule:java.compiler", "-sourcepath", src.toString())
-                .outdir(classes)
-                .files(src.resolve("javax/lang/model/element/Extra.java"))
-                .run()
-                .writeAll()
-                .getOutput(Task.OutputKind.DIRECT);
-
-        if (!log.isEmpty())
-            throw new Exception("expected output not found: " + log);
-    }
-
-    @Test
-    public void testClassPath(Path base) throws Exception {
-        Path cpSrc = base.resolve("cpSrc");
-        tb.writeJavaFiles(cpSrc, "package p; public interface Other { }");
-        Path cpClasses = base.resolve("cpClasses");
-        tb.createDirectories(cpClasses);
-
-        String cpLog = new JavacTask(tb)
-                .outdir(cpClasses)
-                .files(findJavaFiles(cpSrc))
-                .run()
-                .writeAll()
-                .getOutput(Task.OutputKind.DIRECT);
-
-        if (!cpLog.isEmpty())
-            throw new Exception("expected output not found: " + cpLog);
-
-        Path src = base.resolve("src");
-        //note: avoiding use of java.base, as that gets special handling on some places:
-        tb.writeJavaFiles(src, "package javax.lang.model.element; public interface Extra extends Element, p.Other { }");
-        Path classes = base.resolve("classes");
-        tb.createDirectories(classes);
-
-        List<String> log = new JavacTask(tb)
-                .options("-Xmodule:java.compiler",
-                         "--class-path", cpClasses.toString(),
-                         "-XDrawDiagnostics")
-                .outdir(classes)
-                .files(src.resolve("javax/lang/model/element/Extra.java"))
-                .run(Expect.FAIL)
-                .writeAll()
-                .getOutputLines(Task.OutputKind.DIRECT);
-
-        List<String> expectedOut = Arrays.asList(
-                "Extra.java:1:76: compiler.err.doesnt.exist: p",
-                "1 error"
-        );
-
-        if (!expectedOut.equals(log))
-            throw new Exception("expected output not found: " + log);
-    }
-
-    @Test
-    public void testNoModuleInfoOnSourcePath(Path base) throws Exception {
-        //note: avoiding use of java.base, as that gets special handling on some places:
-        Path src = base.resolve("src");
-        tb.writeJavaFiles(src,
-                          "module java.compiler {}",
-                          "package javax.lang.model.element; public interface Extra { }");
-        Path classes = base.resolve("classes");
-        tb.createDirectories(classes);
-
-        List<String> log = new JavacTask(tb)
-                .options("-XDrawDiagnostics", "-Xmodule:java.compiler")
-                .outdir(classes)
-                .files(findJavaFiles(src))
-                .run(Task.Expect.FAIL)
-                .writeAll()
-                .getOutputLines(Task.OutputKind.DIRECT);
-
-        List<String> expected = Arrays.asList("Extra.java:1:1: compiler.err.module-info.with.xmodule.sourcepath",
-                                              "1 error");
-
-        if (!expected.equals(log))
-            throw new Exception("expected output not found: " + log);
-    }
-
-    @Test
-    public void testNoModuleInfoInClassOutput(Path base) throws Exception {
-        //note: avoiding use of java.base, as that gets special handling on some places:
-        Path srcMod = base.resolve("src-mod");
-        tb.writeJavaFiles(srcMod,
-                          "module mod {}");
-        Path classes = base.resolve("classes");
-        tb.createDirectories(classes);
-
-        String logMod = new JavacTask(tb)
-                .options()
-                .outdir(classes)
-                .files(findJavaFiles(srcMod))
-                .run()
-                .writeAll()
-                .getOutput(Task.OutputKind.DIRECT);
-
-        if (!logMod.isEmpty())
-            throw new Exception("unexpected output found: " + logMod);
-
-        Path src = base.resolve("src");
-        tb.writeJavaFiles(src,
-                          "package javax.lang.model.element; public interface Extra { }");
-        tb.createDirectories(classes);
-
-        List<String> log = new JavacTask(tb)
-                .options("-XDrawDiagnostics", "-Xmodule:java.compiler")
-                .outdir(classes)
-                .files(findJavaFiles(src))
-                .run(Task.Expect.FAIL)
-                .writeAll()
-                .getOutputLines(Task.OutputKind.DIRECT);
-
-        List<String> expected = Arrays.asList("Extra.java:1:1: compiler.err.module-info.with.xmodule.classpath",
-                                              "1 error");
-
-        if (!expected.equals(log))
-            throw new Exception("expected output not found: " + log);
-    }
-
-    @Test
-    public void testModuleSourcePathXModule(Path base) throws Exception {
-        //note: avoiding use of java.base, as that gets special handling on some places:
-        Path src = base.resolve("src");
-        tb.writeJavaFiles(src, "package javax.lang.model.element; public interface Extra extends Element { }");
-        Path classes = base.resolve("classes");
-        tb.createDirectories(classes);
-
-        List<String> log = new JavacTask(tb)
-                .options("-XDrawDiagnostics", "-Xmodule:java.compiler", "--module-source-path", src.toString())
-                .outdir(classes)
-                .files(findJavaFiles(src))
-                .run(Task.Expect.FAIL)
-                .writeAll()
-                .getOutputLines(Task.OutputKind.DIRECT);
-
-        List<String> expected = Arrays.asList("- compiler.err.xmodule.no.module.sourcepath");
-
-        if (!expected.equals(log))
-            throw new Exception("expected output not found: " + log);
-    }
-
-    @Test
-    public void testXModuleTooMany(Path base) throws Exception {
-        //note: avoiding use of java.base, as that gets special handling on some places:
-        Path src = base.resolve("src");
-        tb.writeJavaFiles(src, "package javax.lang.model.element; public interface Extra extends Element { }");
-        Path classes = base.resolve("classes");
-        tb.createDirectories(classes);
-
-        List<String> log = new JavacTask(tb, Task.Mode.CMDLINE)
-                .options("-XDrawDiagnostics", "-Xmodule:java.compiler", "-Xmodule:java.compiler")
-                .outdir(classes)
-                .files(findJavaFiles(src))
-                .run(Task.Expect.FAIL)
-                .writeAll()
-                .getOutputLines(Task.OutputKind.DIRECT);
-
-        List<String> expected = Arrays.asList("javac: option -Xmodule: can only be specified once",
-                                              "Usage: javac <options> <source files>",
-                                              "use --help for a list of possible options");
-
-        if (!expected.equals(log))
-            throw new Exception("expected output not found: " + log);
-    }
-
-    @Test
-    public void testWithModulePath(Path base) throws Exception {
-        Path modSrc = base.resolve("modSrc");
-        Path modules = base.resolve("modules");
-        new ModuleBuilder(tb, "m1")
-                .classes("package pkg1; public interface E { }")
-                .build(modSrc, modules);
-
-        Path src = base.resolve("src");
-        tb.writeJavaFiles(src, "package p; interface A extends pkg1.E { }");
-
-        new JavacTask(tb, Task.Mode.CMDLINE)
-                .options("--module-path", modules.toString(),
-                        "-Xmodule:m1")
-                .files(findJavaFiles(src))
-                .run()
-                .writeAll();
-
-        //checks module bounds still exist
-        new ModuleBuilder(tb, "m2")
-                .classes("package pkg2; public interface D { }")
-                .build(modSrc, modules);
-
-        Path src2 = base.resolve("src2");
-        tb.writeJavaFiles(src2, "package p; interface A extends pkg2.D { }");
-
-        List<String> log = new JavacTask(tb, Task.Mode.CMDLINE)
-                .options("-XDrawDiagnostics",
-                        "--module-path", modules.toString(),
-                        "-Xmodule:m1")
-                .files(findJavaFiles(src2))
-                .run(Task.Expect.FAIL)
-                .writeAll()
-                .getOutputLines(Task.OutputKind.DIRECT);
-
-        List<String> expected = Arrays.asList("A.java:1:32: compiler.err.package.not.visible: pkg2, (compiler.misc.not.def.access.does.not.read: m1, pkg2, m2)",
-                "1 error");
-
-        if (!expected.equals(log))
-            throw new Exception("expected output not found: " + log);
-    }
-
-    @Test
-    public void testWithUpgradeModulePath(Path base) throws Exception {
-        Path modSrc = base.resolve("modSrc");
-        Path modules = base.resolve("modules");
-        new ModuleBuilder(tb, "m1")
-                .classes("package pkg1; public interface E { }")
-                .build(modSrc, modules);
-
-        Path upgrSrc = base.resolve("upgradeSrc");
-        Path upgrade = base.resolve("upgrade");
-        new ModuleBuilder(tb, "m1")
-                .classes("package pkg1; public interface D { }")
-                .build(upgrSrc, upgrade);
-
-        Path src = base.resolve("src");
-        tb.writeJavaFiles(src, "package p; interface A extends pkg1.D { }");
-
-        new JavacTask(tb, Task.Mode.CMDLINE)
-                .options("--module-path", modules.toString(),
-                        "--upgrade-module-path", upgrade.toString(),
-                        "-Xmodule:m1")
-                .files(findJavaFiles(src))
-                .run()
-                .writeAll();
-    }
-
-    @Test
-    public void testUnnamedIsolation(Path base) throws Exception {
-        //note: avoiding use of java.base, as that gets special handling on some places:
-        Path sourcePath = base.resolve("source-path");
-        tb.writeJavaFiles(sourcePath, "package src; public class Src {}");
-
-        Path classPathSrc = base.resolve("class-path-src");
-        tb.writeJavaFiles(classPathSrc, "package cp; public class CP { }");
-        Path classPath = base.resolve("classPath");
-        tb.createDirectories(classPath);
-
-        String cpLog = new JavacTask(tb)
-                .outdir(classPath)
-                .files(findJavaFiles(classPathSrc))
-                .run()
-                .writeAll()
-                .getOutput(Task.OutputKind.DIRECT);
-
-        if (!cpLog.isEmpty())
-            throw new Exception("expected output not found: " + cpLog);
-
-        Path modulePathSrc = base.resolve("module-path-src");
-        tb.writeJavaFiles(modulePathSrc,
-                          "module m {}",
-                          "package m; public class M {}");
-        Path modulePath = base.resolve("modulePath");
-        tb.createDirectories(modulePath.resolve("m"));
-
-        String modLog = new JavacTask(tb)
-                .outdir(modulePath.resolve("m"))
-                .files(findJavaFiles(modulePathSrc))
-                .run()
-                .writeAll()
-                .getOutput(Task.OutputKind.DIRECT);
-
-        if (!modLog.isEmpty())
-            throw new Exception("expected output not found: " + modLog);
-
-        Path src = base.resolve("src");
-        tb.writeJavaFiles(src, "package m; public class Extra { }");
-        Path classes = base.resolve("classes");
-        tb.createDirectories(classes);
-
-        String log = new JavacTask(tb)
-                .options("-Xmodule:m",
-                         "--class-path", classPath.toString(),
-                         "--source-path", sourcePath.toString(),
-                         "--module-path", modulePath.toString(),
-                         "--processor-path", System.getProperty("test.classes"),
-                         "-XDaccessInternalAPI=true",
-                         "-processor", CheckModuleContentProcessing.class.getName())
-                .outdir(classes)
-                .files(findJavaFiles(sourcePath))
-                .run()
-                .writeAll()
-                .getOutput(Task.OutputKind.DIRECT);
-
-        if (!log.isEmpty())
-            throw new Exception("expected output not found: " + log);
-    }
-
-    @SupportedAnnotationTypes("*")
-    public static final class CheckModuleContentProcessing extends AbstractProcessor {
-
-        @Override
-        public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
-            Symtab syms = Symtab.instance(((JavacProcessingEnvironment) processingEnv).getContext());
-            Elements elements = processingEnv.getElementUtils();
-            ModuleElement unnamedModule = syms.unnamedModule;
-            ModuleElement mModule = elements.getModuleElement("m");
-
-            assertNonNull("mModule found", mModule);
-            assertNonNull("src.Src from m", elements.getTypeElement(mModule, "src.Src"));
-            assertNull("cp.CP not from m", elements.getTypeElement(mModule, "cp.CP"));
-            assertNull("src.Src not from unnamed", elements.getTypeElement(unnamedModule, "src.Src"));
-            assertNonNull("cp.CP from unnamed", elements.getTypeElement(unnamedModule, "cp.CP"));
-
-            return false;
-        }
-
-        @Override
-        public SourceVersion getSupportedSourceVersion() {
-            return SourceVersion.latest();
-        }
-
-        private static void assertNonNull(String msg, Object val) {
-            if (val == null) {
-                throw new AssertionError(msg);
-            }
-        }
-
-        private static void assertNull(String msg, Object val) {
-            if (val != null) {
-                throw new AssertionError(msg);
-            }
-        }
-    }
-
-}
--- a/langtools/test/tools/javac/processing/StopAfterError/StopAfterError.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/processing/StopAfterError/StopAfterError.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,7 +27,8 @@
  * @summary If an error is produced by an annotation processor, the code should not be Attred, \
  *          unless requested
  * @modules jdk.compiler
- * @compile StopAfterError.java
+ * @library /tools/javac/lib
+ * @build StopAfterError JavacTestingAbstractProcessor
  * @compile/fail/ref=StopAfterError.out -XDrawDiagnostics -processor StopAfterError StopAfterErrorAux.java
  * @compile/fail/ref=StopAfterError.out -XDshould-stop.ifError=PROCESS -XDrawDiagnostics -processor StopAfterError StopAfterErrorAux.java
  * @compile/fail/ref=StopAfterErrorContinue.out -XDshould-stop.ifError=ATTR -XDrawDiagnostics -processor StopAfterError StopAfterErrorAux.java
@@ -42,8 +43,7 @@
 import javax.lang.model.element.TypeElement;
 import javax.tools.Diagnostic.Kind;
 
-@SupportedAnnotationTypes("*")
-public class StopAfterError extends AbstractProcessor {
+public class StopAfterError extends JavacTestingAbstractProcessor {
 
     @Override
     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
@@ -52,10 +52,4 @@
         }
         return false;
     }
-
-    @Override
-    public SourceVersion getSupportedSourceVersion() {
-        return SourceVersion.latestSupported();
-    }
-
 }
--- a/langtools/test/tools/javac/processing/model/LocalClasses/LocalClassesModel.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/processing/model/LocalClasses/LocalClassesModel.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -26,7 +26,8 @@
  * @bug 8166700
  * @summary Check that local classes originating in static initializer can be loaded properly.
  * @modules jdk.compiler
- * @build LocalTest$1Local LocalTest$2Local LocalTest$3Local LocalTest$4Local LocalTest$5Local LocalTest
+ * @library /tools/javac/lib
+ * @build LocalTest$1Local LocalTest$2Local LocalTest$3Local LocalTest$4Local LocalTest$5Local LocalTest JavacTestingAbstractProcessor
  * @compile LocalClassesModel.java
  * @compile/process/ref=LocalClassesModel.out -processor LocalClassesModel LocalTest$1Local LocalTest$2Local LocalTest$3Local LocalTest$4Local LocalTest$5Local LocalTest
  */
@@ -42,8 +43,7 @@
 import javax.lang.model.element.VariableElement;
 import javax.lang.model.util.ElementFilter;
 
-@SupportedAnnotationTypes("*")
-public class LocalClassesModel extends AbstractProcessor {
+public class LocalClassesModel extends JavacTestingAbstractProcessor {
 
     @Override
     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
@@ -65,9 +65,4 @@
 
         return false;
     }
-
-    @Override
-    public SourceVersion getSupportedSourceVersion() {
-        return SourceVersion.latestSupported();
-    }
 }
--- a/langtools/test/tools/javac/processing/model/TestSourceVersion.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/processing/model/TestSourceVersion.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, 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 7025809 8028543 6415644
+ * @bug 7025809 8028543 6415644 8028544 8029942
  * @summary Test latest, latestSupported, underscore as keyword, etc.
  * @author  Joseph D. Darcy
  * @modules java.compiler
@@ -44,8 +44,8 @@
     }
 
     private static void testLatestSupported() {
-        if (SourceVersion.latest() != RELEASE_9 ||
-            SourceVersion.latestSupported() != RELEASE_9)
+        if (SourceVersion.latest() != RELEASE_10 ||
+            SourceVersion.latestSupported() != RELEASE_10)
             throw new RuntimeException("Unexpected release value(s) found:\n" +
                                        "latest:\t" + SourceVersion.latest() + "\n" +
                                        "latestSupported:\t" + SourceVersion.latestSupported());
--- a/langtools/test/tools/javac/processing/model/nestedTypeVars/NestedTypeVars.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/processing/model/nestedTypeVars/NestedTypeVars.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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
@@ -24,7 +24,8 @@
 /**
  * @test
  * @modules jdk.compiler
- * @build NestedTypeVars
+ * @library /tools/javac/lib
+ * @build NestedTypeVars JavacTestingAbstractProcessor
  * @compile/process/ref=NestedTypeVars.out -processor NestedTypeVars Test$1L1$L2$1L3$L4$L5 Test$1L1$CCheck Test$1L1 Test$1CCheck Test$CCheck Test
  */
 
@@ -44,8 +45,7 @@
 import javax.lang.model.type.TypeVariable;
 import javax.lang.model.util.ElementFilter;
 
-@SupportedAnnotationTypes("*")
-public class NestedTypeVars extends AbstractProcessor{
+public class NestedTypeVars extends JavacTestingAbstractProcessor {
 
     @Override
     public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
@@ -102,12 +102,6 @@
                 throw new IllegalStateException("Unexpected element: " + el + "(" + el.getKind() + ")");
         }
     }
-    @Override
-    public SourceVersion getSupportedSourceVersion() {
-        return SourceVersion.latestSupported();
-    }
-
-
 }
 
 class Test<T1, C> {
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/processing/model/util/elements/TestAllFoos.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,93 @@
+/*
+ * Copyright (c) 2017, 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 8173945
+ * @summary Test Elements.getAll{Type, Package, Module}Elements
+ * @library /tools/javac/lib
+ * @modules java.compiler
+ *          jdk.compiler
+ * @build   JavacTestingAbstractProcessor TestAllFoos
+ * @compile -processor TestAllFoos -proc:only --release 8 --source-path modules/m1/pkg  modules/m1/pkg/C.java
+ * @compile -processor TestAllFoos -proc:only --release 8 --source-path modules/m2/pkg  modules/m2/pkg/C.java
+ */
+// @compile -processor TestAllFoos -proc:only             --module-source-path  modules -m m1,m2
+
+import java.util.Set;
+import static java.util.Objects.*;
+import javax.annotation.processing.*;
+import static javax.lang.model.SourceVersion.*;
+import javax.lang.model.element.*;
+import javax.lang.model.util.*;
+
+/**
+ * Test basic workings of Elements.getAll{Type, Package, Module}Elements under
+ * pre- and post-modules.
+ */
+public class TestAllFoos extends JavacTestingAbstractProcessor {
+    public boolean process(Set<? extends TypeElement> annotations,
+                           RoundEnvironment roundEnv) {
+        if (!roundEnv.processingOver()) {
+            boolean expectModules =
+                (processingEnv.getSourceVersion().compareTo(RELEASE_9) >= 0);
+
+            testSetSize(eltUtils.getAllTypeElements("java.lang.String"), 1);
+            testSetSize(eltUtils.getAllTypeElements("example.com"), 0);
+
+            if (!expectModules) {
+                // Expect empty modules set, single package named "pkg" with one type "pkg.C".
+                testSetSize(eltUtils.getAllModuleElements(), 0);
+                testSetSize(eltUtils.getAllPackageElements("pkg"), 1);
+                testSetSize(eltUtils.getAllTypeElements("pkg.C"),  1);
+            } else {
+                Set<? extends ModuleElement> modules =
+                    requireNonNull(eltUtils.getAllModuleElements());
+
+                ModuleElement m1 = requireNonNull(eltUtils.getModuleElement("m1"));
+                ModuleElement m2 = requireNonNull(eltUtils.getModuleElement("m2"));
+
+                if (!modules.contains(m1) ||
+                    !modules.contains(m2) ||
+                    !modules.contains(requireNonNull(eltUtils.getModuleElement("java.base"))))
+                    throw new RuntimeException("Missing modules " + modules);
+
+                // Expect two packages named "pkg" and two types named "pkg.C".
+                testSetSize(eltUtils.getAllPackageElements("pkg"), 2);
+                testSetSize(eltUtils.getAllTypeElements("pkg.C"),  2);
+            }
+        }
+        return true;
+    }
+
+    /**
+     * Check the set argument against null and throw an exception if
+     * the set is not of the expected size.
+     */
+    private static <E> Set<E> testSetSize(Set<E> set, int expectedSize) {
+        requireNonNull(set);
+        if (set.size() != expectedSize)
+            throw new RuntimeException("Unexpected size of set " + set);
+        return set;
+    }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/processing/model/util/elements/modules/m1/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,4 @@
+/* /nodynamiccopyright/ */
+
+module m1 {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/processing/model/util/elements/modules/m1/pkg/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,11 @@
+/* /nodynamiccopyright/ */
+
+package pkg;
+
+/**
+ * A lovely description of class C of package pkg in module m1.
+ */
+public class C {
+    public C() {}
+    public static String foo() {return "foo";}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/processing/model/util/elements/modules/m1/pkg/package-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,6 @@
+/* /nodynamiccopyright/ */
+
+/**
+ * A lovely description of package pkg in module m1.
+ */
+package pkg;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/processing/model/util/elements/modules/m2/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,4 @@
+/* /nodynamiccopyright/ */
+
+module m2 {
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/processing/model/util/elements/modules/m2/pkg/C.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,11 @@
+/* /nodynamiccopyright/ */
+
+package pkg;
+
+/**
+ * A lovely description of class C of package pkg in module m2.
+ */
+public class C {
+    public C() {}
+    public static String bar() {return "bar";}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/processing/model/util/elements/modules/m2/pkg/package-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,6 @@
+/* /nodynamiccopyright/ */
+
+/**
+ * A lovely description of package pkg in module m2.
+ */
+package pkg;
--- a/langtools/test/tools/javac/processing/warnings/TestSourceVersionWarnings.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/processing/warnings/TestSourceVersionWarnings.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2017, 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
@@ -35,6 +35,7 @@
  * @compile/ref=gold_unsp_warn.out     -XDrawDiagnostics -processor TestSourceVersionWarnings -proc:only -ASourceVersion=RELEASE_6 -source 1.6 -Xlint:-options -Aunsupported HelloWorld.java
  * @compile/ref=gold_sv_none.out       -XDrawDiagnostics -processor TestSourceVersionWarnings -proc:only -ASourceVersion=RELEASE_7 -source 1.7 -Xlint:-options HelloWorld.java
  * @compile/ref=gold_sv_none.out       -XDrawDiagnostics -processor TestSourceVersionWarnings -proc:only -ASourceVersion=RELEASE_8 -source 1.8 -Xlint:-options HelloWorld.java
+ * @compile/ref=gold_sv_none.out       -XDrawDiagnostics -processor TestSourceVersionWarnings -proc:only -ASourceVersion=RELEASE_9 -source 1.9 -Xlint:-options HelloWorld.java
  */
 
 import java.util.Set;
--- a/langtools/test/tools/javac/profiles/ProfileOptionTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/profiles/ProfileOptionTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 2017, 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
@@ -148,6 +148,7 @@
                             error("unexpected exception from compiler: " + ise);
                         break;
                     case JDK1_9:
+                    case JDK1_10:
                         if (p == Profile.DEFAULT)
                             break;
                         if (ise == null)
--- a/langtools/test/tools/javac/redefineObject/Object1-test.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/redefineObject/Object1-test.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,6 +27,6 @@
  * @summary java.lang.Object can't be redefined without crashing javac
  * @author gafter
  *
- * @compile/module=java.base/fail/ref=Object1.out -XDrawDiagnostics Object1.java
+ * @compile/module=java.base/fail/ref=Object1.out -XDrawDiagnostics java/lang/Object1.java
  */
 
--- a/langtools/test/tools/javac/redefineObject/Object2-test.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/redefineObject/Object2-test.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2017, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -27,5 +27,5 @@
  * @summary java.lang.Object can't be redefined without crashing javac
  * @author gafter
  *
- * @compile/module=java.base/fail/ref=Object2.out -XDrawDiagnostics  Object2.java
+ * @compile/module=java.base/fail/ref=Object2.out -XDrawDiagnostics java/lang/Object2.java
  */
--- a/langtools/test/tools/javac/redefineObject/java.base/Object1.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,19 +0,0 @@
-/*
- * /nodynamiccopyright/
- * See ../Object1-test.java
- */
-
-package java.lang;
-class Object extends Throwable {
-    public final native Class getClass();
-    public native int hashCode();
-    public native boolean equals(Object obj);
-    protected native Object clone() throws CloneNotSupportedException;
-    public native String toString();
-    public final native void notify();
-    public final native void notifyAll();
-    public final native void wait(long timeout) throws InterruptedException;
-    public native final void wait(long timeout, int nanos) throws InterruptedException;
-    public native final void wait() throws InterruptedException;
-    protected void finalize() throws Throwable { }
-}
--- a/langtools/test/tools/javac/redefineObject/java.base/Object2.java	Thu Mar 16 16:34:35 2017 +0000
+++ /dev/null	Thu Jan 01 00:00:00 1970 +0000
@@ -1,19 +0,0 @@
-/*
- * /nodynamiccopyright/
- * See ../Object2-test.java
- */
-
-package java.lang;
-class Object implements Cloneable {
-    public final native Class getClass();
-    public native int hashCode();
-    public native boolean equals(Object obj);
-    public native Object clone() throws CloneNotSupportedException;
-    public native String toString();
-    public final native void notify();
-    public final native void notifyAll();
-    public final native void wait(long timeout) throws InterruptedException;
-    public native final void wait(long timeout, int nanos) throws InterruptedException;
-    public native final void wait() throws InterruptedException;
-    protected void finalize() throws Throwable { }
-}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/redefineObject/java.base/java/lang/Object1.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,19 @@
+/*
+ * /nodynamiccopyright/
+ * See ../Object1-test.java
+ */
+
+package java.lang;
+class Object extends Throwable {
+    public final native Class getClass();
+    public native int hashCode();
+    public native boolean equals(Object obj);
+    protected native Object clone() throws CloneNotSupportedException;
+    public native String toString();
+    public final native void notify();
+    public final native void notifyAll();
+    public final native void wait(long timeout) throws InterruptedException;
+    public native final void wait(long timeout, int nanos) throws InterruptedException;
+    public native final void wait() throws InterruptedException;
+    protected void finalize() throws Throwable { }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/javac/redefineObject/java.base/java/lang/Object2.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,19 @@
+/*
+ * /nodynamiccopyright/
+ * See ../Object2-test.java
+ */
+
+package java.lang;
+class Object implements Cloneable {
+    public final native Class getClass();
+    public native int hashCode();
+    public native boolean equals(Object obj);
+    public native Object clone() throws CloneNotSupportedException;
+    public native String toString();
+    public final native void notify();
+    public final native void notifyAll();
+    public final native void wait(long timeout) throws InterruptedException;
+    public native final void wait(long timeout, int nanos) throws InterruptedException;
+    public native final void wait() throws InterruptedException;
+    protected void finalize() throws Throwable { }
+}
--- a/langtools/test/tools/javac/synthesize/Main.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/synthesize/Main.java	Thu Mar 16 20:47:03 2017 +0000
@@ -92,12 +92,17 @@
         File empty = new File("empty");
         empty.mkdirs();
 
+        // files to compile are in a separate directory from test to avoid
+        // confusing jtreg
+        File src = new File(testSrc, "src");
+
         List<String> args = new ArrayList<String>();
         args.add("-classpath");
         args.add("empty");
 
         if (stdBootClassPath) {
-            args.add("-Xmodule:java.base");
+            args.add("--patch-module");
+            args.add("java.base=" + testSrc.getAbsolutePath());
         } else {
             args.add("--system");
             args.add("none");
@@ -108,9 +113,6 @@
         args.add("-d");
         args.add(".");
 
-        // files to compile are in a separate directory from test to avoid
-        // confusing jtreg
-        File src = new File(testSrc, "src");
         for (String f: files)
             args.add(new File(src, f).getPath());
 
--- a/langtools/test/tools/javac/tree/ArrayTypeToString.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/tree/ArrayTypeToString.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, 2017, 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
@@ -26,7 +26,8 @@
  * @bug 8068737
  * @summary Tests ArrayType.toString with type annotations present
  * @modules jdk.compiler/com.sun.tools.javac.code
- * @build ArrayTypeToString
+ * @library /tools/javac/lib
+ * @build ArrayTypeToString JavacTestingAbstractProcessor
  * @compile/ref=ArrayTypeToString.out -XDaccessInternalAPI -XDrawDiagnostics -processor ArrayTypeToString -proc:only ArrayTypeToString.java
  */
 
@@ -54,8 +55,7 @@
 }
 
 @SupportedAnnotationTypes("Foo")
-@SupportedSourceVersion(SourceVersion.RELEASE_9)
-public class ArrayTypeToString extends AbstractProcessor {
+public class ArrayTypeToString extends JavacTestingAbstractProcessor {
     @Foo(0) String @Foo(1)[] @Foo(2)[] @Foo(3)[] field;
 
     public boolean process(Set<? extends TypeElement> tes, RoundEnvironment renv) {
--- a/langtools/test/tools/javac/tree/JavacTreeScannerTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/tree/JavacTreeScannerTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -41,7 +41,7 @@
  *          jdk.compiler/com.sun.tools.javac.tree
  *          jdk.compiler/com.sun.tools.javac.util
  * @build AbstractTreeScannerTest JavacTreeScannerTest
- * @run main JavacTreeScannerTest -q -r .
+ * @run main/othervm JavacTreeScannerTest -q -r .
  */
 
 import java.io.*;
--- a/langtools/test/tools/javac/tree/SourceTreeScannerTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/tree/SourceTreeScannerTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -41,7 +41,7 @@
  *          jdk.compiler/com.sun.tools.javac.tree
  *          jdk.compiler/com.sun.tools.javac.util
  * @build AbstractTreeScannerTest SourceTreeScannerTest
- * @run main SourceTreeScannerTest -q -r .
+ * @run main/othervm SourceTreeScannerTest -q -r .
  */
 
 import java.io.*;
--- a/langtools/test/tools/javac/tree/TreePosTest.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/tree/TreePosTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -108,7 +108,7 @@
  *          jdk.compiler/com.sun.tools.javac.file
  *          jdk.compiler/com.sun.tools.javac.tree
  *          jdk.compiler/com.sun.tools.javac.util
- * @run main TreePosTest -q -r .
+ * @run main/othervm TreePosTest -q -r .
  */
 public class TreePosTest {
     /**
--- a/langtools/test/tools/javac/varargs/7043922/T7043922.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/varargs/7043922/T7043922.java	Thu Mar 16 20:47:03 2017 +0000
@@ -28,6 +28,7 @@
  * @modules jdk.compiler/com.sun.tools.javac.api
  *          jdk.compiler/com.sun.tools.javac.file
  *          jdk.compiler/com.sun.tools.javac.util
+ * @run main/othervm T7043922
  */
 
 import com.sun.source.util.JavacTask;
--- a/langtools/test/tools/javac/versions/Versions.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/javac/versions/Versions.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2014, 2017, 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 4981566 5028634 5094412 6304984 7025786 7025789 8001112 8028545 8000961 8030610
+ * @bug 4981566 5028634 5094412 6304984 7025786 7025789 8001112 8028545 8000961 8030610 8028546
  * @summary Check interpretation of -target and -source options
  * @modules java.compiler
  *          jdk.compiler
@@ -69,6 +69,7 @@
         check("53.0", "-source 1.7");
         check("53.0", "-source 1.8");
         check("53.0", "-source 1.9");
+        check("53.0", "-source 1.10");
 
         check_source_target("50.0", "6", "6");
         check_source_target("51.0", "6", "7");
@@ -80,6 +81,7 @@
         check_source_target("53.0", "7", "9");
         check_source_target("53.0", "8", "9");
         check_source_target("53.0", "9", "9");
+        check_source_target("53.0", "10", "10");
 
         checksrc16("-source 1.6");
         checksrc16("-source 6");
@@ -93,19 +95,26 @@
         checksrc18("-source 8");
         checksrc18("-source 1.8", "-target 1.8");
         checksrc18("-source 8", "-target 8");
-        checksrc19();
         checksrc19("-source 1.9");
         checksrc19("-source 9");
         checksrc19("-source 1.9", "-target 1.9");
         checksrc19("-source 9", "-target 9");
-        checksrc19("-target 1.9");
-        checksrc19("-target 9");
+
+        checksrc110();
+        checksrc110("-source 1.10");
+        checksrc110("-source 10");
+        checksrc110("-source 1.10", "-target 1.10");
+        checksrc110("-source 10", "-target 10");
+        checksrc110("-target 1.10");
+        checksrc110("-target 10");
 
         fail("-source 7", "-target 1.6", "Base.java");
         fail("-source 8", "-target 1.6", "Base.java");
         fail("-source 8", "-target 1.7", "Base.java");
         fail("-source 9", "-target 1.7", "Base.java");
         fail("-source 9", "-target 1.8", "Base.java");
+        fail("-source 10", "-target 1.7", "Base.java");
+        fail("-source 10", "-target 1.8", "Base.java");
 
         fail("-source 1.5", "-target 1.5", "Base.java");
         fail("-source 1.4", "-target 1.4", "Base.java");
@@ -202,6 +211,11 @@
         checksrc18(args);
     }
 
+    protected void checksrc110(String... args) {
+        printargs("checksrc110", args);
+        checksrc19(args);
+    }
+
     protected void pass(String... args) {
         printargs("pass", args);
 
--- a/langtools/test/tools/jdeprscan/tests/jdk/jdeprscan/TestRelease.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/jdeprscan/tests/jdk/jdeprscan/TestRelease.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2016, 2017, 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,7 @@
         assertTrue(invoke("7"));
         assertTrue(invoke("8"));
         assertTrue(invoke("9"));
+        assertTrue(invoke("10"));
     }
 
     @Test
--- a/langtools/test/tools/jdeps/jdkinternals/RemovedJDKInternals.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/langtools/test/tools/jdeps/jdkinternals/RemovedJDKInternals.java	Thu Mar 16 20:47:03 2017 +0000
@@ -63,7 +63,7 @@
         Path sunMiscSrc = Paths.get(TEST_SRC, "patches", JDK_UNSUPPORTED);
         Path patchDir = PATCHES_DIR.resolve(JDK_UNSUPPORTED);
         assertTrue(CompilerUtils.compile(sunMiscSrc, patchDir,
-                                         "-Xmodule:" + JDK_UNSUPPORTED));
+                                         "--patch-module", JDK_UNSUPPORTED + "=" + sunMiscSrc.toString()));
 
         // compile com.sun.image.codec.jpeg types
         Path codecSrc = Paths.get(TEST_SRC, "patches", "java.desktop");
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/langtools/test/tools/jdeps/modules/DotFileTest.java	Thu Mar 16 20:47:03 2017 +0000
@@ -0,0 +1,130 @@
+/*
+ * Copyright (c) 2017, 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 8173374
+ * @summary Tests module dot graph
+ * @modules java.desktop
+ *          java.sql
+ *          jdk.jdeps/com.sun.tools.jdeps
+ * @run testng DotFileTest
+ */
+
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Set;
+
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.spi.ToolProvider;
+import java.util.stream.Collectors;
+
+import org.testng.annotations.DataProvider;
+import org.testng.annotations.Test;
+
+import static org.testng.Assert.assertTrue;
+import static org.testng.Assert.assertEquals;
+
+public class DotFileTest {
+    private static final ToolProvider JDEPS = ToolProvider.findFirst("jdeps")
+        .orElseThrow(() -> new RuntimeException("jdeps not found"));
+
+    private static final Path DOTS_DIR = Paths.get("dots");
+    private static final Path SPEC_DIR = Paths.get("spec");
+
+    @DataProvider(name = "modules")
+    public Object[][] modules() {
+        return new Object[][]{
+            {"java.desktop", Set.of("java.datatransfer -> java.base",
+                                    "java.desktop -> java.datatransfer",
+                                    "java.desktop -> java.prefs",
+                                    "java.prefs -> java.xml",
+                                    "java.xml -> java.base" )
+            },
+            { "java.sql",    Set.of("java.logging -> java.base",
+                                    "java.sql -> java.logging",
+                                    "java.sql -> java.xml",
+                                    "java.xml -> java.base" )
+            }
+        };
+    }
+    @DataProvider(name = "specVersion")
+    public Object[][] specVersion() {
+        return new Object[][]{
+            {"java.desktop", Set.of("java.datatransfer -> java.base",
+                                    "java.desktop -> java.datatransfer",
+                                    "java.desktop -> java.xml",
+                                    "java.xml -> java.base")
+            },
+            { "java.sql",    Set.of("java.logging -> java.base",
+                                    "java.sql -> java.logging",
+                                    "java.sql -> java.xml",
+                                    "java.xml -> java.base" )
+            }
+        };
+    }
+
+    @Test(dataProvider = "modules")
+    public void test(String name, Set<String> edges) throws Exception {
+        String[] options = new String[] {
+            "-dotoutput", DOTS_DIR.toString(),
+            "-s", "-m", name
+        };
+        assertTrue(JDEPS.run(System.out, System.out, options) == 0);
+
+        Path path = DOTS_DIR.resolve(name + ".dot");
+        assertTrue(Files.exists(path));
+        Set<String> lines = Files.readAllLines(path).stream()
+                                 .filter(l -> l.contains(" -> "))
+                                 .map(this::split)
+                                 .collect(Collectors.toSet());
+        assertEquals(lines, edges);
+    }
+
+    @Test(dataProvider = "specVersion")
+    public void testAPIOnly(String name, Set<String> edges) throws Exception {
+        String[] options = new String[]{
+            "-dotoutput", SPEC_DIR.toString(),
+            "-s", "-apionly",
+            "-m", name
+        };
+        assertTrue(JDEPS.run(System.out, System.out, options) == 0);
+
+        Path path = SPEC_DIR.resolve(name + ".dot");
+        assertTrue(Files.exists(path));
+        Set<String> lines = Files.readAllLines(path).stream()
+                                 .filter(l -> l.contains(" -> "))
+                                 .map(this::split)
+                                 .collect(Collectors.toSet());
+        assertEquals(lines, edges);
+    }
+
+    static Pattern PATTERN = Pattern.compile(" *\"(\\S+)\" -> \"(\\S+)\" .*");
+    String split(String line) {
+        Matcher pm = PATTERN.matcher(line);
+        assertTrue(pm.find());
+        return String.format("%s -> %s", pm.group(1), pm.group(2));
+    }
+}
--- a/make/CompileJavaModules.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/make/CompileJavaModules.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -85,7 +85,7 @@
 
 ################################################################################
 
-java.compiler_ADD_JAVAC_FLAGS := -Xdoclint:all/protected,-reference '-Xdoclint/package:java.*,javax.*'
+java.compiler_ADD_JAVAC_FLAGS := -Xdoclint:all/protected '-Xdoclint/package:java.*,javax.*'
 
 ################################################################################
 
@@ -247,7 +247,7 @@
 
 ################################################################################
 
-java.management.rmi_ADD_JAVAC_FLAGS := -Xdoclint:all/protected,-reference '-Xdoclint/package:javax.*'
+java.management.rmi_ADD_JAVAC_FLAGS := -Xdoclint:all/protected '-Xdoclint/package:javax.*'
 
 ################################################################################
 
--- a/make/GenerateLinkOptData.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/make/GenerateLinkOptData.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -49,7 +49,7 @@
 
 LINK_OPT_DIR := $(SUPPORT_OUTPUTDIR)/link_opt
 CLASSLIST_FILE := $(LINK_OPT_DIR)/classlist
-JLI_TRACE_FILE := $(LINK_OPT_DIR)/jli_trace.out
+JLI_TRACE_FILE := $(LINK_OPT_DIR)/default_jli_trace.txt
 
 # If an external buildjdk has been supplied, we don't build a separate interim
 # image, so just use the external build jdk instead.
@@ -83,6 +83,14 @@
 
 TARGETS += $(COPY_CLASSLIST)
 
+# Copy the default_jli_trace.txt file into jdk.jlink
+$(eval $(call SetupCopyFiles, COPY_JLI_TRACE, \
+    FILES := $(JLI_TRACE_FILE), \
+    DEST := $(JDK_OUTPUTDIR)/modules/jdk.jlink/jdk/tools/jlink/internal/plugins, \
+))
+
+TARGETS += $(COPY_JLI_TRACE)
+
 ################################################################################
 
 all: $(TARGETS)
--- a/make/Images.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/make/Images.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -105,7 +105,7 @@
 JLINK_JLI_CLASSES :=
 ifeq ($(ENABLE_GENERATE_CLASSLIST), true)
   JLINK_ORDER_RESOURCES += @$(SUPPORT_OUTPUTDIR)/link_opt/classlist
-  JLINK_JLI_CLASSES := --generate-jli-classes=@$(SUPPORT_OUTPUTDIR)/link_opt/jli_trace.out
+  JLINK_JLI_CLASSES := --generate-jli-classes=@$(SUPPORT_OUTPUTDIR)/link_opt/default_jli_trace.txt
 endif
 JLINK_ORDER_RESOURCES += \
     /java.base/java/** \
--- a/make/Init.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/make/Init.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -66,7 +66,7 @@
   ifeq ($(CALLED_SPEC_TARGETS), )
     ONLY_GLOBAL_TARGETS := true
   endif
-  ifneq ($(findstring qp, $(MAKEFLAGS)),)
+  ifeq ($(findstring p, $(MAKEFLAGS))$(findstring q, $(MAKEFLAGS)), pq)
     ONLY_GLOBAL_TARGETS := true
   endif
 
--- a/make/Javadoc.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/make/Javadoc.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -314,7 +314,7 @@
   $1_INDEX_FILE := $$(JAVADOC_OUTPUTDIR)/$$($1_OUTPUT_DIRNAME)/index.html
 
   # Rule for actually running javadoc
-  $$($1_INDEX_FILE): $(BUILD_TOOLS_JDK) $$($1_VARDEPS_FILE) $$($1_PACKAGE_DEPS) $$($1_DEPS)
+  $$($1_INDEX_FILE): $$(BUILD_TOOLS_JDK) $$($1_VARDEPS_FILE) $$($1_PACKAGE_DEPS) $$($1_DEPS)
 	$$(call LogWarn, Generating Javadoc from $$(words $$($1_PACKAGES)) package(s) for $$($1_OUTPUT_DIRNAME))
 	$$(call MakeDir, $$(@D))
         ifneq ($$($1_PACKAGES_FILE), )
@@ -743,7 +743,7 @@
 
 ################################################################################
 
-docs-javadoc: $(BUILD_TOOLS_JDK) $(TARGETS)
+docs-javadoc: $(TARGETS)
 
 docs-copy: $(COPY_TARGETS)
 
--- a/make/Main.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/make/Main.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -654,8 +654,7 @@
   # When creating a BUILDJDK, we don't need to add hashes to java.base, thus
   # we don't need to depend on all other jmods
   ifneq ($(CREATING_BUILDJDK), true)
-    java.base-jmod: jrtfs-jar $(filter-out java.base-jmod \
-        $(addsuffix -jmod, $(call FindAllUpgradeableModules)), $(JMOD_TARGETS))
+    java.base-jmod: jrtfs-jar $(filter-out java.base-jmod, $(JMOD_TARGETS))
   endif
 
   # Building java.base-jmod requires all of hotspot to be built.
@@ -728,7 +727,7 @@
     generate-link-opt-data: buildtools-jdk
 
     # The generated classlist needs to go into java.base-jmod.
-    java.base-jmod jdk-image jre-image: generate-link-opt-data
+    java.base-jmod jdk.jlink-jmod jdk-image jre-image: generate-link-opt-data
   endif
 
   release-file: create-source-revision-tracker
--- a/make/common/Modules.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/make/common/Modules.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -107,7 +107,6 @@
     jdk.charsets \
     jdk.crypto.ec \
     jdk.crypto.cryptoki \
-    jdk.desktop \
     jdk.dynalink \
     jdk.jsobject \
     jdk.localedata \
@@ -115,6 +114,7 @@
     jdk.scripting.nashorn \
     jdk.security.auth \
     jdk.security.jgss \
+    jdk.vm.compiler \
     jdk.xml.dom \
     jdk.zipfs \
     #
--- a/make/common/SetupJavaCompilers.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/make/common/SetupJavaCompilers.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -69,7 +69,7 @@
 $(eval $(call SetupJavaCompiler,GENERATE_JDKBYTECODE, \
     JVM := $(JAVA_JAVAC), \
     JAVAC := $(NEW_JAVAC), \
-    FLAGS := -source 9 -target 9 \
+    FLAGS := -source 10 -target 10 \
         -encoding ascii -XDignore.symbol.file=true $(JAVAC_WARNINGS), \
     SERVER_DIR := $(SJAVAC_SERVER_DIR), \
     SERVER_JVM := $(SJAVAC_SERVER_JAVA)))
@@ -79,7 +79,7 @@
 $(eval $(call SetupJavaCompiler,GENERATE_JDKBYTECODE_NOWARNINGS, \
     JVM := $(JAVA_JAVAC), \
     JAVAC := $(NEW_JAVAC), \
-    FLAGS := -source 9 -target 9 \
+    FLAGS := -source 10 -target 10 \
         -encoding ascii -XDignore.symbol.file=true $(DISABLE_WARNINGS), \
     SERVER_DIR := $(SJAVAC_SERVER_DIR), \
     SERVER_JVM := $(SJAVAC_SERVER_JAVA)))
--- a/nashorn/.hgtags	Thu Mar 16 16:34:35 2017 +0000
+++ b/nashorn/.hgtags	Thu Mar 16 20:47:03 2017 +0000
@@ -387,5 +387,9 @@
 2a0437036a64853334e538044eb68d2df70075fa jdk-9+151
 ddc52e72757086a75a54371e8e7f56a3f89f1e55 jdk-9+152
 19aaaf2d02b7d6986538cd9a8c46901ecb50eebf jdk-9+153
+a84b49cfee63716975535abae2865ffef4dd6474 jdk-10+0
 a84b49cfee63716975535abae2865ffef4dd6474 jdk-9+154
 f9bb37a817b3cd3b758a60f3c68258a6554eb382 jdk-9+155
+d577398d31111be4bdaa08008247cf4242eaea94 jdk-9+156
+f6070efba6af0dc003e24ca736426c93e99ee96a jdk-9+157
+13ae2480a4c395026b3aa1739e0f9895dc8b25d9 jdk-9+158
--- a/nashorn/.jcheck/conf	Thu Mar 16 16:34:35 2017 +0000
+++ b/nashorn/.jcheck/conf	Thu Mar 16 20:47:03 2017 +0000
@@ -1,1 +1,1 @@
-project=jdk9
+project=jdk10
--- a/nashorn/src/jdk.dynalink/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/nashorn/src/jdk.dynalink/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -216,6 +216,8 @@
  * language runtime B gets passed to code from language runtime A, the linker
  * from B will get a chance to link the call site in A when it encounters the
  * object from B.
+ *
+ * @since 9
  */
 module jdk.dynalink {
     requires java.logging;
--- a/nashorn/src/jdk.scripting.nashorn.shell/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/nashorn/src/jdk.scripting.nashorn.shell/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -25,6 +25,8 @@
 
 /**
  * Nashorn shell module
+ *
+ * @since 9
  */
 module jdk.scripting.nashorn.shell {
     requires java.desktop;
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Context.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/Context.java	Thu Mar 16 20:47:03 2017 +0000
@@ -1372,7 +1372,7 @@
         };
 
         final Configuration cf = parent.configuration()
-                .resolveRequires(finder, ModuleFinder.of(), Set.of(mn));
+                .resolve(finder, ModuleFinder.of(), Set.of(mn));
 
         final PrivilegedAction<Layer> pa = () -> parent.defineModules(cf, name -> loader);
         final Layer layer = AccessController.doPrivileged(pa, GET_LOADER_ACC_CTXT);
@@ -1798,7 +1798,7 @@
 
         final Layer boot = Layer.boot();
         final Configuration conf = boot.configuration().
-            resolveRequires(mf, ModuleFinder.of(), rootMods);
+            resolve(mf, ModuleFinder.of(), rootMods);
         final String firstMod = rootMods.iterator().next();
         return boot.defineModulesWithOneLoader(conf, cl).findLoader(firstMod);
     }
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptLoader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/ScriptLoader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -26,9 +26,11 @@
 package jdk.nashorn.internal.runtime;
 
 import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleDescriptor.Modifier;
 import java.lang.reflect.Module;
 import java.security.CodeSource;
 import java.util.Objects;
+import java.util.Set;
 
 /**
  * Responsible for loading script generated classes.
@@ -69,12 +71,11 @@
     private Module createModule(final String moduleName) {
         final Module structMod = context.getStructLoader().getModule();
         final ModuleDescriptor.Builder builder =
-            ModuleDescriptor.module(moduleName)
-                    .requires("java.base")
+            ModuleDescriptor.newModule(moduleName, Set.of(Modifier.SYNTHETIC))
                     .requires("java.logging")
                     .requires(NASHORN_MODULE.getName())
                     .requires(structMod.getName())
-                    .contains(SCRIPTS_PKG);
+                    .packages(Set.of(SCRIPTS_PKG));
 
         if (Context.javaSqlFound) {
             builder.requires("java.sql");
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/StructureLoader.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/jdk/nashorn/internal/runtime/StructureLoader.java	Thu Mar 16 20:47:03 2017 +0000
@@ -31,8 +31,10 @@
 import static jdk.nashorn.internal.codegen.CompilerConstants.JS_OBJECT_SINGLE_FIELD_PREFIX;
 
 import java.lang.module.ModuleDescriptor;
+import java.lang.module.ModuleDescriptor.Modifier;
 import java.lang.reflect.Module;
 import java.security.ProtectionDomain;
+import java.util.Set;
 import jdk.nashorn.internal.codegen.ObjectClassGenerator;
 
 /**
@@ -62,12 +64,11 @@
     }
 
     private Module createModule(final String moduleName) {
-        final ModuleDescriptor descriptor
-                = ModuleDescriptor.module(moduleName)
-                    .requires("java.base")
-                    .requires(NASHORN_MODULE.getName())
-                    .contains(SCRIPTS_PKG)
-                    .build();
+        final ModuleDescriptor descriptor =
+            ModuleDescriptor.newModule(moduleName, Set.of(Modifier.SYNTHETIC))
+                            .requires(NASHORN_MODULE.getName())
+                            .packages(Set.of(SCRIPTS_PKG))
+                            .build();
 
         final Module mod = Context.createModuleTrusted(descriptor, this);
         loadModuleManipulator();
--- a/nashorn/src/jdk.scripting.nashorn/share/classes/module-info.java	Thu Mar 16 16:34:35 2017 +0000
+++ b/nashorn/src/jdk.scripting.nashorn/share/classes/module-info.java	Thu Mar 16 20:47:03 2017 +0000
@@ -89,6 +89,8 @@
 <h2>Other non-standard built-in objects</h2>
 In addition to {@code Java}, Nashorn also exposes some other non-standard built-in objects:
 {@code JSAdapter}, {@code JavaImporter}, {@code Packages}
+
+@since 9
  */
 module jdk.scripting.nashorn {
     requires java.logging;
--- a/test/TestCommon.gmk	Thu Mar 16 16:34:35 2017 +0000
+++ b/test/TestCommon.gmk	Thu Mar 16 20:47:03 2017 +0000
@@ -370,7 +370,7 @@
 # Give tests access to JT_JAVA, see JDK-8141609
 JTREG_BASIC_OPTIONS += -e:JDK8_HOME=${JT_JAVA}
 # Set other vm and test options
-JTREG_TEST_OPTIONS = $(JAVA_ARGS:%=-javaoptions:%) $(JAVA_OPTIONS:%=-vmoption:%) $(JAVA_VM_ARGS:%=-vmoption:%)
+JTREG_TEST_OPTIONS += $(JAVA_ARGS:%=-javaoptions:%) $(JAVA_OPTIONS:%=-vmoption:%) $(JAVA_VM_ARGS:%=-vmoption:%)
 
 ifeq ($(IGNORE_MARKED_TESTS), true)
   # Option to tell jtreg to not run tests marked with "ignore"