Mirror code for jdk8u111-b14
diff --git a/ASSEMBLY_EXCEPTION b/ASSEMBLY_EXCEPTION
index 065b8d9..8b7ac1d 100644
--- a/ASSEMBLY_EXCEPTION
+++ b/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
-openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
-General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Sun at openjdk.java.net and
+openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
+GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Oracle gives you permission to link this
-    OpenJDK Code with certain code licensed by Oracle as indicated at
+    As a special exception, Sun gives you permission to link this
+    OpenJDK Code with certain code licensed by Sun as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Oracle.
+    governed by the licenses under which they were offered by Sun.
 
-As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
-to build an executable that includes those portions of necessary code that
-Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
-with the Classpath exception).  If you modify or add to the OpenJDK code,
-that new GPL2 code may still be combined with Designated Exception Modules
-if the new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
+build an executable that includes those portions of necessary code that Sun
+could not provide under GPL2 (or that Sun has provided under GPL2 with the
+Classpath exception).  If you modify or add to the OpenJDK code, that new
+GPL2 code may still be combined with Designated Exception Modules if the
+new code is made subject to this exception by its copyright holder.
diff --git a/LICENSE b/LICENSE
index 8b400c7..b40a0f4 100644
--- a/LICENSE
+++ b/LICENSE
@@ -3,7 +3,7 @@
 Version 2, June 1991
 
 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Everyone is permitted to copy and distribute verbatim copies of this license
 document, but changing it is not allowed.
@@ -287,8 +287,8 @@
     more details.
 
     You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+    with this program; if not, write to the Free Software Foundation, Inc., 59
+    Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Also add information on how to contact you by electronic and paper mail.
 
diff --git a/common/autoconf/generated-configure.sh b/common/autoconf/generated-configure.sh
index c9d7429..d3d0ccd 100644
--- a/common/autoconf/generated-configure.sh
+++ b/common/autoconf/generated-configure.sh
@@ -679,9 +679,6 @@
 CFLAGS_JDKLIB
 MACOSX_VERSION_MIN
 PACKAGE_PATH
-NO_LIFETIME_DSE_CFLAG
-NO_DELETE_NULL_POINTER_CHECKS_CFLAG
-CXXSTD_CXXFLAG
 LEGACY_EXTRA_LDFLAGS
 LEGACY_EXTRA_CXXFLAGS
 LEGACY_EXTRA_CFLAGS
@@ -746,8 +743,6 @@
 ac_ct_OBJC
 OBJCFLAGS
 OBJC
-CXX_VERSION
-CC_VERSION
 ac_ct_CXX
 CXXFLAGS
 CXX
@@ -3677,7 +3672,7 @@
 
 
 #
-# Copyright (c) 2011, 2015, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 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
@@ -3800,19 +3795,6 @@
 # questions.
 #
 
-# Prepare the system so that TOOLCHAIN_CHECK_COMPILER_VERSION can be called.
-# Must have CC_VERSION_NUMBER and CXX_VERSION_NUMBER.
-
-
-# Check if the configured compiler (C and C++) is of a specific version or
-# newer. TOOLCHAIN_PREPARE_FOR_VERSION_COMPARISONS must have been called before.
-#
-# Arguments:
-#   $1:   The version string to check against the found version
-#   $2:   block to run if the compiler is at least this version (>=)
-#   $3:   block to run if the compiler is older than this version (<)
-
-
 # $1 = compiler to test (CC or CXX)
 # $2 = human readable name of compiler (C or C++)
 
@@ -3836,22 +3818,10 @@
 
 
 
-# TOOLCHAIN_C_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
-#                                      [RUN-IF-FALSE])
-# ------------------------------------------------------------
-# Check that the C compiler supports an argument
-
-
-# TOOLCHAIN_CXX_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
-#                                        [RUN-IF-FALSE])
-# ------------------------------------------------------------
-# Check that the C++ compiler supports an argument
-
-
 # TOOLCHAIN_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
-#                                    [RUN-IF-FALSE])
+#                                   [RUN-IF-FALSE])
 # ------------------------------------------------------------
-# Check that the C and C++ compilers support an argument
+# Check that the c and c++ compilers support an argument
 
 
 
@@ -3859,8 +3829,6 @@
 # Setup the JTREG paths
 
 
-
-
 #
 # Copyright (c) 2011, 2012, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
@@ -3912,7 +3880,7 @@
 #CUSTOM_AUTOCONF_INCLUDE
 
 # Do not change or remove the following line, it is needed for consistency checks:
-DATE_WHEN_GENERATED=1468207795
+DATE_WHEN_GENERATED=1449096260
 
 ###############################################################################
 #
@@ -20400,8 +20368,7 @@
 
     # First line typically looks something like:
     # gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
-    COMPILER_VERSION=`$ECHO $COMPILER_VERSION_TEST | \
-        $SED -e 's/^.* \([1-9]\.[0-9.]*\)[^0-9.].*$/\1/'`
+    COMPILER_VERSION=`$ECHO $COMPILER_VERSION_TEST | $SED -n "s/^.* \([1-9][0-9.]*\)/\1/p"`
     COMPILER_VENDOR=`$ECHO $COMPILER_VERSION_TEST | $SED -n "s/^\(.*\) [1-9][0-9.]*/\1/p"`
   fi
   # This sets CC_VERSION or CXX_VERSION. (This comment is a grep marker)
@@ -22002,8 +21969,7 @@
 
     # First line typically looks something like:
     # gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
-    COMPILER_VERSION=`$ECHO $COMPILER_VERSION_TEST | \
-        $SED -e 's/^.* \([1-9]\.[0-9.]*\)[^0-9.].*$/\1/'`
+    COMPILER_VERSION=`$ECHO $COMPILER_VERSION_TEST | $SED -n "s/^.* \([1-9][0-9.]*\)/\1/p"`
     COMPILER_VENDOR=`$ECHO $COMPILER_VERSION_TEST | $SED -n "s/^\(.*\) [1-9][0-9.]*/\1/p"`
   fi
   # This sets CC_VERSION or CXX_VERSION. (This comment is a grep marker)
@@ -22274,32 +22240,6 @@
 ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
 
 
-  # This is the compiler version number on the form X.Y[.Z]
-
-
-
-
-  if test "x$CC_VERSION" != "x$CXX_VERSION"; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: C and C++ compiler has different version numbers, $CC_VERSION vs $CXX_VERSION." >&5
-$as_echo "$as_me: WARNING: C and C++ compiler has different version numbers, $CC_VERSION vs $CXX_VERSION." >&2;}
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: This typically indicates a broken setup, and is not supported" >&5
-$as_echo "$as_me: WARNING: This typically indicates a broken setup, and is not supported" >&2;}
-  fi
-
-  # We only check CC_VERSION since we assume CXX_VERSION is equal.
-  if  [[ "$CC_VERSION" =~ (.*\.){3} ]] ; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: C compiler version number has more than three parts (X.Y.Z): $CC_VERSION. Comparisons might be wrong." >&5
-$as_echo "$as_me: WARNING: C compiler version number has more than three parts (X.Y.Z): $CC_VERSION. Comparisons might be wrong." >&2;}
-  fi
-
-  if  [[  "$CC_VERSION" =~ [0-9]{6} ]] ; then
-    { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: C compiler version number has a part larger than 99999: $CC_VERSION. Comparisons might be wrong." >&5
-$as_echo "$as_me: WARNING: C compiler version number has a part larger than 99999: $CC_VERSION. Comparisons might be wrong." >&2;}
-  fi
-
-  COMPARABLE_ACTUAL_VERSION=`$AWK -F. '{ printf("%05d%05d%05d\n", $1, $2, $3) }' <<< "$CC_VERSION"`
-
-
   ### Locate other tools
 
   if test "x$OPENJDK_TARGET_OS" = xmacosx; then
@@ -24891,8 +24831,7 @@
 
 
       COMPILER_TYPE=CL
-      # silence copyright notice and other headers.
-      COMMON_CCXXFLAGS="$COMMON_CCXXFLAGS -nologo"
+      CCXXFLAGS="$CCXXFLAGS -nologo"
 
 fi
 
@@ -29725,57 +29664,12 @@
   #
   # Now setup the CFLAGS and LDFLAGS for the JDK build.
   # Later we will also have CFLAGS and LDFLAGS for the hotspot subrepo build.
-  #    CFLAGS_JDK    - C Compiler flags
-  #    CXXFLAGS_JDK  - C++ Compiler flags
-  #    COMMON_CCXXFLAGS_JDK - common to C and C++
   #
   case $COMPILER_NAME in
     gcc )
-      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -W -Wall -Wno-unused -Wno-parentheses \
+      CCXXFLAGS_JDK="$CCXXFLAGS $CCXXFLAGS_JDK -W -Wall -Wno-unused -Wno-parentheses \
       -pipe \
       -D_GNU_SOURCE -D_REENTRANT -D_LARGEFILE64_SOURCE"
-      CXXSTD_CXXFLAG="-std=gnu++98"
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C++ compiler supports \"$CXXSTD_CXXFLAG $CFLAGS_WARNINGS_ARE_ERRORS\"" >&5
-$as_echo_n "checking if the C++ compiler supports \"$CXXSTD_CXXFLAG $CFLAGS_WARNINGS_ARE_ERRORS\"... " >&6; }
-  supports=yes
-
-  saved_cxxflags="$CXXFLAGS"
-  CXXFLAGS="$CXXFLAG $CXXSTD_CXXFLAG $CFLAGS_WARNINGS_ARE_ERRORS"
-  ac_ext=cpp
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
-
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-int i;
-_ACEOF
-if ac_fn_cxx_try_compile "$LINENO"; then :
-
-else
-  supports=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  ac_ext=cpp
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
-
-  CXXFLAGS="$saved_cxxflags"
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
-$as_echo "$supports" >&6; }
-  if test "x$supports" = "xyes" ; then
-    :
-  else
-    CXXSTD_CXXFLAG=""
-  fi
-
-      CXXFLAGS_JDK="${CXXFLAGS_JDK} ${CXXSTD_CXXFLAG}"
-
       case $OPENJDK_TARGET_CPU_ARCH in
         arm )
           # on arm we don't prevent gcc to omit frame pointer but do prevent strict aliasing
@@ -29785,234 +29679,16 @@
           # on ppc we don't prevent gcc to omit frame pointer nor strict-aliasing
           ;;
         * )
-          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -fno-omit-frame-pointer"
+          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -fno-omit-frame-pointer"
           CFLAGS_JDK="${CFLAGS_JDK} -fno-strict-aliasing"
           ;;
       esac
-
-  REFERENCE_VERSION=6
-
-  if  [[ "$REFERENCE_VERSION" =~ (.*\.){3} ]] ; then
-    as_fn_error $? "Internal error: Cannot compare to $REFERENCE_VERSION, only three parts (X.Y.Z) is supported" "$LINENO" 5
-  fi
-
-  if  [[ "$REFERENCE_VERSION" =~ [0-9]{6} ]] ; then
-    as_fn_error $? "Internal error: Cannot compare to $REFERENCE_VERSION, only parts < 99999 is supported" "$LINENO" 5
-  fi
-
-  # Version comparison method inspired by http://stackoverflow.com/a/24067243
-  COMPARABLE_REFERENCE_VERSION=`$AWK -F. '{ printf("%05d%05d%05d\n", $1, $2, $3) }' <<< "$REFERENCE_VERSION"`
-
-  if test $COMPARABLE_ACTUAL_VERSION -ge $COMPARABLE_REFERENCE_VERSION ; then
-
-  # These flags are required for GCC 6 builds as undefined behaviour in OpenJDK code
-  # runs afoul of the more aggressive versions of these optimisations.
-  # Notably, value range propagation now assumes that the this pointer of C++
-  # member functions is non-null.
-  NO_DELETE_NULL_POINTER_CHECKS_CFLAG="-fno-delete-null-pointer-checks"
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C compiler supports \"$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror\"" >&5
-$as_echo_n "checking if the C compiler supports \"$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror\"... " >&6; }
-  supports=yes
-
-  saved_cflags="$CFLAGS"
-  CFLAGS="$CFLAGS $NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror"
-  ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-
-cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-int i;
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-else
-  supports=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  ac_ext=cpp
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
-
-  CFLAGS="$saved_cflags"
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
-$as_echo "$supports" >&6; }
-  if test "x$supports" = "xyes" ; then
-    C_COMP_SUPPORTS="yes"
-  else
-    C_COMP_SUPPORTS="no"
-  fi
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C++ compiler supports \"$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror\"" >&5
-$as_echo_n "checking if the C++ compiler supports \"$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror\"... " >&6; }
-  supports=yes
-
-  saved_cxxflags="$CXXFLAGS"
-  CXXFLAGS="$CXXFLAG $NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror"
-  ac_ext=cpp
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
-
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-int i;
-_ACEOF
-if ac_fn_cxx_try_compile "$LINENO"; then :
-
-else
-  supports=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  ac_ext=cpp
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
-
-  CXXFLAGS="$saved_cxxflags"
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
-$as_echo "$supports" >&6; }
-  if test "x$supports" = "xyes" ; then
-    CXX_COMP_SUPPORTS="yes"
-  else
-    CXX_COMP_SUPPORTS="no"
-  fi
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if both compilers support \"$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror\"" >&5
-$as_echo_n "checking if both compilers support \"$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror\"... " >&6; }
-  supports=no
-  if test "x$C_COMP_SUPPORTS" = "xyes" -a "x$CXX_COMP_SUPPORTS" = "xyes"; then supports=yes; fi
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
-$as_echo "$supports" >&6; }
-  if test "x$supports" = "xyes" ; then
-    :
-  else
-    NO_DELETE_NULL_POINTER_CHECKS_CFLAG=""
-  fi
-
-
-  NO_LIFETIME_DSE_CFLAG="-fno-lifetime-dse"
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C compiler supports \"$NO_LIFETIME_DSE_CFLAG -Werror\"" >&5
-$as_echo_n "checking if the C compiler supports \"$NO_LIFETIME_DSE_CFLAG -Werror\"... " >&6; }
-  supports=yes
-
-  saved_cflags="$CFLAGS"
-  CFLAGS="$CFLAGS $NO_LIFETIME_DSE_CFLAG -Werror"
-  ac_ext=c
-ac_cpp='$CPP $CPPFLAGS'
-ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_c_compiler_gnu
-
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-int i;
-_ACEOF
-if ac_fn_c_try_compile "$LINENO"; then :
-
-else
-  supports=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  ac_ext=cpp
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
-
-  CFLAGS="$saved_cflags"
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
-$as_echo "$supports" >&6; }
-  if test "x$supports" = "xyes" ; then
-    C_COMP_SUPPORTS="yes"
-  else
-    C_COMP_SUPPORTS="no"
-  fi
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C++ compiler supports \"$NO_LIFETIME_DSE_CFLAG -Werror\"" >&5
-$as_echo_n "checking if the C++ compiler supports \"$NO_LIFETIME_DSE_CFLAG -Werror\"... " >&6; }
-  supports=yes
-
-  saved_cxxflags="$CXXFLAGS"
-  CXXFLAGS="$CXXFLAG $NO_LIFETIME_DSE_CFLAG -Werror"
-  ac_ext=cpp
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
-
-  cat confdefs.h - <<_ACEOF >conftest.$ac_ext
-/* end confdefs.h.  */
-int i;
-_ACEOF
-if ac_fn_cxx_try_compile "$LINENO"; then :
-
-else
-  supports=no
-fi
-rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext
-  ac_ext=cpp
-ac_cpp='$CXXCPP $CPPFLAGS'
-ac_compile='$CXX -c $CXXFLAGS $CPPFLAGS conftest.$ac_ext >&5'
-ac_link='$CXX -o conftest$ac_exeext $CXXFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5'
-ac_compiler_gnu=$ac_cv_cxx_compiler_gnu
-
-  CXXFLAGS="$saved_cxxflags"
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
-$as_echo "$supports" >&6; }
-  if test "x$supports" = "xyes" ; then
-    CXX_COMP_SUPPORTS="yes"
-  else
-    CXX_COMP_SUPPORTS="no"
-  fi
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if both compilers support \"$NO_LIFETIME_DSE_CFLAG -Werror\"" >&5
-$as_echo_n "checking if both compilers support \"$NO_LIFETIME_DSE_CFLAG -Werror\"... " >&6; }
-  supports=no
-  if test "x$C_COMP_SUPPORTS" = "xyes" -a "x$CXX_COMP_SUPPORTS" = "xyes"; then supports=yes; fi
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
-$as_echo "$supports" >&6; }
-  if test "x$supports" = "xyes" ; then
-    :
-  else
-    NO_LIFETIME_DSE_CFLAG=""
-  fi
-
-  CFLAGS_JDK="${CFLAGS_JDK} ${NO_DELETE_NULL_POINTER_CHECKS_CFLAG} ${NO_LIFETIME_DSE_CFLAG}"
-
-
-
-  else
-    :
-  fi
-
       ;;
     ossc )
-      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -DTRACING -DMACRO_MEMSYS_OPS -DBREAKPTS"
+      CCXXFLAGS_JDK="$CCXXFLAGS $CCXXFLAGS_JDK -DTRACING -DMACRO_MEMSYS_OPS -DBREAKPTS"
       case $OPENJDK_TARGET_CPU_ARCH in
         x86 )
-          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DcpuIntel -Di586 -D$OPENJDK_TARGET_CPU_LEGACY_LIB"
+          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DcpuIntel -Di586 -D$OPENJDK_TARGET_CPU_LEGACY_LIB"
           CFLAGS_JDK="$CFLAGS_JDK -erroff=E_BAD_PRAGMA_PACK_VALUE"
           ;;
       esac
@@ -30031,16 +29707,16 @@
       LDFLAGS_CXX_JDK="$LDFLAGS_CXX_JDK"
       ;;
     cl )
-      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -Zi -MD -Zc:wchar_t- -W3 -wd4800 \
+      CCXXFLAGS_JDK="$CCXXFLAGS $CCXXFLAGS_JDK -Zi -MD -Zc:wchar_t- -W3 -wd4800 \
       -D_STATIC_CPPLIB -D_DISABLE_DEPRECATE_STATIC_CPPLIB -DWIN32_LEAN_AND_MEAN \
       -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE \
       -DWIN32 -DIAL"
       case $OPENJDK_TARGET_CPU in
         x86 )
-          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_X86_ -Dx86"
+          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_X86_ -Dx86"
           ;;
         x86_64 )
-          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_AMD64_ -Damd64"
+          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_AMD64_ -Damd64"
           ;;
       esac
       ;;
@@ -30070,7 +29746,7 @@
       ;;
   esac
 
-  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK $ADD_LP64"
+  CCXXFLAGS_JDK="$CCXXFLAGS_JDK $ADD_LP64"
 
   # The package path is used only on macosx?
   PACKAGE_PATH=/opt/local
@@ -30083,27 +29759,27 @@
     #   Note: -Dmacro         is the same as    #define macro 1
     #         -Dmacro=        is the same as    #define macro
     if test "x$OPENJDK_TARGET_OS" = xsolaris; then
-      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_LITTLE_ENDIAN="
+      CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_LITTLE_ENDIAN="
     else
-      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_LITTLE_ENDIAN"
+      CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_LITTLE_ENDIAN"
     fi
   else
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_BIG_ENDIAN"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_BIG_ENDIAN"
   fi
   if test "x$OPENJDK_TARGET_OS" = xlinux; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DLINUX"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DLINUX"
   fi
   if test "x$OPENJDK_TARGET_OS" = xwindows; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DWINDOWS"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DWINDOWS"
   fi
   if test "x$OPENJDK_TARGET_OS" = xsolaris; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DSOLARIS"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DSOLARIS"
   fi
   if test "x$OPENJDK_TARGET_OS" = xaix; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DAIX -DPPC64"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DAIX -DPPC64"
   fi
   if test "x$OPENJDK_TARGET_OS" = xmacosx; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DMACOSX -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DMACOSX -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT"
     # Setting these parameters makes it an error to link to macosx APIs that are
     # newer than the given OS version and makes the linked binaries compatible even
     # if built on a newer version of the OS.
@@ -30113,25 +29789,25 @@
     # The macro takes the version with no dots, ex: 1070
     # Let the flags variables get resolved in make for easier override on make
     # command line.
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DMAC_OS_X_VERSION_MAX_ALLOWED=\$(subst .,,\$(MACOSX_VERSION_MIN)) -mmacosx-version-min=\$(MACOSX_VERSION_MIN)"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DMAC_OS_X_VERSION_MAX_ALLOWED=\$(subst .,,\$(MACOSX_VERSION_MIN)) -mmacosx-version-min=\$(MACOSX_VERSION_MIN)"
     LDFLAGS_JDK="$LDFLAGS_JDK -mmacosx-version-min=\$(MACOSX_VERSION_MIN)"
   fi
   if test "x$OPENJDK_TARGET_OS" = xbsd; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DBSD -D_ALLBSD_SOURCE"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DBSD -D_ALLBSD_SOURCE"
   fi
   if test "x$DEBUG_LEVEL" = xrelease; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DNDEBUG"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DNDEBUG"
   if test "x$OPENJDK_TARGET_OS" = xsolaris; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DTRIMMED"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DTRIMMED"
   fi
   else
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DDEBUG"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DDEBUG"
   fi
 
-  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DARCH='\"$OPENJDK_TARGET_CPU_LEGACY\"' -D$OPENJDK_TARGET_CPU_LEGACY"
-  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DRELEASE='\"\$(RELEASE)\"'"
+  CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DARCH='\"$OPENJDK_TARGET_CPU_LEGACY\"' -D$OPENJDK_TARGET_CPU_LEGACY"
+  CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DRELEASE='\"\$(RELEASE)\"'"
 
-  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK \
+  CCXXFLAGS_JDK="$CCXXFLAGS_JDK \
       -I${JDK_OUTPUTDIR}/include \
       -I${JDK_OUTPUTDIR}/include/$OPENJDK_TARGET_OS \
       -I${JDK_TOPDIR}/src/share/javavm/export \
@@ -30140,12 +29816,12 @@
       -I${JDK_TOPDIR}/src/$OPENJDK_TARGET_OS_API_DIR/native/common"
 
   # The shared libraries are compiled using the picflag.
-  CFLAGS_JDKLIB="$COMMON_CCXXFLAGS_JDK $CFLAGS_JDK $PICFLAG $CFLAGS_JDKLIB_EXTRA"
-  CXXFLAGS_JDKLIB="$COMMON_CCXXFLAGS_JDK $CXXFLAGS_JDK $PICFLAG $CXXFLAGS_JDKLIB_EXTRA "
+  CFLAGS_JDKLIB="$CCXXFLAGS_JDK $CFLAGS_JDK $PICFLAG $CFLAGS_JDKLIB_EXTRA"
+  CXXFLAGS_JDKLIB="$CCXXFLAGS_JDK $CXXFLAGS_JDK $PICFLAG $CXXFLAGS_JDKLIB_EXTRA "
 
   # Executable flags
-  CFLAGS_JDKEXE="$COMMON_CCXXFLAGS_JDK $CFLAGS_JDK"
-  CXXFLAGS_JDKEXE="$COMMON_CCXXFLAGS_JDK $CXXFLAGS_JDK"
+  CFLAGS_JDKEXE="$CCXXFLAGS_JDK $CFLAGS_JDK"
+  CXXFLAGS_JDKEXE="$CCXXFLAGS_JDK $CXXFLAGS_JDK"
 
   # Now this is odd. The JDK native libraries have to link against libjvm.so
   # On 32-bit machines there is normally two distinct libjvm.so:s, client and server.
@@ -30229,6 +29905,7 @@
 
 
 
+
   # Some Zero and Shark settings.
   # ZERO_ARCHFLAG tells the compiler which mode to build for
   case "${OPENJDK_TARGET_CPU}" in
@@ -30239,9 +29916,8 @@
       ZERO_ARCHFLAG="${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}"
   esac
 
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C compiler supports \"$ZERO_ARCHFLAG\"" >&5
-$as_echo_n "checking if the C compiler supports \"$ZERO_ARCHFLAG\"... " >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if compiler supports \"$ZERO_ARCHFLAG\"" >&5
+$as_echo_n "checking if compiler supports \"$ZERO_ARCHFLAG\"... " >&6; }
   supports=yes
 
   saved_cflags="$CFLAGS"
@@ -30270,19 +29946,6 @@
 
   CFLAGS="$saved_cflags"
 
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
-$as_echo "$supports" >&6; }
-  if test "x$supports" = "xyes" ; then
-    C_COMP_SUPPORTS="yes"
-  else
-    C_COMP_SUPPORTS="no"
-  fi
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C++ compiler supports \"$ZERO_ARCHFLAG\"" >&5
-$as_echo_n "checking if the C++ compiler supports \"$ZERO_ARCHFLAG\"... " >&6; }
-  supports=yes
-
   saved_cxxflags="$CXXFLAGS"
   CXXFLAGS="$CXXFLAG $ZERO_ARCHFLAG"
   ac_ext=cpp
@@ -30312,20 +29975,6 @@
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
 $as_echo "$supports" >&6; }
   if test "x$supports" = "xyes" ; then
-    CXX_COMP_SUPPORTS="yes"
-  else
-    CXX_COMP_SUPPORTS="no"
-  fi
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if both compilers support \"$ZERO_ARCHFLAG\"" >&5
-$as_echo_n "checking if both compilers support \"$ZERO_ARCHFLAG\"... " >&6; }
-  supports=no
-  if test "x$C_COMP_SUPPORTS" = "xyes" -a "x$CXX_COMP_SUPPORTS" = "xyes"; then supports=yes; fi
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
-$as_echo "$supports" >&6; }
-  if test "x$supports" = "xyes" ; then
     :
   else
     ZERO_ARCHFLAG=""
@@ -30336,9 +29985,8 @@
   # Check that the compiler supports -mX (or -qX on AIX) flags
   # Set COMPILER_SUPPORTS_TARGET_BITS_FLAG to 'true' if it does
 
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C compiler supports \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"" >&5
-$as_echo_n "checking if the C compiler supports \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"... " >&6; }
+  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if compiler supports \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"" >&5
+$as_echo_n "checking if compiler supports \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"... " >&6; }
   supports=yes
 
   saved_cflags="$CFLAGS"
@@ -30367,19 +30015,6 @@
 
   CFLAGS="$saved_cflags"
 
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
-$as_echo "$supports" >&6; }
-  if test "x$supports" = "xyes" ; then
-    C_COMP_SUPPORTS="yes"
-  else
-    C_COMP_SUPPORTS="no"
-  fi
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the C++ compiler supports \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"" >&5
-$as_echo_n "checking if the C++ compiler supports \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"... " >&6; }
-  supports=yes
-
   saved_cxxflags="$CXXFLAGS"
   CXXFLAGS="$CXXFLAG ${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}"
   ac_ext=cpp
@@ -30409,20 +30044,6 @@
   { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
 $as_echo "$supports" >&6; }
   if test "x$supports" = "xyes" ; then
-    CXX_COMP_SUPPORTS="yes"
-  else
-    CXX_COMP_SUPPORTS="no"
-  fi
-
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: checking if both compilers support \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"" >&5
-$as_echo_n "checking if both compilers support \"${COMPILER_TARGET_BITS_FLAG}${OPENJDK_TARGET_CPU_BITS}\"... " >&6; }
-  supports=no
-  if test "x$C_COMP_SUPPORTS" = "xyes" -a "x$CXX_COMP_SUPPORTS" = "xyes"; then supports=yes; fi
-
-  { $as_echo "$as_me:${as_lineno-$LINENO}: result: $supports" >&5
-$as_echo "$supports" >&6; }
-  if test "x$supports" = "xyes" ; then
     COMPILER_SUPPORTS_TARGET_BITS_FLAG=true
   else
     COMPILER_SUPPORTS_TARGET_BITS_FLAG=false
diff --git a/common/autoconf/hotspot-spec.gmk.in b/common/autoconf/hotspot-spec.gmk.in
index 8146fe5..65d14dc 100644
--- a/common/autoconf/hotspot-spec.gmk.in
+++ b/common/autoconf/hotspot-spec.gmk.in
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 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
@@ -109,8 +109,7 @@
 MT:=@HOTSPOT_MT@
 RC:=@HOTSPOT_RC@
 
-EXTRA_CFLAGS=@LEGACY_EXTRA_CFLAGS@ $(NO_DELETE_NULL_POINTER_CHECKS_CFLAG) \
-				   $(NO_LIFETIME_DSE_CFLAG) $(CXXSTD_CXXFLAG)
+EXTRA_CFLAGS=@LEGACY_EXTRA_CFLAGS@
 EXTRA_CXXFLAGS=@LEGACY_EXTRA_CXXFLAGS@
 EXTRA_LDFLAGS=@LEGACY_EXTRA_LDFLAGS@
 
diff --git a/common/autoconf/spec.gmk.in b/common/autoconf/spec.gmk.in
index 1c418f2..ed3ef8b 100644
--- a/common/autoconf/spec.gmk.in
+++ b/common/autoconf/spec.gmk.in
@@ -331,10 +331,6 @@
 CFLAGS_JDKEXE:=@CFLAGS_JDKEXE@
 CXXFLAGS_JDKEXE:=@CXXFLAGS_JDKEXE@
 
-NO_DELETE_NULL_POINTER_CHECKS_CFLAG=@NO_DELETE_NULL_POINTER_CHECKS_CFLAG@
-NO_LIFETIME_DSE_CFLAG=@NO_LIFETIME_DSE_CFLAG@
-CXXSTD_CXXFLAG=@CXXSTD_CXXFLAG@
-
 CXX:=@FIXPATH@ @CCACHE@ @CXX@
 #CXXFLAGS:=@CXXFLAGS@
 
diff --git a/common/autoconf/toolchain.m4 b/common/autoconf/toolchain.m4
index 1af8fa3..44ceadf 100644
--- a/common/autoconf/toolchain.m4
+++ b/common/autoconf/toolchain.m4
@@ -23,59 +23,9 @@
 # questions.
 #
 
-# Prepare the system so that TOOLCHAIN_CHECK_COMPILER_VERSION can be called.
-# Must have CC_VERSION_NUMBER and CXX_VERSION_NUMBER.
-AC_DEFUN([TOOLCHAIN_PREPARE_FOR_VERSION_COMPARISONS],
-[
-  if test "x$CC_VERSION" != "x$CXX_VERSION"; then
-    AC_MSG_WARN([C and C++ compiler has different version numbers, $CC_VERSION vs $CXX_VERSION.])
-    AC_MSG_WARN([This typically indicates a broken setup, and is not supported])
-  fi
-
-  # We only check CC_VERSION since we assume CXX_VERSION is equal.
-  if [ [[ "$CC_VERSION" =~ (.*\.){3} ]] ]; then
-    AC_MSG_WARN([C compiler version number has more than three parts (X.Y.Z): $CC_VERSION. Comparisons might be wrong.])
-  fi
-
-  if [ [[  "$CC_VERSION" =~ [0-9]{6} ]] ]; then
-    AC_MSG_WARN([C compiler version number has a part larger than 99999: $CC_VERSION. Comparisons might be wrong.])
-  fi
-
-  COMPARABLE_ACTUAL_VERSION=`$AWK -F. '{ printf("%05d%05d%05d\n", [$]1, [$]2, [$]3) }' <<< "$CC_VERSION"`
-])
-
-# Check if the configured compiler (C and C++) is of a specific version or
-# newer. TOOLCHAIN_PREPARE_FOR_VERSION_COMPARISONS must have been called before.
-#
-# Arguments:
-#   $1:   The version string to check against the found version
-#   $2:   block to run if the compiler is at least this version (>=)
-#   $3:   block to run if the compiler is older than this version (<)
-AC_DEFUN([TOOLCHAIN_CHECK_COMPILER_VERSION],
-[
-  REFERENCE_VERSION=$1
-
-  if [ [[ "$REFERENCE_VERSION" =~ (.*\.){3} ]] ]; then
-    AC_MSG_ERROR([Internal error: Cannot compare to $REFERENCE_VERSION, only three parts (X.Y.Z) is supported])
-  fi
-
-  if [ [[ "$REFERENCE_VERSION" =~ [0-9]{6} ]] ]; then
-    AC_MSG_ERROR([Internal error: Cannot compare to $REFERENCE_VERSION, only parts < 99999 is supported])
-  fi
-
-  # Version comparison method inspired by http://stackoverflow.com/a/24067243
-  COMPARABLE_REFERENCE_VERSION=`$AWK -F. '{ printf("%05d%05d%05d\n", [$]1, [$]2, [$]3) }' <<< "$REFERENCE_VERSION"`
-
-  if test $COMPARABLE_ACTUAL_VERSION -ge $COMPARABLE_REFERENCE_VERSION ; then
-    m4_ifval([$2], [$2], [:])
-  else
-    m4_ifval([$3], [$3], [:])
-  fi
-])
-
 # $1 = compiler to test (CC or CXX)
 # $2 = human readable name of compiler (C or C++)
-AC_DEFUN([TOOLCHAIN_EXTRACT_COMPILER_VERSION],
+AC_DEFUN([TOOLCHAIN_CHECK_COMPILER_VERSION],
 [
   COMPILER=[$]$1
   COMPILER_NAME=$2
@@ -131,8 +81,7 @@
 
     # First line typically looks something like:
     # gcc (Ubuntu/Linaro 4.5.2-8ubuntu4) 4.5.2
-    COMPILER_VERSION=`$ECHO $COMPILER_VERSION_TEST | \
-        $SED -e 's/^.* \(@<:@1-9@:>@\.@<:@0-9.@:>@*\)@<:@^0-9.@:>@.*$/\1/'`
+    COMPILER_VERSION=`$ECHO $COMPILER_VERSION_TEST | $SED -n "s/^.* \(@<:@1-9@:>@@<:@0-9.@:>@*\)/\1/p"`
     COMPILER_VENDOR=`$ECHO $COMPILER_VERSION_TEST | $SED -n "s/^\(.*\) @<:@1-9@:>@@<:@0-9.@:>@*/\1/p"`
   fi
   # This sets CC_VERSION or CXX_VERSION. (This comment is a grep marker)
@@ -232,7 +181,7 @@
     AC_MSG_RESULT([no, keeping $1])
     $1="$TEST_COMPILER"
   fi
-  TOOLCHAIN_EXTRACT_COMPILER_VERSION([$1], [$COMPILER_NAME])
+  TOOLCHAIN_CHECK_COMPILER_VERSION([$1], [$COMPILER_NAME])
 ])
 
 
@@ -436,12 +385,6 @@
   # Now that we have resolved CXX ourself, let autoconf have its go at it
   AC_PROG_CXX([$CXX])
 
-  # This is the compiler version number on the form X.Y[.Z]
-  AC_SUBST(CC_VERSION)
-  AC_SUBST(CXX_VERSION)
-
-  TOOLCHAIN_PREPARE_FOR_VERSION_COMPARISONS
-
   ### Locate other tools
 
   if test "x$OPENJDK_TARGET_OS" = xmacosx; then
@@ -564,8 +507,7 @@
       BASIC_FIXUP_EXECUTABLE(DUMPBIN)
 
       COMPILER_TYPE=CL
-      # silence copyright notice and other headers.
-      COMMON_CCXXFLAGS="$COMMON_CCXXFLAGS -nologo"
+      CCXXFLAGS="$CCXXFLAGS -nologo"
   ])
   AC_SUBST(RC_FLAGS)
   AC_SUBST(COMPILER_TYPE)
@@ -1012,20 +954,12 @@
   #
   # Now setup the CFLAGS and LDFLAGS for the JDK build.
   # Later we will also have CFLAGS and LDFLAGS for the hotspot subrepo build.
-  #    CFLAGS_JDK    - C Compiler flags
-  #    CXXFLAGS_JDK  - C++ Compiler flags
-  #    COMMON_CCXXFLAGS_JDK - common to C and C++
   #
   case $COMPILER_NAME in
     gcc )
-      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -W -Wall -Wno-unused -Wno-parentheses \
+      CCXXFLAGS_JDK="$CCXXFLAGS $CCXXFLAGS_JDK -W -Wall -Wno-unused -Wno-parentheses \
       -pipe \
       -D_GNU_SOURCE -D_REENTRANT -D_LARGEFILE64_SOURCE"
-      CXXSTD_CXXFLAG="-std=gnu++98"
-      TOOLCHAIN_CXX_COMPILER_CHECK_ARGUMENTS([$CXXSTD_CXXFLAG $CFLAGS_WARNINGS_ARE_ERRORS],
-    					     [], [CXXSTD_CXXFLAG=""])
-      CXXFLAGS_JDK="${CXXFLAGS_JDK} ${CXXSTD_CXXFLAG}"
-      AC_SUBST([CXXSTD_CXXFLAG])
       case $OPENJDK_TARGET_CPU_ARCH in
         arm )
           # on arm we don't prevent gcc to omit frame pointer but do prevent strict aliasing
@@ -1035,17 +969,16 @@
           # on ppc we don't prevent gcc to omit frame pointer nor strict-aliasing
           ;;
         * )
-          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -fno-omit-frame-pointer"
+          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -fno-omit-frame-pointer"
           CFLAGS_JDK="${CFLAGS_JDK} -fno-strict-aliasing"
           ;;
       esac
-      TOOLCHAIN_CHECK_COMPILER_VERSION(6, TOOLCHAIN_SETUP_GCC6_COMPILER_FLAGS)
       ;;
     ossc )
-      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -DTRACING -DMACRO_MEMSYS_OPS -DBREAKPTS"
+      CCXXFLAGS_JDK="$CCXXFLAGS $CCXXFLAGS_JDK -DTRACING -DMACRO_MEMSYS_OPS -DBREAKPTS"
       case $OPENJDK_TARGET_CPU_ARCH in
         x86 )
-          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DcpuIntel -Di586 -D$OPENJDK_TARGET_CPU_LEGACY_LIB"
+          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DcpuIntel -Di586 -D$OPENJDK_TARGET_CPU_LEGACY_LIB"
           CFLAGS_JDK="$CFLAGS_JDK -erroff=E_BAD_PRAGMA_PACK_VALUE"
           ;;
       esac
@@ -1064,16 +997,16 @@
       LDFLAGS_CXX_JDK="$LDFLAGS_CXX_JDK"
       ;;
     cl )
-      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS $COMMON_CCXXFLAGS_JDK -Zi -MD -Zc:wchar_t- -W3 -wd4800 \
+      CCXXFLAGS_JDK="$CCXXFLAGS $CCXXFLAGS_JDK -Zi -MD -Zc:wchar_t- -W3 -wd4800 \
       -D_STATIC_CPPLIB -D_DISABLE_DEPRECATE_STATIC_CPPLIB -DWIN32_LEAN_AND_MEAN \
       -D_CRT_SECURE_NO_DEPRECATE -D_CRT_NONSTDC_NO_DEPRECATE \
       -DWIN32 -DIAL"
       case $OPENJDK_TARGET_CPU in
         x86 )
-          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_X86_ -Dx86"
+          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_X86_ -Dx86"
           ;;
         x86_64 )
-          COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_AMD64_ -Damd64"
+          CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_AMD64_ -Damd64"
           ;;
       esac
       ;;
@@ -1103,7 +1036,7 @@
       ;;
   esac
 
-  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK $ADD_LP64"
+  CCXXFLAGS_JDK="$CCXXFLAGS_JDK $ADD_LP64"
 
   # The package path is used only on macosx?
   PACKAGE_PATH=/opt/local
@@ -1116,27 +1049,27 @@
     #   Note: -Dmacro         is the same as    #define macro 1
     #         -Dmacro=        is the same as    #define macro
     if test "x$OPENJDK_TARGET_OS" = xsolaris; then
-      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_LITTLE_ENDIAN="
+      CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_LITTLE_ENDIAN="
     else
-      COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_LITTLE_ENDIAN"
+      CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_LITTLE_ENDIAN"
     fi
   else
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -D_BIG_ENDIAN"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -D_BIG_ENDIAN"
   fi
   if test "x$OPENJDK_TARGET_OS" = xlinux; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DLINUX"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DLINUX"
   fi
   if test "x$OPENJDK_TARGET_OS" = xwindows; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DWINDOWS"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DWINDOWS"
   fi
   if test "x$OPENJDK_TARGET_OS" = xsolaris; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DSOLARIS"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DSOLARIS"
   fi
   if test "x$OPENJDK_TARGET_OS" = xaix; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DAIX -DPPC64"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DAIX -DPPC64"
   fi
   if test "x$OPENJDK_TARGET_OS" = xmacosx; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DMACOSX -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DMACOSX -D_ALLBSD_SOURCE -D_DARWIN_UNLIMITED_SELECT"
     # Setting these parameters makes it an error to link to macosx APIs that are
     # newer than the given OS version and makes the linked binaries compatible even
     # if built on a newer version of the OS.
@@ -1146,25 +1079,25 @@
     # The macro takes the version with no dots, ex: 1070
     # Let the flags variables get resolved in make for easier override on make
     # command line.
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DMAC_OS_X_VERSION_MAX_ALLOWED=\$(subst .,,\$(MACOSX_VERSION_MIN)) -mmacosx-version-min=\$(MACOSX_VERSION_MIN)"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DMAC_OS_X_VERSION_MAX_ALLOWED=\$(subst .,,\$(MACOSX_VERSION_MIN)) -mmacosx-version-min=\$(MACOSX_VERSION_MIN)"
     LDFLAGS_JDK="$LDFLAGS_JDK -mmacosx-version-min=\$(MACOSX_VERSION_MIN)"
   fi
   if test "x$OPENJDK_TARGET_OS" = xbsd; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DBSD -D_ALLBSD_SOURCE"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DBSD -D_ALLBSD_SOURCE"
   fi
   if test "x$DEBUG_LEVEL" = xrelease; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DNDEBUG"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DNDEBUG"
   if test "x$OPENJDK_TARGET_OS" = xsolaris; then
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DTRIMMED"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DTRIMMED"
   fi
   else
-    COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DDEBUG"
+    CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DDEBUG"
   fi
 
-  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DARCH='\"$OPENJDK_TARGET_CPU_LEGACY\"' -D$OPENJDK_TARGET_CPU_LEGACY"
-  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK -DRELEASE='\"\$(RELEASE)\"'"
+  CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DARCH='\"$OPENJDK_TARGET_CPU_LEGACY\"' -D$OPENJDK_TARGET_CPU_LEGACY"
+  CCXXFLAGS_JDK="$CCXXFLAGS_JDK -DRELEASE='\"\$(RELEASE)\"'"
 
-  COMMON_CCXXFLAGS_JDK="$COMMON_CCXXFLAGS_JDK \
+  CCXXFLAGS_JDK="$CCXXFLAGS_JDK \
       -I${JDK_OUTPUTDIR}/include \
       -I${JDK_OUTPUTDIR}/include/$OPENJDK_TARGET_OS \
       -I${JDK_TOPDIR}/src/share/javavm/export \
@@ -1173,12 +1106,12 @@
       -I${JDK_TOPDIR}/src/$OPENJDK_TARGET_OS_API_DIR/native/common"
 
   # The shared libraries are compiled using the picflag.
-  CFLAGS_JDKLIB="$COMMON_CCXXFLAGS_JDK $CFLAGS_JDK $PICFLAG $CFLAGS_JDKLIB_EXTRA"
-  CXXFLAGS_JDKLIB="$COMMON_CCXXFLAGS_JDK $CXXFLAGS_JDK $PICFLAG $CXXFLAGS_JDKLIB_EXTRA "
+  CFLAGS_JDKLIB="$CCXXFLAGS_JDK $CFLAGS_JDK $PICFLAG $CFLAGS_JDKLIB_EXTRA"
+  CXXFLAGS_JDKLIB="$CCXXFLAGS_JDK $CXXFLAGS_JDK $PICFLAG $CXXFLAGS_JDKLIB_EXTRA "
 
   # Executable flags
-  CFLAGS_JDKEXE="$COMMON_CCXXFLAGS_JDK $CFLAGS_JDK"
-  CXXFLAGS_JDKEXE="$COMMON_CCXXFLAGS_JDK $CXXFLAGS_JDK"
+  CFLAGS_JDKEXE="$CCXXFLAGS_JDK $CFLAGS_JDK"
+  CXXFLAGS_JDKEXE="$CCXXFLAGS_JDK $CXXFLAGS_JDK"
 
   # Now this is odd. The JDK native libraries have to link against libjvm.so
   # On 32-bit machines there is normally two distinct libjvm.so:s, client and server.
@@ -1263,13 +1196,13 @@
 ])
 
 
-# TOOLCHAIN_C_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
-#                                      [RUN-IF-FALSE])
+# TOOLCHAIN_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
+#                                   [RUN-IF-FALSE])
 # ------------------------------------------------------------
-# Check that the C compiler supports an argument
-AC_DEFUN([TOOLCHAIN_C_COMPILER_CHECK_ARGUMENTS],
+# Check that the c and c++ compilers support an argument
+AC_DEFUN([TOOLCHAIN_COMPILER_CHECK_ARGUMENTS],
 [
-  AC_MSG_CHECKING([if the C compiler supports "$1"])
+  AC_MSG_CHECKING([if compiler supports "$1"])
   supports=yes
 
   saved_cflags="$CFLAGS"
@@ -1280,23 +1213,6 @@
   AC_LANG_POP([C])
   CFLAGS="$saved_cflags"
 
-  AC_MSG_RESULT([$supports])
-  if test "x$supports" = "xyes" ; then
-    m4_ifval([$2], [$2], [:])
-  else
-    m4_ifval([$3], [$3], [:])
-  fi
-])
-
-# TOOLCHAIN_CXX_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
-#                                        [RUN-IF-FALSE])
-# ------------------------------------------------------------
-# Check that the C++ compiler supports an argument
-AC_DEFUN([TOOLCHAIN_CXX_COMPILER_CHECK_ARGUMENTS],
-[
-  AC_MSG_CHECKING([if the C++ compiler supports "$1"])
-  supports=yes
-
   saved_cxxflags="$CXXFLAGS"
   CXXFLAGS="$CXXFLAG $1"
   AC_LANG_PUSH([C++])
@@ -1304,32 +1220,7 @@
       [supports=no])
   AC_LANG_POP([C++])
   CXXFLAGS="$saved_cxxflags"
-  
-  AC_MSG_RESULT([$supports])
-  if test "x$supports" = "xyes" ; then
-    m4_ifval([$2], [$2], [:])
-  else
-    m4_ifval([$3], [$3], [:])
-  fi
-])
 
-# TOOLCHAIN_COMPILER_CHECK_ARGUMENTS([ARGUMENT], [RUN-IF-TRUE],
-#                                    [RUN-IF-FALSE])
-# ------------------------------------------------------------
-# Check that the C and C++ compilers support an argument
-AC_DEFUN([TOOLCHAIN_COMPILER_CHECK_ARGUMENTS],
-[
-  TOOLCHAIN_C_COMPILER_CHECK_ARGUMENTS([$1],
-  				       [C_COMP_SUPPORTS="yes"],
-				       [C_COMP_SUPPORTS="no"])
-  TOOLCHAIN_CXX_COMPILER_CHECK_ARGUMENTS([$1],
-  					 [CXX_COMP_SUPPORTS="yes"],
-					 [CXX_COMP_SUPPORTS="no"])
-
-  AC_MSG_CHECKING([if both compilers support "$1"])
-  supports=no
-  if test "x$C_COMP_SUPPORTS" = "xyes" -a "x$CXX_COMP_SUPPORTS" = "xyes"; then supports=yes; fi
-  
   AC_MSG_RESULT([$supports])
   if test "x$supports" = "xyes" ; then
     m4_ifval([$2], [$2], [:])
@@ -1420,20 +1311,3 @@
   AC_SUBST(JT_HOME)
   AC_SUBST(JTREGEXE)
 ])
-
-AC_DEFUN_ONCE([TOOLCHAIN_SETUP_GCC6_COMPILER_FLAGS],
-[
-  # These flags are required for GCC 6 builds as undefined behaviour in OpenJDK code
-  # runs afoul of the more aggressive versions of these optimisations.
-  # Notably, value range propagation now assumes that the this pointer of C++
-  # member functions is non-null.
-  NO_DELETE_NULL_POINTER_CHECKS_CFLAG="-fno-delete-null-pointer-checks"
-  TOOLCHAIN_COMPILER_CHECK_ARGUMENTS([$NO_DELETE_NULL_POINTER_CHECKS_CFLAG -Werror],
-  				     [], [NO_DELETE_NULL_POINTER_CHECKS_CFLAG=""])
-  AC_SUBST([NO_DELETE_NULL_POINTER_CHECKS_CFLAG])
-  NO_LIFETIME_DSE_CFLAG="-fno-lifetime-dse"
-  TOOLCHAIN_COMPILER_CHECK_ARGUMENTS([$NO_LIFETIME_DSE_CFLAG -Werror],
-  				     [], [NO_LIFETIME_DSE_CFLAG=""])
-  CFLAGS_JDK="${CFLAGS_JDK} ${NO_DELETE_NULL_POINTER_CHECKS_CFLAG} ${NO_LIFETIME_DSE_CFLAG}"
-  AC_SUBST([NO_LIFETIME_DSE_CFLAG])
-])
diff --git a/corba/ASSEMBLY_EXCEPTION b/corba/ASSEMBLY_EXCEPTION
index 065b8d9..8b7ac1d 100644
--- a/corba/ASSEMBLY_EXCEPTION
+++ b/corba/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
-openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
-General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Sun at openjdk.java.net and
+openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
+GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Oracle gives you permission to link this
-    OpenJDK Code with certain code licensed by Oracle as indicated at
+    As a special exception, Sun gives you permission to link this
+    OpenJDK Code with certain code licensed by Sun as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Oracle.
+    governed by the licenses under which they were offered by Sun.
 
-As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
-to build an executable that includes those portions of necessary code that
-Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
-with the Classpath exception).  If you modify or add to the OpenJDK code,
-that new GPL2 code may still be combined with Designated Exception Modules
-if the new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
+build an executable that includes those portions of necessary code that Sun
+could not provide under GPL2 (or that Sun has provided under GPL2 with the
+Classpath exception).  If you modify or add to the OpenJDK code, that new
+GPL2 code may still be combined with Designated Exception Modules if the
+new code is made subject to this exception by its copyright holder.
diff --git a/corba/LICENSE b/corba/LICENSE
index 8b400c7..b40a0f4 100644
--- a/corba/LICENSE
+++ b/corba/LICENSE
@@ -3,7 +3,7 @@
 Version 2, June 1991
 
 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Everyone is permitted to copy and distribute verbatim copies of this license
 document, but changing it is not allowed.
@@ -287,8 +287,8 @@
     more details.
 
     You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+    with this program; if not, write to the Free Software Foundation, Inc., 59
+    Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Also add information on how to contact you by electronic and paper mail.
 
diff --git a/corba/src/share/classes/com/sun/corba/se/impl/io/IIOPInputStream.java b/corba/src/share/classes/com/sun/corba/se/impl/io/IIOPInputStream.java
index 7eff7c3..c9d6320 100644
--- a/corba/src/share/classes/com/sun/corba/se/impl/io/IIOPInputStream.java
+++ b/corba/src/share/classes/com/sun/corba/se/impl/io/IIOPInputStream.java
@@ -2230,7 +2230,7 @@
      * REVISIT -- This code doesn't do what the comment says to when
      * getField() is null!
      */
-    private void inputClassFields(Object o, final Class<?> cl,
+    private void inputClassFields(Object o, Class cl,
                                   ObjectStreamField[] fields,
                                   com.sun.org.omg.SendingContext.CodeBase sender)
         throws InvalidClassException, StreamCorruptedException,
@@ -2264,31 +2264,21 @@
                 }
 
                 try {
-                    Class<?> fieldCl = fields[i].getClazz();
+                    Class fieldCl = fields[i].getClazz();
                     if ((objectValue != null)
                             && (!fieldCl.isAssignableFrom(
                                     objectValue.getClass()))) {
                         throw new IllegalArgumentException("Field mismatch");
                     }
-                    Field declaredClassField = null;
-                    final String inputStreamFieldName = fields[i].getName();
+                   Field classField = null;
                     try {
-                        declaredClassField = getDeclaredField( cl, inputStreamFieldName);
-                    } catch (PrivilegedActionException paEx) {
-                        throw new IllegalArgumentException(
-                            (NoSuchFieldException) paEx.getException());
+                        classField = cl.getDeclaredField(fields[i].getName());
+                    } catch (NoSuchFieldException nsfEx) {
+                        throw new IllegalArgumentException(nsfEx);
                     } catch (SecurityException secEx) {
-                        throw new IllegalArgumentException(secEx);
-                    }  catch (NullPointerException npEx) {
-                        continue;
-                    } catch (NoSuchFieldException e) {
-                        continue;
+                        throw new IllegalArgumentException(secEx.getCause());
                     }
-
-                    if (declaredClassField == null) {
-                        continue;
-                    }
-                    Class<?> declaredFieldClass = declaredClassField.getType();
+                    Class<?> declaredFieldClass = classField.getType();
 
                     // check input field type is a declared field type
                     // input field is a subclass of the declared field
@@ -2301,24 +2291,15 @@
                     }
                     bridge.putObject( o, fields[i].getFieldID(), objectValue ) ;
                     // reflective code: fields[i].getField().set( o, objectValue ) ;
-                } catch (IllegalArgumentException iaEx) {
-                    String objectValueClassName = "null";
-                    String currentClassDescClassName = "null";
-                    String fieldName = "null";
-                    if (objectValue != null) {
-                        objectValueClassName = objectValue.getClass().getName();
-                    }
-                    if (currentClassDesc != null) {
-                        currentClassDescClassName = currentClassDesc.getName();
-                    }
-                    if (fields[i] != null && fields[i].getField() != null) {
-                        fieldName = fields[i].getField().getName();
-                    }
-                    ClassCastException ccEx = new ClassCastException(
-                            "Assigning instance of class " + objectValueClassName
-                                    + " to field " + currentClassDescClassName + '#' + fieldName);
-                    ccEx.initCause( iaEx ) ;
-                    throw ccEx ;
+                } catch (IllegalArgumentException e) {
+                    ClassCastException exc = new ClassCastException("Assigning instance of class " +
+                                                 objectValue.getClass().getName() +
+                                                 " to field " +
+                                                 currentClassDesc.getName() +
+                                                 '#' +
+                                                 fields[i].getField().getName());
+                    exc.initCause( e ) ;
+                    throw exc ;
                 }
             } // end : for loop
             }
@@ -2614,9 +2595,9 @@
 
     }
 
-    private static void setObjectField(Object o, Class<?> c, String fieldName, Object v) {
+    private static void setObjectField(Object o, Class c, String fieldName, Object v) {
         try {
-            Field fld = getDeclaredField( c, fieldName ) ;
+            Field fld = c.getDeclaredField( fieldName ) ;
             Class fieldCl = fld.getType();
             if(v != null && !fieldCl.isInstance(v)) {
                 throw new Exception();
@@ -2636,10 +2617,10 @@
         }
     }
 
-    private static void setBooleanField(Object o, Class<?> c, String fieldName, boolean v)
+    private static void setBooleanField(Object o, Class c, String fieldName, boolean v)
     {
         try {
-            Field fld = getDeclaredField( c, fieldName ) ;
+            Field fld = c.getDeclaredField( fieldName ) ;
             if ((fld != null) && (fld.getType() == Boolean.TYPE)) {
                 long key = bridge.objectFieldOffset( fld ) ;
                 bridge.putBoolean( o, key, v ) ;
@@ -2659,10 +2640,10 @@
         }
     }
 
-    private static void setByteField(Object o, Class<?> c, String fieldName, byte v)
+    private static void setByteField(Object o, Class c, String fieldName, byte v)
     {
         try {
-            Field fld = getDeclaredField( c, fieldName ) ;
+            Field fld = c.getDeclaredField( fieldName ) ;
             if ((fld != null) && (fld.getType() == Byte.TYPE)) {
                 long key = bridge.objectFieldOffset( fld ) ;
                 bridge.putByte( o, key, v ) ;
@@ -2682,10 +2663,10 @@
         }
     }
 
-    private static void setCharField(Object o, Class<?> c, String fieldName, char v)
+    private static void setCharField(Object o, Class c, String fieldName, char v)
     {
         try {
-            Field fld = getDeclaredField( c, fieldName ) ;
+            Field fld = c.getDeclaredField( fieldName ) ;
             if ((fld != null) && (fld.getType() == Character.TYPE)) {
                 long key = bridge.objectFieldOffset( fld ) ;
                 bridge.putChar( o, key, v ) ;
@@ -2705,10 +2686,10 @@
         }
     }
 
-    private static void setShortField(Object o, Class<?> c, String fieldName, short v)
+    private static void setShortField(Object o, Class c, String fieldName, short v)
     {
         try {
-            Field fld = getDeclaredField( c, fieldName ) ;
+            Field fld = c.getDeclaredField( fieldName ) ;
             if ((fld != null) && (fld.getType() == Short.TYPE)) {
                 long key = bridge.objectFieldOffset( fld ) ;
                 bridge.putShort( o, key, v ) ;
@@ -2728,10 +2709,10 @@
         }
     }
 
-    private static void setIntField(Object o, final Class<?> c, final String fieldName, int v)
+    private static void setIntField(Object o, Class c, String fieldName, int v)
     {
         try {
-            Field fld = getDeclaredField( c, fieldName ) ;
+            Field fld = c.getDeclaredField( fieldName ) ;
             if ((fld != null) && (fld.getType() == Integer.TYPE)) {
                 long key = bridge.objectFieldOffset( fld ) ;
                 bridge.putInt( o, key, v ) ;
@@ -2751,10 +2732,10 @@
         }
     }
 
-    private static void setLongField(Object o, Class<?> c, String fieldName, long v)
+    private static void setLongField(Object o, Class c, String fieldName, long v)
     {
         try {
-            Field fld = getDeclaredField( c, fieldName ) ;
+            Field fld = c.getDeclaredField( fieldName ) ;
             if ((fld != null) && (fld.getType() == Long.TYPE)) {
                 long key = bridge.objectFieldOffset( fld ) ;
                 bridge.putLong( o, key, v ) ;
@@ -2774,10 +2755,10 @@
         }
     }
 
-    private static void setFloatField(Object o, Class<?> c, String fieldName, float v)
+    private static void setFloatField(Object o, Class c, String fieldName, float v)
     {
         try {
-            Field fld = getDeclaredField( c, fieldName ) ;
+            Field fld = c.getDeclaredField( fieldName ) ;
             if ((fld != null) && (fld.getType() == Float.TYPE)) {
                 long key = bridge.objectFieldOffset( fld ) ;
                 bridge.putFloat( o, key, v ) ;
@@ -2797,10 +2778,10 @@
         }
     }
 
-    private static void setDoubleField(Object o, Class<?> c, String fieldName, double v)
+    private static void setDoubleField(Object o, Class c, String fieldName, double v)
     {
         try {
-            Field fld = getDeclaredField(c, fieldName ) ;
+            Field fld = c.getDeclaredField( fieldName ) ;
             if ((fld != null) && (fld.getType() == Double.TYPE)) {
                 long key = bridge.objectFieldOffset( fld ) ;
                 bridge.putDouble( o, key, v ) ;
@@ -2820,23 +2801,6 @@
         }
     }
 
-
-    private static Field getDeclaredField(final Class<?> c,
-                                           final String fieldName)
-        throws PrivilegedActionException, NoSuchFieldException, SecurityException {
-        if (System.getSecurityManager() == null) {
-            return c.getDeclaredField(fieldName);
-        } else {
-            return AccessController
-                .doPrivileged(new PrivilegedExceptionAction<Field>() {
-                    public Field run()
-                            throws NoSuchFieldException {
-                        return c.getDeclaredField(fieldName);
-                    }
-                });
-        }
-    }
-
     /**
      * This class maintains a map of stream position to
      * an Object currently being deserialized.  It is used
@@ -2847,12 +2811,12 @@
      */
     static class ActiveRecursionManager
     {
-        private Map<Integer, Object> offsetToObjectMap;
+        private Map offsetToObjectMap;
 
         public ActiveRecursionManager() {
             // A hash map is unsynchronized and allows
             // null values
-            offsetToObjectMap = new HashMap<>();
+            offsetToObjectMap = new HashMap();
         }
 
         // Called right after allocating a new object.
diff --git a/get_source.sh b/get_source.sh
index 72049bd..5e874d1 100755
--- a/get_source.sh
+++ b/get_source.sh
@@ -67,7 +67,7 @@
   error "Could not locate Mercurial command"
 fi
 
-hgversion="`LANGUAGE=en hg --version 2> /dev/null | sed -n -e 's@^Mercurial Distributed SCM (version \([^+]*\).*)\$@\1@p'`"
+hgversion="`hg --version 2> /dev/null | sed -n -e 's@^Mercurial Distributed SCM (version \([^+]*\).*)\$@\1@p'`"
 if [ "x${hgversion}" = "x" ] ; then
   error "Could not determine Mercurial version of $hgwhere"
 fi
diff --git a/hotspot/ASSEMBLY_EXCEPTION b/hotspot/ASSEMBLY_EXCEPTION
index 065b8d9..3e78398 100644
--- a/hotspot/ASSEMBLY_EXCEPTION
+++ b/hotspot/ASSEMBLY_EXCEPTION
@@ -1,9 +1,9 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
-openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
-General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Oracle at openjdk.java.net and
+openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
+GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
@@ -19,9 +19,9 @@
     provided that the Designated Exception Modules continue to be
     governed by the licenses under which they were offered by Oracle.
 
-As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
-to build an executable that includes those portions of necessary code that
-Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
-with the Classpath exception).  If you modify or add to the OpenJDK code,
-that new GPL2 code may still be combined with Designated Exception Modules
-if the new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code to
+build an executable that includes those portions of necessary code that Oracle
+could not provide under GPL2 (or that Oracle has provided under GPL2 with the
+Classpath exception).  If you modify or add to the OpenJDK code, that new
+GPL2 code may still be combined with Designated Exception Modules if the
+new code is made subject to this exception by its copyright holder.
diff --git a/hotspot/LICENSE b/hotspot/LICENSE
index 8b400c7..b40a0f4 100644
--- a/hotspot/LICENSE
+++ b/hotspot/LICENSE
@@ -3,7 +3,7 @@
 Version 2, June 1991
 
 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Everyone is permitted to copy and distribute verbatim copies of this license
 document, but changing it is not allowed.
@@ -287,8 +287,8 @@
     more details.
 
     You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+    with this program; if not, write to the Free Software Foundation, Inc., 59
+    Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Also add information on how to contact you by electronic and paper mail.
 
diff --git a/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp b/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp
index a488d6d..7d9aecb 100644
--- a/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp
+++ b/hotspot/src/cpu/ppc/vm/assembler_ppc.hpp
@@ -589,7 +589,6 @@
     VNOR_OPCODE    = (4u  << OPCODE_SHIFT | 1284u     ),
     VOR_OPCODE     = (4u  << OPCODE_SHIFT | 1156u     ),
     VXOR_OPCODE    = (4u  << OPCODE_SHIFT | 1220u     ),
-    VRLD_OPCODE    = (4u  << OPCODE_SHIFT |  196u     ),
     VRLB_OPCODE    = (4u  << OPCODE_SHIFT |    4u     ),
     VRLW_OPCODE    = (4u  << OPCODE_SHIFT |  132u     ),
     VRLH_OPCODE    = (4u  << OPCODE_SHIFT |   68u     ),
@@ -1919,7 +1918,6 @@
   inline void vnor(     VectorRegister d, VectorRegister a, VectorRegister b);
   inline void vor(      VectorRegister d, VectorRegister a, VectorRegister b);
   inline void vxor(     VectorRegister d, VectorRegister a, VectorRegister b);
-  inline void vrld(     VectorRegister d, VectorRegister a, VectorRegister b);
   inline void vrlb(     VectorRegister d, VectorRegister a, VectorRegister b);
   inline void vrlw(     VectorRegister d, VectorRegister a, VectorRegister b);
   inline void vrlh(     VectorRegister d, VectorRegister a, VectorRegister b);
diff --git a/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp b/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp
index 0f76435..b4a7370 100644
--- a/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp
+++ b/hotspot/src/cpu/ppc/vm/assembler_ppc.inline.hpp
@@ -739,7 +739,6 @@
 inline void Assembler::vnor(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VNOR_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vor(     VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VOR_OPCODE      | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vxor(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VXOR_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
-inline void Assembler::vrld(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VRLD_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vrlb(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VRLB_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vrlw(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VRLW_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
 inline void Assembler::vrlh(    VectorRegister d, VectorRegister a, VectorRegister b) { emit_int32( VRLH_OPCODE     | vrt(d) | vra(a) | vrb(b)); }
diff --git a/hotspot/src/cpu/ppc/vm/compiledIC_ppc.cpp b/hotspot/src/cpu/ppc/vm/compiledIC_ppc.cpp
index 762a329..1b54594 100644
--- a/hotspot/src/cpu/ppc/vm/compiledIC_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/compiledIC_ppc.cpp
@@ -94,7 +94,7 @@
 
 const int IC_pos_in_java_to_interp_stub = 8;
 #define __ _masm.
-address CompiledStaticCall::emit_to_interp_stub(CodeBuffer &cbuf) {
+void CompiledStaticCall::emit_to_interp_stub(CodeBuffer &cbuf) {
 #ifdef COMPILER2
   // Get the mark within main instrs section which is set to the address of the call.
   address call_addr = cbuf.insts_mark();
@@ -106,7 +106,8 @@
   // Start the stub.
   address stub = __ start_a_stub(CompiledStaticCall::to_interp_stub_size());
   if (stub == NULL) {
-    return NULL; // CodeCache is full
+    Compile::current()->env()->record_out_of_memory_failure();
+    return;
   }
 
   // For java_to_interp stubs we use R11_scratch1 as scratch register
@@ -148,7 +149,6 @@
 
  // End the stub.
   __ end_a_stub();
-  return stub;
 #else
   ShouldNotReachHere();
 #endif
diff --git a/hotspot/src/cpu/ppc/vm/ppc.ad b/hotspot/src/cpu/ppc/vm/ppc.ad
index 54c2361..9fd4d73 100644
--- a/hotspot/src/cpu/ppc/vm/ppc.ad
+++ b/hotspot/src/cpu/ppc/vm/ppc.ad
@@ -1171,7 +1171,7 @@
   // Start the stub.
   address stub = __ start_a_stub(Compile::MAX_stubs_size/2);
   if (stub == NULL) {
-    ciEnv::current()->record_failure("CodeCache is full");
+    Compile::current()->env()->record_out_of_memory_failure();
     return;
   }
 
@@ -1249,7 +1249,7 @@
 
     // Emit the trampoline stub which will be related to the branch-and-link below.
     CallStubImpl::emit_trampoline_stub(_masm, entry_point_toc_offset, offsets.insts_call_instruction_offset);
-    if (ciEnv::current()->failing()) { return offsets; } // Code cache may be full.
+    if (Compile::current()->env()->failing()) { return offsets; } // Code cache may be full.
     __ relocate(rtype);
   }
 
@@ -3488,7 +3488,7 @@
 
         // Emit the trampoline stub which will be related to the branch-and-link below.
         CallStubImpl::emit_trampoline_stub(_masm, entry_point_toc_offset, start_offset);
-        if (ciEnv::current()->failing()) { return; } // Code cache may be full.
+        if (Compile::current()->env()->failing()) { return; } // Code cache may be full.
         __ relocate(_optimized_virtual ?
                     relocInfo::opt_virtual_call_type : relocInfo::static_call_type);
       }
@@ -3501,11 +3501,7 @@
       __ bl(__ pc());  // Emits a relocation.
 
       // The stub for call to interpreter.
-      address stub = CompiledStaticCall::emit_to_interp_stub(cbuf);
-      if (stub == NULL) {
-        ciEnv::current()->record_failure("CodeCache is full"); 
-        return;
-      }
+      CompiledStaticCall::emit_to_interp_stub(cbuf);
     }
   %}
 
@@ -3550,11 +3546,7 @@
 
     assert(_method, "execute next statement conditionally");
     // The stub for call to interpreter.
-    address stub = CompiledStaticCall::emit_to_interp_stub(cbuf);
-    if (stub == NULL) {
-      ciEnv::current()->record_failure("CodeCache is full"); 
-      return;
-    }
+    CompiledStaticCall::emit_to_interp_stub(cbuf);
 
     // Restore original sp.
     __ ld(R11_scratch1, 0, R1_SP); // Load caller sp.
@@ -5469,7 +5461,7 @@
 %}
 
 // Match loading integer and casting it to long.
-instruct loadI2L(iRegLdst dst, memoryAlg4 mem) %{
+instruct loadI2L(iRegLdst dst, memory mem) %{
   match(Set dst (ConvI2L (LoadI mem)));
   predicate(_kids[0]->_leaf->as_Load()->is_unordered());
   ins_cost(MEMORY_REF_COST);
@@ -5485,7 +5477,7 @@
 %}
 
 // Match loading integer and casting it to long - acquire.
-instruct loadI2L_ac(iRegLdst dst, memoryAlg4 mem) %{
+instruct loadI2L_ac(iRegLdst dst, memory mem) %{
   match(Set dst (ConvI2L (LoadI mem)));
   ins_cost(3*MEMORY_REF_COST);
 
diff --git a/hotspot/src/cpu/ppc/vm/relocInfo_ppc.cpp b/hotspot/src/cpu/ppc/vm/relocInfo_ppc.cpp
index b48cba0..4f365a4 100644
--- a/hotspot/src/cpu/ppc/vm/relocInfo_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/relocInfo_ppc.cpp
@@ -62,7 +62,7 @@
       nativeMovConstReg_at(addr())->set_narrow_oop(no, code());
     }
   } else {
-    guarantee((address) (nativeMovConstReg_at(addr())->data()) == x, "data must match");
+    assert((address) (nativeMovConstReg_at(addr())->data()) == x, "data must match");
   }
 }
 
diff --git a/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp b/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp
index 325b527..ed292cb 100644
--- a/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/stubGenerator_ppc.cpp
@@ -1961,434 +1961,6 @@
     return start;
   }
 
-  // Arguments for generated stub (little endian only):
-  //   R3_ARG1   - source byte array address
-  //   R4_ARG2   - destination byte array address
-  //   R5_ARG3   - round key array
-  address generate_aescrypt_encryptBlock() {
-    assert(UseAES, "need AES instructions and misaligned SSE support");
-    StubCodeMark mark(this, "StubRoutines", "aescrypt_encryptBlock");
-
-    address start = __ function_entry();
-
-    Label L_doLast;
-
-    Register from           = R3_ARG1;  // source array address
-    Register to             = R4_ARG2;  // destination array address
-    Register key            = R5_ARG3;  // round key array
-
-    Register keylen         = R8;
-    Register temp           = R9;
-    Register keypos         = R10;
-    Register hex            = R11;
-    Register fifteen        = R12;
-
-    VectorRegister vRet     = VR0;
-
-    VectorRegister vKey1    = VR1;
-    VectorRegister vKey2    = VR2;
-    VectorRegister vKey3    = VR3;
-    VectorRegister vKey4    = VR4;
-
-    VectorRegister fromPerm = VR5;
-    VectorRegister keyPerm  = VR6;
-    VectorRegister toPerm   = VR7;
-    VectorRegister fSplt    = VR8;
-
-    VectorRegister vTmp1    = VR9;
-    VectorRegister vTmp2    = VR10;
-    VectorRegister vTmp3    = VR11;
-    VectorRegister vTmp4    = VR12;
-
-    VectorRegister vLow     = VR13;
-    VectorRegister vHigh    = VR14;
-
-    __ li              (hex, 16);
-    __ li              (fifteen, 15);
-    __ vspltisb        (fSplt, 0x0f);
-
-    // load unaligned from[0-15] to vsRet
-    __ lvx             (vRet, from);
-    __ lvx             (vTmp1, fifteen, from);
-    __ lvsl            (fromPerm, from);
-    __ vxor            (fromPerm, fromPerm, fSplt);
-    __ vperm           (vRet, vRet, vTmp1, fromPerm);
-
-    // load keylen (44 or 52 or 60)
-    __ lwz             (keylen, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT), key);
-
-    // to load keys
-    __ lvsr            (keyPerm, key);
-    __ vxor            (vTmp2, vTmp2, vTmp2);
-    __ vspltisb        (vTmp2, -16);
-    __ vrld            (keyPerm, keyPerm, vTmp2);
-    __ vrld            (keyPerm, keyPerm, vTmp2);
-    __ vsldoi          (keyPerm, keyPerm, keyPerm, -8);
-
-    // load the 1st round key to vKey1
-    __ li              (keypos, 0);
-    __ lvx             (vKey1, keypos, key);
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey1, vTmp1, vKey1, keyPerm);
-
-    // 1st round
-    __ vxor (vRet, vRet, vKey1);
-
-    // load the 2nd round key to vKey1
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey1, vTmp2, vTmp1, keyPerm);
-
-    // load the 3rd round key to vKey2
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey2, vTmp1, vTmp2, keyPerm);
-
-    // load the 4th round key to vKey3
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey3, vTmp2, vTmp1, keyPerm);
-
-    // load the 5th round key to vKey4
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey4, vTmp1, vTmp2, keyPerm);
-
-    // 2nd - 5th rounds
-    __ vcipher (vRet, vRet, vKey1);
-    __ vcipher (vRet, vRet, vKey2);
-    __ vcipher (vRet, vRet, vKey3);
-    __ vcipher (vRet, vRet, vKey4);
-
-    // load the 6th round key to vKey1
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey1, vTmp2, vTmp1, keyPerm);
-
-    // load the 7th round key to vKey2
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey2, vTmp1, vTmp2, keyPerm);
-
-    // load the 8th round key to vKey3
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey3, vTmp2, vTmp1, keyPerm);
-
-    // load the 9th round key to vKey4
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey4, vTmp1, vTmp2, keyPerm);
-
-    // 6th - 9th rounds
-    __ vcipher (vRet, vRet, vKey1);
-    __ vcipher (vRet, vRet, vKey2);
-    __ vcipher (vRet, vRet, vKey3);
-    __ vcipher (vRet, vRet, vKey4);
-
-    // load the 10th round key to vKey1
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey1, vTmp2, vTmp1, keyPerm);
-
-    // load the 11th round key to vKey2
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey2, vTmp1, vTmp2, keyPerm);
-
-    // if all round keys are loaded, skip next 4 rounds
-    __ cmpwi           (CCR0, keylen, 44);
-    __ beq             (CCR0, L_doLast);
-
-    // 10th - 11th rounds
-    __ vcipher (vRet, vRet, vKey1);
-    __ vcipher (vRet, vRet, vKey2);
-
-    // load the 12th round key to vKey1
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey1, vTmp2, vTmp1, keyPerm);
-
-    // load the 13th round key to vKey2
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey2, vTmp1, vTmp2, keyPerm);
-
-    // if all round keys are loaded, skip next 2 rounds
-    __ cmpwi           (CCR0, keylen, 52);
-    __ beq             (CCR0, L_doLast);
-
-    // 12th - 13th rounds
-    __ vcipher (vRet, vRet, vKey1);
-    __ vcipher (vRet, vRet, vKey2);
-
-    // load the 14th round key to vKey1
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey1, vTmp2, vTmp1, keyPerm);
-
-    // load the 15th round key to vKey2
-    __ addi            (keypos, keypos, 16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey2, vTmp1, vTmp2, keyPerm);
-
-    __ bind(L_doLast);
-
-    // last two rounds
-    __ vcipher (vRet, vRet, vKey1);
-    __ vcipherlast (vRet, vRet, vKey2);
-
-    __ neg             (temp, to);
-    __ lvsr            (toPerm, temp);
-    __ vspltisb        (vTmp2, -1);
-    __ vxor            (vTmp1, vTmp1, vTmp1);
-    __ vperm           (vTmp2, vTmp2, vTmp1, toPerm);
-    __ vxor            (toPerm, toPerm, fSplt);
-    __ lvx             (vTmp1, to);
-    __ vperm           (vRet, vRet, vRet, toPerm);
-    __ vsel            (vTmp1, vTmp1, vRet, vTmp2);
-    __ lvx             (vTmp4, fifteen, to);
-    __ stvx            (vTmp1, to);
-    __ vsel            (vRet, vRet, vTmp4, vTmp2);
-    __ stvx            (vRet, fifteen, to);
-
-    __ blr();
-     return start;
-  }
-
-  // Arguments for generated stub (little endian only):
-  //   R3_ARG1   - source byte array address
-  //   R4_ARG2   - destination byte array address
-  //   R5_ARG3   - K (key) in little endian int array
-  address generate_aescrypt_decryptBlock() {
-    assert(UseAES, "need AES instructions and misaligned SSE support");
-    StubCodeMark mark(this, "StubRoutines", "aescrypt_decryptBlock");
-
-    address start = __ function_entry();
-
-    Label L_doLast;
-    Label L_do44;
-    Label L_do52;
-    Label L_do60;
-
-    Register from           = R3_ARG1;  // source array address
-    Register to             = R4_ARG2;  // destination array address
-    Register key            = R5_ARG3;  // round key array
-
-    Register keylen         = R8;
-    Register temp           = R9;
-    Register keypos         = R10;
-    Register hex            = R11;
-    Register fifteen        = R12;
-
-    VectorRegister vRet     = VR0;
-
-    VectorRegister vKey1    = VR1;
-    VectorRegister vKey2    = VR2;
-    VectorRegister vKey3    = VR3;
-    VectorRegister vKey4    = VR4;
-    VectorRegister vKey5    = VR5;
-
-    VectorRegister fromPerm = VR6;
-    VectorRegister keyPerm  = VR7;
-    VectorRegister toPerm   = VR8;
-    VectorRegister fSplt    = VR9;
-
-    VectorRegister vTmp1    = VR10;
-    VectorRegister vTmp2    = VR11;
-    VectorRegister vTmp3    = VR12;
-    VectorRegister vTmp4    = VR13;
-
-    VectorRegister vLow     = VR14;
-    VectorRegister vHigh    = VR15;
-
-    __ li              (hex, 16);
-    __ li              (fifteen, 15);
-    __ vspltisb        (fSplt, 0x0f);
-
-    // load unaligned from[0-15] to vsRet
-    __ lvx             (vRet, from);
-    __ lvx             (vTmp1, fifteen, from);
-    __ lvsl            (fromPerm, from);
-    __ vxor            (fromPerm, fromPerm, fSplt);
-    __ vperm           (vRet, vRet, vTmp1, fromPerm); // align [and byte swap in LE]
-
-    // load keylen (44 or 52 or 60)
-    __ lwz             (keylen, arrayOopDesc::length_offset_in_bytes() - arrayOopDesc::base_offset_in_bytes(T_INT), key);
-
-    // to load keys
-    __ lvsr            (keyPerm, key);
-    __ vxor            (vTmp2, vTmp2, vTmp2);
-    __ vspltisb        (vTmp2, -16);
-    __ vrld            (keyPerm, keyPerm, vTmp2);
-    __ vrld            (keyPerm, keyPerm, vTmp2);
-    __ vsldoi          (keyPerm, keyPerm, keyPerm, -8);
-
-    __ cmpwi           (CCR0, keylen, 44);
-    __ beq             (CCR0, L_do44);
-
-    __ cmpwi           (CCR0, keylen, 52);
-    __ beq             (CCR0, L_do52);
-
-    // load the 15th round key to vKey11
-    __ li              (keypos, 240);
-    __ lvx             (vTmp1, keypos, key);
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey1, vTmp1, vTmp2, keyPerm);
-
-    // load the 14th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey2, vTmp2, vTmp1, keyPerm);
-
-    // load the 13th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey3, vTmp1, vTmp2, keyPerm);
-
-    // load the 12th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey4, vTmp2, vTmp1, keyPerm);
-
-    // load the 11th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey5, vTmp1, vTmp2, keyPerm);
-
-    // 1st - 5th rounds
-    __ vxor            (vRet, vRet, vKey1);
-    __ vncipher        (vRet, vRet, vKey2);
-    __ vncipher        (vRet, vRet, vKey3);
-    __ vncipher        (vRet, vRet, vKey4);
-    __ vncipher        (vRet, vRet, vKey5);
-
-    __ b               (L_doLast);
-
-    __ bind            (L_do52);
-
-    // load the 13th round key to vKey11
-    __ li              (keypos, 208);
-    __ lvx             (vTmp1, keypos, key);
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey1, vTmp1, vTmp2, keyPerm);
-
-    // load the 12th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey2, vTmp2, vTmp1, keyPerm);
-
-    // load the 11th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey3, vTmp1, vTmp2, keyPerm);
-
-    // 1st - 3rd rounds
-    __ vxor            (vRet, vRet, vKey1);
-    __ vncipher        (vRet, vRet, vKey2);
-    __ vncipher        (vRet, vRet, vKey3);
-
-    __ b               (L_doLast);
-
-    __ bind            (L_do44);
-
-    // load the 11th round key to vKey11
-    __ li              (keypos, 176);
-    __ lvx             (vTmp1, keypos, key);
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey1, vTmp1, vTmp2, keyPerm);
-
-    // 1st round
-    __ vxor            (vRet, vRet, vKey1);
-
-    __ bind            (L_doLast);
-
-    // load the 10th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey1, vTmp2, vTmp1, keyPerm);
-
-    // load the 9th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey2, vTmp1, vTmp2, keyPerm);
-
-    // load the 8th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey3, vTmp2, vTmp1, keyPerm);
-
-    // load the 7th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey4, vTmp1, vTmp2, keyPerm);
-
-    // load the 6th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey5, vTmp2, vTmp1, keyPerm);
-
-    // last 10th - 6th rounds
-    __ vncipher        (vRet, vRet, vKey1);
-    __ vncipher        (vRet, vRet, vKey2);
-    __ vncipher        (vRet, vRet, vKey3);
-    __ vncipher        (vRet, vRet, vKey4);
-    __ vncipher        (vRet, vRet, vKey5);
-
-    // load the 5th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey1, vTmp1, vTmp2, keyPerm);
-
-    // load the 4th round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey2, vTmp2, vTmp1, keyPerm);
-
-    // load the 3rd round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey3, vTmp1, vTmp2, keyPerm);
-
-    // load the 2nd round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp1, keypos, key);
-    __ vperm           (vKey4, vTmp2, vTmp1, keyPerm);
-
-    // load the 1st round key to vKey10
-    __ addi            (keypos, keypos, -16);
-    __ lvx             (vTmp2, keypos, key);
-    __ vperm           (vKey5, vTmp1, vTmp2, keyPerm);
-
-    // last 5th - 1th rounds
-    __ vncipher        (vRet, vRet, vKey1);
-    __ vncipher        (vRet, vRet, vKey2);
-    __ vncipher        (vRet, vRet, vKey3);
-    __ vncipher        (vRet, vRet, vKey4);
-    __ vncipherlast    (vRet, vRet, vKey5);
-
-    __ neg             (temp, to);
-    __ lvsr            (toPerm, temp);
-    __ vspltisb        (vTmp2, -1);
-    __ vxor            (vTmp1, vTmp1, vTmp1);
-    __ vperm           (vTmp2, vTmp2, vTmp1, toPerm);
-    __ vxor            (toPerm, toPerm, fSplt);
-    __ lvx             (vTmp1, to);
-    __ vperm           (vRet, vRet, vRet, toPerm);
-    __ vsel            (vTmp1, vTmp1, vRet, vTmp2);
-    __ lvx             (vTmp4, fifteen, to);
-    __ stvx            (vTmp1, to);
-    __ vsel            (vRet, vRet, vTmp4, vTmp2);
-    __ stvx            (vRet, fifteen, to);
-
-    __ blr();
-     return start;
-  }
-
   void generate_arraycopy_stubs() {
     // Note: the disjoint stubs must be generated first, some of
     // the conjoint stubs use them.
@@ -2511,6 +2083,10 @@
     // arraycopy stubs used by compilers
     generate_arraycopy_stubs();
 
+    if (UseAESIntrinsics) {
+      guarantee(!UseAESIntrinsics, "not yet implemented.");
+    }
+
     // Safefetch stubs.
     generate_safefetch("SafeFetch32", sizeof(int),     &StubRoutines::_safefetch32_entry,
                                                        &StubRoutines::_safefetch32_fault_pc,
@@ -2518,12 +2094,6 @@
     generate_safefetch("SafeFetchN", sizeof(intptr_t), &StubRoutines::_safefetchN_entry,
                                                        &StubRoutines::_safefetchN_fault_pc,
                                                        &StubRoutines::_safefetchN_continuation_pc);
-
-    if (UseAESIntrinsics) {
-      StubRoutines::_aescrypt_encryptBlock = generate_aescrypt_encryptBlock();
-      StubRoutines::_aescrypt_decryptBlock = generate_aescrypt_decryptBlock();
-    }
-
   }
 
  public:
diff --git a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp
index d8214a8..1f8375f 100644
--- a/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp
+++ b/hotspot/src/cpu/ppc/vm/vm_version_ppc.cpp
@@ -102,7 +102,7 @@
   // Create and print feature-string.
   char buf[(num_features+1) * 16]; // Max 16 chars per feature.
   jio_snprintf(buf, sizeof(buf),
-               "ppc64%s%s%s%s%s%s%s%s%s",
+               "ppc64%s%s%s%s%s%s%s%s",
                (has_fsqrt()   ? " fsqrt"   : ""),
                (has_isel()    ? " isel"    : ""),
                (has_lxarxeh() ? " lxarxeh" : ""),
@@ -111,8 +111,7 @@
                (has_popcntb() ? " popcntb" : ""),
                (has_popcntw() ? " popcntw" : ""),
                (has_fcfids()  ? " fcfids"  : ""),
-               (has_vand()    ? " vand"    : ""),
-               (has_vcipher() ? " aes"     : "")
+               (has_vand()    ? " vand"    : "")
                // Make sure number of %s matches num_features!
               );
   _features_str = strdup(buf);
@@ -157,28 +156,6 @@
   }
 
   // The AES intrinsic stubs require AES instruction support.
-#if defined(VM_LITTLE_ENDIAN)
-  if (has_vcipher()) {
-    if (FLAG_IS_DEFAULT(UseAES)) {
-      UseAES = true;
-    }
-  } else if (UseAES) {
-    if (!FLAG_IS_DEFAULT(UseAES))
-      warning("AES instructions are not available on this CPU");
-    FLAG_SET_DEFAULT(UseAES, false);
-  }
-
-  if (UseAES && has_vcipher()) {
-    if (FLAG_IS_DEFAULT(UseAESIntrinsics)) {
-      UseAESIntrinsics = true;
-    }
-  } else if (UseAESIntrinsics) {
-    if (!FLAG_IS_DEFAULT(UseAESIntrinsics))
-      warning("AES intrinsics are not available on this CPU");
-    FLAG_SET_DEFAULT(UseAESIntrinsics, false);
-  }
-
-#else
   if (UseAES) {
     warning("AES instructions are not available on this CPU");
     FLAG_SET_DEFAULT(UseAES, false);
@@ -188,7 +165,6 @@
       warning("AES intrinsics are not available on this CPU");
     FLAG_SET_DEFAULT(UseAESIntrinsics, false);
   }
-#endif
 
   if (UseSHA) {
     warning("SHA instructions are not available on this CPU");
@@ -476,7 +452,6 @@
   a->popcntw(R7, R5);                          // code[7] -> popcntw
   a->fcfids(F3, F4);                           // code[8] -> fcfids
   a->vand(VR0, VR0, VR0);                      // code[9] -> vand
-  a->vcipher(VR0, VR1, VR2);                   // code[10] -> vcipher
   a->blr();
 
   // Emit function to set one cache line to zero. Emit function descriptor and get pointer to it.
@@ -520,7 +495,6 @@
   if (code[feature_cntr++]) features |= popcntw_m;
   if (code[feature_cntr++]) features |= fcfids_m;
   if (code[feature_cntr++]) features |= vand_m;
-  if (code[feature_cntr++]) features |= vcipher_m;
 
   // Print the detection code.
   if (PrintAssembly) {
diff --git a/hotspot/src/cpu/ppc/vm/vm_version_ppc.hpp b/hotspot/src/cpu/ppc/vm/vm_version_ppc.hpp
index d7839b4..2bbfddd 100644
--- a/hotspot/src/cpu/ppc/vm/vm_version_ppc.hpp
+++ b/hotspot/src/cpu/ppc/vm/vm_version_ppc.hpp
@@ -42,7 +42,6 @@
     fcfids,
     vand,
     dcba,
-    vcipher,
     num_features // last entry to count features
   };
   enum Feature_Flag_Set {
@@ -57,7 +56,6 @@
     fcfids_m              = (1 << fcfids ),
     vand_m                = (1 << vand   ),
     dcba_m                = (1 << dcba   ),
-    vcipher_m             = (1 << vcipher),
     all_features_m        = -1
   };
   static int  _features;
@@ -85,7 +83,6 @@
   static bool has_fcfids()  { return (_features & fcfids_m) != 0; }
   static bool has_vand()    { return (_features & vand_m) != 0; }
   static bool has_dcba()    { return (_features & dcba_m) != 0; }
-  static bool has_vcipher() { return (_features & vcipher_m) != 0; }
 
   static const char* cpu_features() { return _features_str; }
 
diff --git a/hotspot/src/cpu/sparc/vm/c1_CodeStubs_sparc.cpp b/hotspot/src/cpu/sparc/vm/c1_CodeStubs_sparc.cpp
index 7c6a1d7..8584037 100644
--- a/hotspot/src/cpu/sparc/vm/c1_CodeStubs_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/c1_CodeStubs_sparc.cpp
@@ -431,9 +431,6 @@
   __ mov(length()->as_register(),  O4);
 
   ce->emit_static_call_stub();
-  if (ce->compilation()->bailed_out()) {
-    return; // CodeCache is full
-  }
 
   __ call(SharedRuntime::get_resolve_static_call_stub(), relocInfo::static_call_type);
   __ delayed()->nop();
diff --git a/hotspot/src/cpu/sparc/vm/compiledIC_sparc.cpp b/hotspot/src/cpu/sparc/vm/compiledIC_sparc.cpp
index 5429e33..dee64df 100644
--- a/hotspot/src/cpu/sparc/vm/compiledIC_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/compiledIC_sparc.cpp
@@ -53,7 +53,7 @@
 // ----------------------------------------------------------------------------
 
 #define __ _masm.
-address CompiledStaticCall::emit_to_interp_stub(CodeBuffer &cbuf) {
+void CompiledStaticCall::emit_to_interp_stub(CodeBuffer &cbuf) {
 #ifdef COMPILER2
   // Stub is fixed up when the corresponding call is converted from calling
   // compiled code to calling interpreted code.
@@ -64,10 +64,9 @@
 
   MacroAssembler _masm(&cbuf);
 
-  address base = __ start_a_stub(to_interp_stub_size());
-  if (base == NULL) {
-    return NULL;  // CodeBuffer::expand failed.
-  }
+  address base =
+  __ start_a_stub(to_interp_stub_size()*2);
+  if (base == NULL) return;  // CodeBuffer::expand failed.
 
   // Static stub relocation stores the instruction address of the call.
   __ relocate(static_stub_Relocation::spec(mark));
@@ -82,7 +81,6 @@
 
   // Update current stubs pointer and restore code_end.
   __ end_a_stub();
-  return base;
 #else
   ShouldNotReachHere();
 #endif
diff --git a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp
index 4dfc1db..d7396f6 100644
--- a/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/macroAssembler_sparc.cpp
@@ -4261,7 +4261,6 @@
   assert(UseBlockZeroing && VM_Version::has_block_zeroing(), "only works with BIS zeroing");
   Register end = count;
   int cache_line_size = VM_Version::prefetch_data_size();
-  assert(cache_line_size > 0, "cache line size should be known for this code");
   // Minimum count when BIS zeroing can be used since
   // it needs membar which is expensive.
   int block_zero_size  = MAX2(cache_line_size*3, (int)BlockZeroingLowLimit);
diff --git a/hotspot/src/cpu/sparc/vm/nativeInst_sparc.cpp b/hotspot/src/cpu/sparc/vm/nativeInst_sparc.cpp
index 413cfe2..f5ac37c 100644
--- a/hotspot/src/cpu/sparc/vm/nativeInst_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/nativeInst_sparc.cpp
@@ -64,7 +64,7 @@
   masm.patchable_sethi(x, destreg);
   int len = buffer - masm.pc();
   for (int i = 0; i < len; i++) {
-    guarantee(instaddr[i] == buffer[i], "instructions must match");
+    assert(instaddr[i] == buffer[i], "instructions must match");
   }
 }
 
diff --git a/hotspot/src/cpu/sparc/vm/relocInfo_sparc.cpp b/hotspot/src/cpu/sparc/vm/relocInfo_sparc.cpp
index 4900e14..e132c42 100644
--- a/hotspot/src/cpu/sparc/vm/relocInfo_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/relocInfo_sparc.cpp
@@ -83,7 +83,7 @@
     inst &= ~Assembler::simm(    -1, 13);
     inst |=  Assembler::simm(simm13, 13);
     if (verify_only) {
-      guarantee(ip->long_at(0) == inst, "instructions must match");
+      assert(ip->long_at(0) == inst, "instructions must match");
     } else {
       ip->set_long_at(0, inst);
     }
@@ -101,15 +101,15 @@
       inst &= ~Assembler::hi22(-1);
       inst |=  Assembler::hi22((intptr_t)np);
       if (verify_only) {
-        guarantee(ip->long_at(0) == inst, "instructions must match");
+        assert(ip->long_at(0) == inst, "instructions must match");
       } else {
         ip->set_long_at(0, inst);
       }
       inst2 = ip->long_at( NativeInstruction::nop_instruction_size );
       guarantee(Assembler::inv_op(inst2)==Assembler::arith_op, "arith op");
       if (verify_only) {
-        guarantee(ip->long_at(NativeInstruction::nop_instruction_size) == NativeInstruction::set_data32_simm13( inst2, (intptr_t)np),
-                  "instructions must match");
+        assert(ip->long_at(NativeInstruction::nop_instruction_size) == NativeInstruction::set_data32_simm13( inst2, (intptr_t)np),
+               "instructions must match");
       } else {
         ip->set_long_at(NativeInstruction::nop_instruction_size, NativeInstruction::set_data32_simm13( inst2, (intptr_t)np));
       }
@@ -126,7 +126,7 @@
     inst |=  Assembler::hi22((intptr_t)x);
     // (ignore offset; it doesn't play into the sethi)
     if (verify_only) {
-      guarantee(ip->long_at(0) == inst, "instructions must match");
+      assert(ip->long_at(0) == inst, "instructions must match");
     } else {
       ip->set_long_at(0, inst);
     }
diff --git a/hotspot/src/cpu/sparc/vm/sparc.ad b/hotspot/src/cpu/sparc/vm/sparc.ad
index 0b46f32..3d43f6b 100644
--- a/hotspot/src/cpu/sparc/vm/sparc.ad
+++ b/hotspot/src/cpu/sparc/vm/sparc.ad
@@ -1775,11 +1775,9 @@
   AddressLiteral exception_blob(OptoRuntime::exception_blob()->entry_point());
   MacroAssembler _masm(&cbuf);
 
-  address base = __ start_a_stub(size_exception_handler());
-  if (base == NULL) {
-    ciEnv::current()->record_failure("CodeCache is full");
-    return 0;  // CodeBuffer::expand failed
-  }
+  address base =
+  __ start_a_stub(size_exception_handler());
+  if (base == NULL)  return 0;  // CodeBuffer::expand failed
 
   int offset = __ offset();
 
@@ -1800,11 +1798,9 @@
   AddressLiteral deopt_blob(SharedRuntime::deopt_blob()->unpack());
   MacroAssembler _masm(&cbuf);
 
-  address base = __ start_a_stub(size_deopt_handler());
-  if (base == NULL) {
-    ciEnv::current()->record_failure("CodeCache is full");
-    return 0;  // CodeBuffer::expand failed
-  }
+  address base =
+  __ start_a_stub(size_deopt_handler());
+  if (base == NULL)  return 0;  // CodeBuffer::expand failed
 
   int offset = __ offset();
   __ save_frame(0);
@@ -2605,12 +2601,7 @@
       emit_call_reloc(cbuf, $meth$$method, relocInfo::static_call_type);
     }
     if (_method) {  // Emit stub for static call.
-      address stub = CompiledStaticCall::emit_to_interp_stub(cbuf);
-      // Stub does not fit into scratch buffer if TraceJumps is enabled
-      if (stub == NULL && !(TraceJumps && Compile::current()->in_scratch_emit_size())) {
-        ciEnv::current()->record_failure("CodeCache is full");
-        return;
-      } 
+      CompiledStaticCall::emit_to_interp_stub(cbuf);
     }
   %}
 
diff --git a/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp b/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp
index b14a6e9..72e98c6 100644
--- a/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp
+++ b/hotspot/src/cpu/sparc/vm/vm_version_sparc.cpp
@@ -74,7 +74,7 @@
     AllocatePrefetchDistance = AllocatePrefetchStepSize;
   }
 
-  if (AllocatePrefetchStyle == 3 && (!has_blk_init() || cache_line_size <= 0)) {
+  if (AllocatePrefetchStyle == 3 && !has_blk_init()) {
     warning("BIS instructions are not available on this CPU");
     FLAG_SET_DEFAULT(AllocatePrefetchStyle, 1);
   }
@@ -138,7 +138,7 @@
       FLAG_SET_DEFAULT(InteriorEntryAlignment, 4);
     }
     if (is_niagara_plus()) {
-      if (has_blk_init() && (cache_line_size > 0) && UseTLAB &&
+      if (has_blk_init() && UseTLAB &&
           FLAG_IS_DEFAULT(AllocatePrefetchInstr)) {
         // Use BIS instruction for TLAB allocation prefetch.
         FLAG_SET_ERGO(intx, AllocatePrefetchInstr, 1);
diff --git a/hotspot/src/cpu/x86/vm/c1_CodeStubs_x86.cpp b/hotspot/src/cpu/x86/vm/c1_CodeStubs_x86.cpp
index b96cb13..a6e7731 100644
--- a/hotspot/src/cpu/x86/vm/c1_CodeStubs_x86.cpp
+++ b/hotspot/src/cpu/x86/vm/c1_CodeStubs_x86.cpp
@@ -502,9 +502,6 @@
   ce->align_call(lir_static_call);
 
   ce->emit_static_call_stub();
-  if (ce->compilation()->bailed_out()) {
-    return; // CodeCache is full
-  }
   AddressLiteral resolve(SharedRuntime::get_resolve_static_call_stub(),
                          relocInfo::static_call_type);
   __ call(resolve);
diff --git a/hotspot/src/cpu/x86/vm/compiledIC_x86.cpp b/hotspot/src/cpu/x86/vm/compiledIC_x86.cpp
index 29eba2f..9537ef9 100644
--- a/hotspot/src/cpu/x86/vm/compiledIC_x86.cpp
+++ b/hotspot/src/cpu/x86/vm/compiledIC_x86.cpp
@@ -50,7 +50,7 @@
 // ----------------------------------------------------------------------------
 
 #define __ _masm.
-address CompiledStaticCall::emit_to_interp_stub(CodeBuffer &cbuf) {
+void CompiledStaticCall::emit_to_interp_stub(CodeBuffer &cbuf) {
   // Stub is fixed up when the corresponding call is converted from
   // calling compiled code to calling interpreted code.
   // movq rbx, 0
@@ -62,10 +62,9 @@
   // That's why we must use the macroassembler to generate a stub.
   MacroAssembler _masm(&cbuf);
 
-  address base = __ start_a_stub(to_interp_stub_size());
-  if (base == NULL) {
-    return NULL;  // CodeBuffer::expand failed.
-  }
+  address base =
+  __ start_a_stub(to_interp_stub_size()*2);
+  if (base == NULL) return;  // CodeBuffer::expand failed.
   // Static stub relocation stores the instruction address of the call.
   __ relocate(static_stub_Relocation::spec(mark), Assembler::imm_operand);
   // Static stub relocation also tags the Method* in the code-stream.
@@ -75,7 +74,6 @@
 
   // Update current stubs pointer and restore insts_end.
   __ end_a_stub();
-  return base;
 }
 #undef __
 
diff --git a/hotspot/src/cpu/x86/vm/relocInfo_x86.cpp b/hotspot/src/cpu/x86/vm/relocInfo_x86.cpp
index 918b6f2..14868cb 100644
--- a/hotspot/src/cpu/x86/vm/relocInfo_x86.cpp
+++ b/hotspot/src/cpu/x86/vm/relocInfo_x86.cpp
@@ -40,7 +40,7 @@
          which == Assembler::imm_operand, "format unpacks ok");
   if (which == Assembler::imm_operand) {
     if (verify_only) {
-      guarantee(*pd_address_in_code() == x, "instructions must match");
+      assert(*pd_address_in_code() == x, "instructions must match");
     } else {
       *pd_address_in_code() = x;
     }
@@ -49,13 +49,13 @@
     // both compressed oops and compressed classes look the same
     if (Universe::heap()->is_in_reserved((oop)x)) {
     if (verify_only) {
-      guarantee(*(uint32_t*) disp == oopDesc::encode_heap_oop((oop)x), "instructions must match");
+      assert(*(uint32_t*) disp == oopDesc::encode_heap_oop((oop)x), "instructions must match");
     } else {
       *(int32_t*) disp = oopDesc::encode_heap_oop((oop)x);
     }
   } else {
       if (verify_only) {
-        guarantee(*(uint32_t*) disp == Klass::encode_klass((Klass*)x), "instructions must match");
+        assert(*(uint32_t*) disp == Klass::encode_klass((Klass*)x), "instructions must match");
       } else {
         *(int32_t*) disp = Klass::encode_klass((Klass*)x);
       }
@@ -66,14 +66,14 @@
     address disp = Assembler::locate_operand(ip, which);
     address next_ip = Assembler::locate_next_instruction(ip);
     if (verify_only) {
-      guarantee(*(int32_t*) disp == (x - next_ip), "instructions must match");
+      assert(*(int32_t*) disp == (x - next_ip), "instructions must match");
     } else {
       *(int32_t*) disp = x - next_ip;
     }
   }
 #else
   if (verify_only) {
-    guarantee(*pd_address_in_code() == (x + o), "instructions must match");
+    assert(*pd_address_in_code() == (x + o), "instructions must match");
   } else {
     *pd_address_in_code() = x + o;
   }
diff --git a/hotspot/src/cpu/x86/vm/vm_version_x86.cpp b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp
index 134fa24..28aa48e 100644
--- a/hotspot/src/cpu/x86/vm/vm_version_x86.cpp
+++ b/hotspot/src/cpu/x86/vm/vm_version_x86.cpp
@@ -704,16 +704,16 @@
     UseMultiplyToLenIntrinsic = true;
   }
   if (FLAG_IS_DEFAULT(UseSquareToLenIntrinsic)) {
-    UseSquareToLenIntrinsic = true;
+    UseSquareToLenIntrinsic = false;
   }
   if (FLAG_IS_DEFAULT(UseMulAddIntrinsic)) {
-    UseMulAddIntrinsic = true;
+    UseMulAddIntrinsic = false;
   }
   if (FLAG_IS_DEFAULT(UseMontgomeryMultiplyIntrinsic)) {
-    UseMontgomeryMultiplyIntrinsic = true;
+    UseMontgomeryMultiplyIntrinsic = false;
   }
   if (FLAG_IS_DEFAULT(UseMontgomerySquareIntrinsic)) {
-    UseMontgomerySquareIntrinsic = true;
+    UseMontgomerySquareIntrinsic = false;
   }
 #else
   if (UseMultiplyToLenIntrinsic) {
diff --git a/hotspot/src/cpu/x86/vm/x86.ad b/hotspot/src/cpu/x86/vm/x86.ad
index 4e2499a..8d402c1 100644
--- a/hotspot/src/cpu/x86/vm/x86.ad
+++ b/hotspot/src/cpu/x86/vm/x86.ad
@@ -550,10 +550,7 @@
   // That's why we must use the macroassembler to generate a handler.
   MacroAssembler _masm(&cbuf);
   address base = __ start_a_stub(size_exception_handler());
-  if (base == NULL) {
-    ciEnv::current()->record_failure("CodeCache is full");
-    return 0;  // CodeBuffer::expand failed
-  }
+  if (base == NULL)  return 0;  // CodeBuffer::expand failed
   int offset = __ offset();
   __ jump(RuntimeAddress(OptoRuntime::exception_blob()->entry_point()));
   assert(__ offset() - offset <= (int) size_exception_handler(), "overflow");
@@ -568,10 +565,7 @@
   // That's why we must use the macroassembler to generate a handler.
   MacroAssembler _masm(&cbuf);
   address base = __ start_a_stub(size_deopt_handler());
-  if (base == NULL) {
-    ciEnv::current()->record_failure("CodeCache is full");
-    return 0;  // CodeBuffer::expand failed
-  }
+  if (base == NULL)  return 0;  // CodeBuffer::expand failed
   int offset = __ offset();
 
 #ifdef _LP64
diff --git a/hotspot/src/cpu/x86/vm/x86_32.ad b/hotspot/src/cpu/x86/vm/x86_32.ad
index 512ec20..42aba5b 100644
--- a/hotspot/src/cpu/x86/vm/x86_32.ad
+++ b/hotspot/src/cpu/x86/vm/x86_32.ad
@@ -1870,11 +1870,7 @@
                      static_call_Relocation::spec(), RELOC_IMM32 );
     }
     if (_method) {  // Emit stub for static call.
-      address stub = CompiledStaticCall::emit_to_interp_stub(cbuf);
-      if (stub == NULL) {
-        ciEnv::current()->record_failure("CodeCache is full");
-        return;
-      } 
+      CompiledStaticCall::emit_to_interp_stub(cbuf);
     }
   %}
 
diff --git a/hotspot/src/cpu/x86/vm/x86_64.ad b/hotspot/src/cpu/x86/vm/x86_64.ad
index ed304df..52bc635 100644
--- a/hotspot/src/cpu/x86/vm/x86_64.ad
+++ b/hotspot/src/cpu/x86/vm/x86_64.ad
@@ -2125,11 +2125,7 @@
     }
     if (_method) {
       // Emit stub for static call.
-      address stub = CompiledStaticCall::emit_to_interp_stub(cbuf);
-      if (stub == NULL) {
-        ciEnv::current()->record_failure("CodeCache is full");
-        return;
-      } 
+      CompiledStaticCall::emit_to_interp_stub(cbuf);
     }
   %}
 
diff --git a/hotspot/src/cpu/zero/vm/compiledIC_zero.cpp b/hotspot/src/cpu/zero/vm/compiledIC_zero.cpp
index 185a8b1..143dc31 100644
--- a/hotspot/src/cpu/zero/vm/compiledIC_zero.cpp
+++ b/hotspot/src/cpu/zero/vm/compiledIC_zero.cpp
@@ -60,9 +60,8 @@
 
 // ----------------------------------------------------------------------------
 
-address CompiledStaticCall::emit_to_interp_stub(CodeBuffer &cbuf) {
+void CompiledStaticCall::emit_to_interp_stub(CodeBuffer &cbuf) {
   ShouldNotReachHere(); // Only needed for COMPILER2.
-  return NULL;
 }
 
 int CompiledStaticCall::to_interp_stub_size() {
diff --git a/hotspot/src/cpu/zero/vm/cppInterpreter_zero.cpp b/hotspot/src/cpu/zero/vm/cppInterpreter_zero.cpp
index 242ce1c..15cfc86 100644
--- a/hotspot/src/cpu/zero/vm/cppInterpreter_zero.cpp
+++ b/hotspot/src/cpu/zero/vm/cppInterpreter_zero.cpp
@@ -220,16 +220,9 @@
   // Push our result
   for (int i = 0; i < result_slots; i++) {
     // Adjust result to smaller
-    union {
-      intptr_t res;
-      jint res_jint;
-    };
-    res = result[-i];
+    intptr_t res = result[-i];
     if (result_slots == 1) {
-      BasicType t = method->result_type();
-      if (is_subword_type(t)) {
-        res_jint = (jint)narrow(t, res_jint);
-      }
+      res = narrow(method->result_type(), res);
     }
     stack->push(res);
   }
diff --git a/hotspot/src/os/linux/vm/globals_linux.hpp b/hotspot/src/os/linux/vm/globals_linux.hpp
index 32d4619..83424f2 100644
--- a/hotspot/src/os/linux/vm/globals_linux.hpp
+++ b/hotspot/src/os/linux/vm/globals_linux.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 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
@@ -47,10 +47,7 @@
           "Load DLLs with executable-stack attribute in the VM Thread") \
                                                                         \
   product(bool, UseSHM, false,                                          \
-          "Use SYSV shared memory for large pages")                     \
-                                                                        \
-  diagnostic(bool, PrintActiveCpus, false,                              \
-          "Print the number of CPUs detected in os::active_processor_count")
+          "Use SYSV shared memory for large pages")
 
 //
 // Defines Linux-specific default values. The flags are available on all
diff --git a/hotspot/src/os/linux/vm/os_linux.cpp b/hotspot/src/os/linux/vm/os_linux.cpp
index 292d478..c59b702 100644
--- a/hotspot/src/os/linux/vm/os_linux.cpp
+++ b/hotspot/src/os/linux/vm/os_linux.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 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
@@ -104,14 +104,6 @@
 
 PRAGMA_FORMAT_MUTE_WARNINGS_FOR_GCC
 
-#ifndef _GNU_SOURCE
-  #define _GNU_SOURCE
-  #include <sched.h>
-  #undef _GNU_SOURCE
-#else
-  #include <sched.h>
-#endif
-
 // if RUSAGE_THREAD for getrusage() has not been defined, do it here. The code calling
 // getrusage() is prepared to handle the associated failure.
 #ifndef RUSAGE_THREAD
@@ -2854,7 +2846,7 @@
                               // in the library.
   const size_t BitsPerCLong = sizeof(long) * CHAR_BIT;
 
-  size_t cpu_num = processor_count();
+  size_t cpu_num = os::active_processor_count();
   size_t cpu_map_size = NCPUS / BitsPerCLong;
   size_t cpu_map_valid_size =
     MIN2((cpu_num + BitsPerCLong - 1) / BitsPerCLong, cpu_map_size);
@@ -3055,48 +3047,6 @@
   return addr == MAP_FAILED ? NULL : addr;
 }
 
-// Allocate (using mmap, NO_RESERVE, with small pages) at either a given request address
-//   (req_addr != NULL) or with a given alignment.
-//  - bytes shall be a multiple of alignment.
-//  - req_addr can be NULL. If not NULL, it must be a multiple of alignment.
-//  - alignment sets the alignment at which memory shall be allocated.
-//     It must be a multiple of allocation granularity.
-// Returns address of memory or NULL. If req_addr was not NULL, will only return
-//  req_addr or NULL.
-static char* anon_mmap_aligned(size_t bytes, size_t alignment, char* req_addr) {
-
-  size_t extra_size = bytes;
-  if (req_addr == NULL && alignment > 0) {
-    extra_size += alignment;
-  }
-
-  char* start = (char*) ::mmap(req_addr, extra_size, PROT_NONE,
-    MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
-    -1, 0);
-  if (start == MAP_FAILED) {
-    start = NULL;
-  } else {
-    if (req_addr != NULL) {
-      if (start != req_addr) {
-        ::munmap(start, extra_size);
-        start = NULL;
-      }
-    } else {
-      char* const start_aligned = (char*) align_ptr_up(start, alignment);
-      char* const end_aligned = start_aligned + bytes;
-      char* const end = start + extra_size;
-      if (start_aligned > start) {
-        ::munmap(start, start_aligned - start);
-      }
-      if (end_aligned < end) {
-        ::munmap(end_aligned, end - end_aligned);
-      }
-      start = start_aligned;
-    }
-  }
-  return start;
-}
-
 // Don't update _highest_vm_reserved_address, because there might be memory
 // regions above addr + size. If so, releasing a memory region only creates
 // a hole in the address space, it doesn't help prevent heap-stack collision.
@@ -3381,133 +3331,54 @@
 #define SHM_HUGETLB 04000
 #endif
 
-#define shm_warning_format(format, ...)              \
-  do {                                               \
-    if (UseLargePages &&                             \
-        (!FLAG_IS_DEFAULT(UseLargePages) ||          \
-         !FLAG_IS_DEFAULT(UseSHM) ||                 \
-         !FLAG_IS_DEFAULT(LargePageSizeInBytes))) {  \
-      warning(format, __VA_ARGS__);                  \
-    }                                                \
-  } while (0)
-
-#define shm_warning(str) shm_warning_format("%s", str)
-
-#define shm_warning_with_errno(str)                \
-  do {                                             \
-    int err = errno;                               \
-    shm_warning_format(str " (error = %d)", err);  \
-  } while (0)
-
-static char* shmat_with_alignment(int shmid, size_t bytes, size_t alignment) {
-  assert(is_size_aligned(bytes, alignment), "Must be divisible by the alignment");
-
-  if (!is_size_aligned(alignment, SHMLBA)) {
-    assert(false, "Code below assumes that alignment is at least SHMLBA aligned");
-    return NULL;
-  }
-
-  // To ensure that we get 'alignment' aligned memory from shmat,
-  // we pre-reserve aligned virtual memory and then attach to that.
-
-  char* pre_reserved_addr = anon_mmap_aligned(bytes, alignment, NULL);
-  if (pre_reserved_addr == NULL) {
-    // Couldn't pre-reserve aligned memory.
-    shm_warning("Failed to pre-reserve aligned memory for shmat.");
-    return NULL;
-  }
-
-  // SHM_REMAP is needed to allow shmat to map over an existing mapping.
-  char* addr = (char*)shmat(shmid, pre_reserved_addr, SHM_REMAP);
-
-  if ((intptr_t)addr == -1) {
-    int err = errno;
-    shm_warning_with_errno("Failed to attach shared memory.");
-
-    assert(err != EACCES, "Unexpected error");
-    assert(err != EIDRM,  "Unexpected error");
-    assert(err != EINVAL, "Unexpected error");
-
-    // Since we don't know if the kernel unmapped the pre-reserved memory area
-    // we can't unmap it, since that would potentially unmap memory that was
-    // mapped from other threads.
-    return NULL;
-  }
-
-  return addr;
-}
-
-static char* shmat_at_address(int shmid, char* req_addr) {
-  if (!is_ptr_aligned(req_addr, SHMLBA)) {
-    assert(false, "Requested address needs to be SHMLBA aligned");
-    return NULL;
-  }
-
-  char* addr = (char*)shmat(shmid, req_addr, 0);
-
-  if ((intptr_t)addr == -1) {
-    shm_warning_with_errno("Failed to attach shared memory.");
-    return NULL;
-  }
-
-  return addr;
-}
-
-static char* shmat_large_pages(int shmid, size_t bytes, size_t alignment, char* req_addr) {
-  // If a req_addr has been provided, we assume that the caller has already aligned the address.
-  if (req_addr != NULL) {
-    assert(is_ptr_aligned(req_addr, os::large_page_size()), "Must be divisible by the large page size");
-    assert(is_ptr_aligned(req_addr, alignment), "Must be divisible by given alignment");
-    return shmat_at_address(shmid, req_addr);
-  }
-
-  // Since shmid has been setup with SHM_HUGETLB, shmat will automatically
-  // return large page size aligned memory addresses when req_addr == NULL.
-  // However, if the alignment is larger than the large page size, we have
-  // to manually ensure that the memory returned is 'alignment' aligned.
-  if (alignment > os::large_page_size()) {
-    assert(is_size_aligned(alignment, os::large_page_size()), "Must be divisible by the large page size");
-    return shmat_with_alignment(shmid, bytes, alignment);
-  } else {
-    return shmat_at_address(shmid, NULL);
-  }
-}
-
 char* os::Linux::reserve_memory_special_shm(size_t bytes, size_t alignment, char* req_addr, bool exec) {
   // "exec" is passed in but not used.  Creating the shared image for
   // the code cache doesn't have an SHM_X executable permission to check.
   assert(UseLargePages && UseSHM, "only for SHM large pages");
   assert(is_ptr_aligned(req_addr, os::large_page_size()), "Unaligned address");
-  assert(is_ptr_aligned(req_addr, alignment), "Unaligned address");
 
-  if (!is_size_aligned(bytes, os::large_page_size())) {
+  if (!is_size_aligned(bytes, os::large_page_size()) || alignment > os::large_page_size()) {
     return NULL; // Fallback to small pages.
   }
 
+  key_t key = IPC_PRIVATE;
+  char *addr;
+
+  bool warn_on_failure = UseLargePages &&
+                        (!FLAG_IS_DEFAULT(UseLargePages) ||
+                         !FLAG_IS_DEFAULT(UseSHM) ||
+                         !FLAG_IS_DEFAULT(LargePageSizeInBytes)
+                        );
+  char msg[128];
+
   // Create a large shared memory region to attach to based on size.
-  // Currently, size is the total size of the heap.
-  int shmid = shmget(IPC_PRIVATE, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);
+  // Currently, size is the total size of the heap
+  int shmid = shmget(key, bytes, SHM_HUGETLB|IPC_CREAT|SHM_R|SHM_W);
   if (shmid == -1) {
-    // Possible reasons for shmget failure:
-    // 1. shmmax is too small for Java heap.
-    //    > check shmmax value: cat /proc/sys/kernel/shmmax
-    //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
-    // 2. not enough large page memory.
-    //    > check available large pages: cat /proc/meminfo
-    //    > increase amount of large pages:
-    //          echo new_value > /proc/sys/vm/nr_hugepages
-    //      Note 1: different Linux may use different name for this property,
-    //            e.g. on Redhat AS-3 it is "hugetlb_pool".
-    //      Note 2: it's possible there's enough physical memory available but
-    //            they are so fragmented after a long run that they can't
-    //            coalesce into large pages. Try to reserve large pages when
-    //            the system is still "fresh".
-    shm_warning_with_errno("Failed to reserve shared memory.");
-    return NULL;
+     // Possible reasons for shmget failure:
+     // 1. shmmax is too small for Java heap.
+     //    > check shmmax value: cat /proc/sys/kernel/shmmax
+     //    > increase shmmax value: echo "0xffffffff" > /proc/sys/kernel/shmmax
+     // 2. not enough large page memory.
+     //    > check available large pages: cat /proc/meminfo
+     //    > increase amount of large pages:
+     //          echo new_value > /proc/sys/vm/nr_hugepages
+     //      Note 1: different Linux may use different name for this property,
+     //            e.g. on Redhat AS-3 it is "hugetlb_pool".
+     //      Note 2: it's possible there's enough physical memory available but
+     //            they are so fragmented after a long run that they can't
+     //            coalesce into large pages. Try to reserve large pages when
+     //            the system is still "fresh".
+     if (warn_on_failure) {
+       jio_snprintf(msg, sizeof(msg), "Failed to reserve shared memory (errno = %d).", errno);
+       warning("%s", msg);
+     }
+     return NULL;
   }
 
-  // Attach to the region.
-  char* addr = shmat_large_pages(shmid, bytes, alignment, req_addr);
+  // attach to the region
+  addr = (char*)shmat(shmid, req_addr, 0);
+  int err = errno;
 
   // Remove shmid. If shmat() is successful, the actual shared memory segment
   // will be deleted when it's detached by shmdt() or when the process
@@ -3515,6 +3386,14 @@
   // segment immediately.
   shmctl(shmid, IPC_RMID, NULL);
 
+  if ((intptr_t)addr == -1) {
+     if (warn_on_failure) {
+       jio_snprintf(msg, sizeof(msg), "Failed to attach shared memory (errno = %d).", err);
+       warning("%s", msg);
+     }
+     return NULL;
+  }
+
   return addr;
 }
 
@@ -3554,22 +3433,22 @@
   return addr;
 }
 
-// Reserve memory using mmap(MAP_HUGETLB).
-//  - bytes shall be a multiple of alignment.
-//  - req_addr can be NULL. If not NULL, it must be a multiple of alignment.
-//  - alignment sets the alignment at which memory shall be allocated.
-//     It must be a multiple of allocation granularity.
-// Returns address of memory or NULL. If req_addr was not NULL, will only return
-//  req_addr or NULL.
 char* os::Linux::reserve_memory_special_huge_tlbfs_mixed(size_t bytes, size_t alignment, char* req_addr, bool exec) {
   size_t large_page_size = os::large_page_size();
+
   assert(bytes >= large_page_size, "Shouldn't allocate large pages for small sizes");
 
-  assert(is_ptr_aligned(req_addr, alignment), "Must be");
-  assert(is_size_aligned(bytes, alignment), "Must be");
+  // Allocate small pages.
 
-  // First reserve - but not commit - the address range in small pages.
-  char* const start = anon_mmap_aligned(bytes, alignment, req_addr);
+  char* start;
+  if (req_addr != NULL) {
+    assert(is_ptr_aligned(req_addr, alignment), "Must be");
+    assert(is_size_aligned(bytes, alignment), "Must be");
+    start = os::reserve_memory(bytes, req_addr);
+    assert(start == NULL || start == req_addr, "Must be");
+  } else {
+    start = os::reserve_memory_aligned(bytes, alignment);
+  }
 
   if (start == NULL) {
     return NULL;
@@ -3577,6 +3456,13 @@
 
   assert(is_ptr_aligned(start, alignment), "Must be");
 
+  if (MemTracker::tracking_level() > NMT_minimal) {
+    // os::reserve_memory_special will record this memory area.
+    // Need to release it here to prevent overlapping reservations.
+    Tracker tkr = MemTracker::get_virtual_memory_release_tracker();
+    tkr.record((address)start, bytes);
+  }
+
   char* end = start + bytes;
 
   // Find the regions of the allocated chunk that can be promoted to large pages.
@@ -3596,9 +3482,9 @@
 
   int prot = exec ? PROT_READ|PROT_WRITE|PROT_EXEC : PROT_READ|PROT_WRITE;
 
+
   void* result;
 
-  // Commit small-paged leading area.
   if (start != lp_start) {
     result = ::mmap(start, lp_start - start, prot,
                     MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED,
@@ -3609,12 +3495,11 @@
     }
   }
 
-  // Commit large-paged area.
   result = ::mmap(lp_start, lp_bytes, prot,
                   MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED|MAP_HUGETLB,
                   -1, 0);
   if (result == MAP_FAILED) {
-    warn_on_large_pages_failure(lp_start, lp_bytes, errno);
+    warn_on_large_pages_failure(req_addr, bytes, errno);
     // If the mmap above fails, the large pages region will be unmapped and we
     // have regions before and after with small pages. Release these regions.
     //
@@ -3627,7 +3512,6 @@
     return NULL;
   }
 
-  // Commit small-paged trailing area.
   if (lp_end != end) {
       result = ::mmap(lp_end, end - lp_end, prot,
                       MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED,
@@ -3644,7 +3528,7 @@
 char* os::Linux::reserve_memory_special_huge_tlbfs(size_t bytes, size_t alignment, char* req_addr, bool exec) {
   assert(UseLargePages && UseHugeTLBFS, "only for Huge TLBFS large pages");
   assert(is_ptr_aligned(req_addr, alignment), "Must be");
-  assert(is_size_aligned(alignment, os::vm_allocation_granularity()), "Must be");
+  assert(is_power_of_2(alignment), "Must be");
   assert(is_power_of_2(os::large_page_size()), "Must be");
   assert(bytes >= os::large_page_size(), "Shouldn't allocate large pages for small sizes");
 
@@ -5024,42 +4908,12 @@
   }
 };
 
-static int os_cpu_count(const cpu_set_t* cpus) {
-  int count = 0;
-  // only look up to the number of configured processors
-  for (int i = 0; i < os::processor_count(); i++) {
-    if (CPU_ISSET(i, cpus)) {
-      count++;
-    }
-  }
-  return count;
-}
-
-// Get the current number of available processors for this process.
-// This value can change at any time during a process's lifetime.
-// sched_getaffinity gives an accurate answer as it accounts for cpusets.
-// If anything goes wrong we fallback to returning the number of online
-// processors - which can be greater than the number available to the process.
 int os::active_processor_count() {
-  cpu_set_t cpus;  // can represent at most 1024 (CPU_SETSIZE) processors
-  int cpus_size = sizeof(cpu_set_t);
-  int cpu_count = 0;
-
-  // pid 0 means the current thread - which we have to assume represents the process
-  if (sched_getaffinity(0, cpus_size, &cpus) == 0) {
-    cpu_count = os_cpu_count(&cpus);
-    if (PrintActiveCpus) {
-      tty->print_cr("active_processor_count: sched_getaffinity processor count: %d", cpu_count);
-    }
-  }
-  else {
-    cpu_count = ::sysconf(_SC_NPROCESSORS_ONLN);
-    warning("sched_getaffinity failed (%s)- using online processor count (%d) "
-            "which may exceed available processors", strerror(errno), cpu_count);
-  }
-
-  assert(cpu_count > 0 && cpu_count <= processor_count(), "sanity check");
-  return cpu_count;
+  // Linux doesn't yet have a (official) notion of processor sets,
+  // so just return the number of online processors.
+  int online_cpus = ::sysconf(_SC_NPROCESSORS_ONLN);
+  assert(online_cpus > 0 && online_cpus <= processor_count(), "sanity check");
+  return online_cpus;
 }
 
 void os::set_native_thread_name(const char *name) {
@@ -6248,100 +6102,47 @@
     }
   }
 
+  static void test_reserve_memory_special_huge_tlbfs_mixed(size_t size, size_t alignment) {
+    if (!UseHugeTLBFS) {
+        return;
+    }
+
+    test_log("test_reserve_memory_special_huge_tlbfs_mixed(" SIZE_FORMAT ", " SIZE_FORMAT ")",
+        size, alignment);
+
+    assert(size >= os::large_page_size(), "Incorrect input to test");
+
+    char* addr = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, NULL, false);
+
+    if (addr != NULL) {
+      small_page_write(addr, size);
+
+      os::Linux::release_memory_special_huge_tlbfs(addr, size);
+    }
+  }
+
+  static void test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(size_t size) {
+    size_t lp = os::large_page_size();
+    size_t ag = os::vm_allocation_granularity();
+
+    for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
+      test_reserve_memory_special_huge_tlbfs_mixed(size, alignment);
+    }
+  }
+
   static void test_reserve_memory_special_huge_tlbfs_mixed() {
     size_t lp = os::large_page_size();
     size_t ag = os::vm_allocation_granularity();
 
-    // sizes to test
-    const size_t sizes[] = {
-      lp, lp + ag, lp + lp / 2, lp * 2,
-      lp * 2 + ag, lp * 2 - ag, lp * 2 + lp / 2,
-      lp * 10, lp * 10 + lp / 2
-    };
-    const int num_sizes = sizeof(sizes) / sizeof(size_t);
-
-    // For each size/alignment combination, we test three scenarios:
-    // 1) with req_addr == NULL
-    // 2) with a non-null req_addr at which we expect to successfully allocate
-    // 3) with a non-null req_addr which contains a pre-existing mapping, at which we
-    //    expect the allocation to either fail or to ignore req_addr
-
-    // Pre-allocate two areas; they shall be as large as the largest allocation
-    //  and aligned to the largest alignment we will be testing.
-    const size_t mapping_size = sizes[num_sizes - 1] * 2;
-    char* const mapping1 = (char*) ::mmap(NULL, mapping_size,
-      PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
-      -1, 0);
-    assert(mapping1 != MAP_FAILED, "should work");
-
-    char* const mapping2 = (char*) ::mmap(NULL, mapping_size,
-      PROT_NONE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_NORESERVE,
-      -1, 0);
-    assert(mapping2 != MAP_FAILED, "should work");
-
-    // Unmap the first mapping, but leave the second mapping intact: the first
-    // mapping will serve as a value for a "good" req_addr (case 2). The second
-    // mapping, still intact, as "bad" req_addr (case 3).
-    ::munmap(mapping1, mapping_size);
-
-    // Case 1
-    test_log("%s, req_addr NULL:", __FUNCTION__);
-    test_log("size            align           result");
-
-    for (int i = 0; i < num_sizes; i++) {
-      const size_t size = sizes[i];
-      for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
-        char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, NULL, false);
-        test_log(SIZE_FORMAT_HEX " " SIZE_FORMAT_HEX " ->  " PTR_FORMAT " %s",
-            size, alignment, p, (p != NULL ? "" : "(failed)"));
-        if (p != NULL) {
-          assert(is_ptr_aligned(p, alignment), "must be");
-          small_page_write(p, size);
-          os::Linux::release_memory_special_huge_tlbfs(p, size);
-        }
-      }
-    }
-
-    // Case 2
-    test_log("%s, req_addr non-NULL:", __FUNCTION__);
-    test_log("size            align           req_addr         result");
-
-    for (int i = 0; i < num_sizes; i++) {
-      const size_t size = sizes[i];
-      for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
-        char* const req_addr = (char*) align_ptr_up(mapping1, alignment);
-        char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, req_addr, false);
-        test_log(SIZE_FORMAT_HEX " " SIZE_FORMAT_HEX " " PTR_FORMAT " ->  " PTR_FORMAT " %s",
-            size, alignment, req_addr, p,
-            ((p != NULL ? (p == req_addr ? "(exact match)" : "") : "(failed)")));
-        if (p != NULL) {
-          assert(p == req_addr, "must be");
-          small_page_write(p, size);
-          os::Linux::release_memory_special_huge_tlbfs(p, size);
-        }
-      }
-    }
-
-    // Case 3
-    test_log("%s, req_addr non-NULL with preexisting mapping:", __FUNCTION__);
-    test_log("size            align           req_addr         result");
-
-    for (int i = 0; i < num_sizes; i++) {
-      const size_t size = sizes[i];
-      for (size_t alignment = ag; is_size_aligned(size, alignment); alignment *= 2) {
-        char* const req_addr = (char*) align_ptr_up(mapping2, alignment);
-        char* p = os::Linux::reserve_memory_special_huge_tlbfs_mixed(size, alignment, req_addr, false);
-        test_log(SIZE_FORMAT_HEX " " SIZE_FORMAT_HEX " " PTR_FORMAT " ->  " PTR_FORMAT " %s",
-            size, alignment, req_addr, p,
-            ((p != NULL ? "" : "(failed)")));
-        // as the area around req_addr contains already existing mappings, the API should always
-        // return NULL (as per contract, it cannot return another address)
-        assert(p == NULL, "must be");
-      }
-    }
-
-    ::munmap(mapping2, mapping_size);
-
+    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp);
+    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp + ag);
+    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp + lp / 2);
+    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 2);
+    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 2 + ag);
+    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 2 - ag);
+    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 2 + lp / 2);
+    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 10);
+    test_reserve_memory_special_huge_tlbfs_mixed_all_alignments(lp * 10 + lp / 2);
   }
 
   static void test_reserve_memory_special_huge_tlbfs() {
diff --git a/hotspot/src/share/vm/c1/c1_LIRAssembler.cpp b/hotspot/src/share/vm/c1/c1_LIRAssembler.cpp
index 3447e07..ef2b106 100644
--- a/hotspot/src/share/vm/c1/c1_LIRAssembler.cpp
+++ b/hotspot/src/share/vm/c1/c1_LIRAssembler.cpp
@@ -464,7 +464,6 @@
 
   // emit the static call stub stuff out of line
   emit_static_call_stub();
-  CHECK_BAILOUT();
 
   switch (op->code()) {
   case lir_static_call:
diff --git a/hotspot/src/share/vm/classfile/classFileParser.cpp b/hotspot/src/share/vm/classfile/classFileParser.cpp
index 9678287..23a0cec 100644
--- a/hotspot/src/share/vm/classfile/classFileParser.cpp
+++ b/hotspot/src/share/vm/classfile/classFileParser.cpp
@@ -537,9 +537,6 @@
           int name_index = cp->name_ref_index_at(index);
           Symbol*  name = cp->symbol_at(name_index);
           Symbol*  sig = cp->symbol_at(sig_index);
-          guarantee_property(sig->utf8_length() != 0,
-            "Illegal zero length constant pool entry at %d in class %s",
-            sig_index, CHECK_(nullHandle));
           if (sig->byte_at(0) == JVM_SIGNATURE_FUNC) {
             verify_legal_method_signature(name, sig, CHECK_(nullHandle));
           } else {
@@ -563,9 +560,8 @@
           verify_legal_field_name(name, CHECK_(nullHandle));
           if (_need_verify && _major_version >= JAVA_7_VERSION) {
             // Signature is verified above, when iterating NameAndType_info.
-            // Need only to be sure it's non-zero length and the right type.
-            if (signature->utf8_length() == 0 ||
-                signature->byte_at(0) == JVM_SIGNATURE_FUNC) {
+            // Need only to be sure it's the right type.
+            if (signature->byte_at(0) == JVM_SIGNATURE_FUNC) {
               throwIllegalSignature(
                   "Field", name, signature, CHECK_(nullHandle));
             }
@@ -576,9 +572,8 @@
           verify_legal_method_name(name, CHECK_(nullHandle));
           if (_need_verify && _major_version >= JAVA_7_VERSION) {
             // Signature is verified above, when iterating NameAndType_info.
-            // Need only to be sure it's non-zero length and the right type.
-            if (signature->utf8_length() == 0 ||
-                signature->byte_at(0) != JVM_SIGNATURE_FUNC) {
+            // Need only to be sure it's the right type.
+            if (signature->byte_at(0) != JVM_SIGNATURE_FUNC) {
               throwIllegalSignature(
                   "Method", name, signature, CHECK_(nullHandle));
             }
@@ -589,7 +584,8 @@
             // 4509014: If a class method name begins with '<', it must be "<init>".
             assert(name != NULL, "method name in constant pool is null");
             unsigned int name_len = name->utf8_length();
-            if (name_len != 0 && name->byte_at(0) == '<') {
+            assert(name_len > 0, "bad method name");  // already verified as legal name
+            if (name->byte_at(0) == '<') {
               if (name != vmSymbols::object_initializer_name()) {
                 classfile_parse_error(
                   "Bad method name at constant pool index %u in class file %s",
diff --git a/hotspot/src/share/vm/classfile/classLoaderData.cpp b/hotspot/src/share/vm/classfile/classLoaderData.cpp
index 1f25e15..2e852f3 100644
--- a/hotspot/src/share/vm/classfile/classLoaderData.cpp
+++ b/hotspot/src/share/vm/classfile/classLoaderData.cpp
@@ -813,12 +813,6 @@
     // called on all alive classes. See the comment in ClassLoaderDataGraph::clean_metaspaces.
     cld->free_deallocate_list();
   }
-
-  // In some rare cases items added to the unloading list will not be freed elsewhere.
-  // To keep it simple, walk the _unloading list also.
-  for (ClassLoaderData* cld = _unloading; cld != _saved_unloading; cld = cld->next()) {
-    cld->free_deallocate_list();
-  }
 }
 
 // CDS support
diff --git a/hotspot/src/share/vm/classfile/classLoaderData.inline.hpp b/hotspot/src/share/vm/classfile/classLoaderData.inline.hpp
index 755ac54..11014f2 100644
--- a/hotspot/src/share/vm/classfile/classLoaderData.inline.hpp
+++ b/hotspot/src/share/vm/classfile/classLoaderData.inline.hpp
@@ -40,7 +40,7 @@
 
 
 inline ClassLoaderData *ClassLoaderDataGraph::find_or_create(Handle loader, TRAPS) {
-  guarantee(loader() != NULL && loader()->is_oop(), "Loader must be oop");
+  assert(loader() != NULL,"Must be a class loader");
   // Gets the class loader data out of the java/lang/ClassLoader object, if non-null
   // it's already in the loader_data, so no need to add
   ClassLoaderData* loader_data= java_lang_ClassLoader::loader_data(loader());
diff --git a/hotspot/src/share/vm/classfile/systemDictionary.cpp b/hotspot/src/share/vm/classfile/systemDictionary.cpp
index 1dfe3b6..31be14b 100644
--- a/hotspot/src/share/vm/classfile/systemDictionary.cpp
+++ b/hotspot/src/share/vm/classfile/systemDictionary.cpp
@@ -1084,18 +1084,15 @@
                                                              THREAD);
 
   const char* pkg = "java/";
-  size_t pkglen = strlen(pkg);
   if (!HAS_PENDING_EXCEPTION &&
       !class_loader.is_null() &&
       parsed_name != NULL &&
-      parsed_name->utf8_length() >= (int)pkglen &&
-      !strncmp((const char*)parsed_name->bytes(), pkg, pkglen)) {
+      !strncmp((const char*)parsed_name->bytes(), pkg, strlen(pkg))) {
     // It is illegal to define classes in the "java." package from
     // JVM_DefineClass or jni_DefineClass unless you're the bootclassloader
     ResourceMark rm(THREAD);
     char* name = parsed_name->as_C_string();
     char* index = strrchr(name, '/');
-    assert(index != NULL, "must be");
     *index = '\0'; // chop to just the package name
     while ((index = strchr(name, '/')) != NULL) {
       *index = '.'; // replace '/' with '.' in package name
diff --git a/hotspot/src/share/vm/classfile/vmSymbols.hpp b/hotspot/src/share/vm/classfile/vmSymbols.hpp
index 5281758..b857cb3 100644
--- a/hotspot/src/share/vm/classfile/vmSymbols.hpp
+++ b/hotspot/src/share/vm/classfile/vmSymbols.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -517,7 +517,6 @@
   template(int_StringBuffer_signature,                "(I)Ljava/lang/StringBuffer;")                              \
   template(char_StringBuffer_signature,               "(C)Ljava/lang/StringBuffer;")                              \
   template(int_String_signature,                      "(I)Ljava/lang/String;")                                    \
-  template(codesource_permissioncollection_signature, "(Ljava/security/CodeSource;Ljava/security/PermissionCollection;)V") \
   /* signature symbols needed by intrinsics */                                                                    \
   VM_INTRINSICS_DO(VM_INTRINSIC_IGNORE, VM_SYMBOL_IGNORE, VM_SYMBOL_IGNORE, template, VM_ALIAS_IGNORE)            \
                                                                                                                   \
diff --git a/hotspot/src/share/vm/code/compiledIC.hpp b/hotspot/src/share/vm/code/compiledIC.hpp
index de72423..b797329 100644
--- a/hotspot/src/share/vm/code/compiledIC.hpp
+++ b/hotspot/src/share/vm/code/compiledIC.hpp
@@ -320,7 +320,7 @@
   friend CompiledStaticCall* compiledStaticCall_at(Relocation* call_site);
 
   // Code
-  static address emit_to_interp_stub(CodeBuffer &cbuf);
+  static void emit_to_interp_stub(CodeBuffer &cbuf);
   static int to_interp_stub_size();
   static int reloc_to_interp_stub();
 
diff --git a/hotspot/src/share/vm/code/nmethod.cpp b/hotspot/src/share/vm/code/nmethod.cpp
index e20f507..6ea39ae 100644
--- a/hotspot/src/share/vm/code/nmethod.cpp
+++ b/hotspot/src/share/vm/code/nmethod.cpp
@@ -2290,7 +2290,7 @@
     assert(cur != NULL, "not NULL-terminated");
     nmethod* next = cur->_oops_do_mark_link;
     cur->_oops_do_mark_link = NULL;
-    DEBUG_ONLY(cur->verify_oop_relocations());
+    cur->verify_oop_relocations();
     NOT_PRODUCT(if (TraceScavenge)  cur->print_on(tty, "oops_do, unmark"));
     cur = next;
   }
diff --git a/hotspot/src/share/vm/compiler/compileBroker.cpp b/hotspot/src/share/vm/compiler/compileBroker.cpp
index 32a753c..dad99ec 100644
--- a/hotspot/src/share/vm/compiler/compileBroker.cpp
+++ b/hotspot/src/share/vm/compiler/compileBroker.cpp
@@ -1851,10 +1851,6 @@
           tty->print_cr("Opening compilation log %s", file_name);
         }
         CompileLog* log = new(ResourceObj::C_HEAP, mtCompiler) CompileLog(file_name, fp, thread_id);
-        if (log == NULL) {
-          fclose(fp);
-          return;
-        }
         thread->init_log(log);
 
         if (xtty != NULL) {
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1ParScanThreadState.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1ParScanThreadState.cpp
index fc86a50..406ac73 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1ParScanThreadState.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1ParScanThreadState.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -148,9 +148,7 @@
   do {
     // Drain the overflow stack first, so other threads can steal.
     while (_refs->pop_overflow(ref)) {
-      if (!_refs->try_push_to_taskqueue(ref)) {
-        dispatch_reference(ref);
-      }
+      dispatch_reference(ref);
     }
 
     while (_refs->pop_local(ref)) {
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp
index 45bc364..c55165b 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1RemSetSummary.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -133,6 +133,10 @@
   }
 }
 
+static size_t round_to_K(size_t value) {
+  return value / K;
+}
+
 class RegionTypeCounter VALUE_OBJ_CLASS_SPEC {
 private:
   const char* _name;
@@ -183,10 +187,8 @@
   size_t code_root_elems() const { return _code_root_elems; }
 
   void print_rs_mem_info_on(outputStream * out, size_t total) {
-    out->print_cr("    "SIZE_FORMAT_W(8) "%s (%5.1f%%) by "SIZE_FORMAT" %s regions",
-        byte_size_in_proper_unit(rs_mem_size()),
-        proper_unit_for_byte_size(rs_mem_size()),
-        rs_mem_size_percent_of(total), amount(), _name);
+    out->print_cr("    "SIZE_FORMAT_W(8)"K (%5.1f%%) by "SIZE_FORMAT" %s regions",
+        round_to_K(rs_mem_size()), rs_mem_size_percent_of(total), amount(), _name);
   }
 
   void print_cards_occupied_info_on(outputStream * out, size_t total) {
@@ -195,10 +197,8 @@
   }
 
   void print_code_root_mem_info_on(outputStream * out, size_t total) {
-    out->print_cr("    "SIZE_FORMAT_W(8) "%s (%5.1f%%) by "SIZE_FORMAT" %s regions",
-        byte_size_in_proper_unit(code_root_mem_size()),
-        proper_unit_for_byte_size(code_root_mem_size()),
-        code_root_mem_size_percent_of(total), amount(), _name);
+    out->print_cr("    "SIZE_FORMAT_W(8)"K (%5.1f%%) by "SIZE_FORMAT" %s regions",
+        round_to_K(code_root_mem_size()), code_root_mem_size_percent_of(total), amount(), _name);
   }
 
   void print_code_root_elems_info_on(outputStream * out, size_t total) {
@@ -280,23 +280,17 @@
     RegionTypeCounter* counters[] = { &_young, &_humonguous, &_free, &_old, NULL };
 
     out->print_cr("\n Current rem set statistics");
-    out->print_cr("  Total per region rem sets sizes = " SIZE_FORMAT "%s."
-                  " Max = " SIZE_FORMAT "%s.",
-                  byte_size_in_proper_unit(total_rs_mem_sz()),
-                  proper_unit_for_byte_size(total_rs_mem_sz()),
-                  byte_size_in_proper_unit(max_rs_mem_sz()),
-                  proper_unit_for_byte_size(max_rs_mem_sz()));
-
+    out->print_cr("  Total per region rem sets sizes = "SIZE_FORMAT"K."
+                  " Max = "SIZE_FORMAT"K.",
+                  round_to_K(total_rs_mem_sz()), round_to_K(max_rs_mem_sz()));
     for (RegionTypeCounter** current = &counters[0]; *current != NULL; current++) {
       (*current)->print_rs_mem_info_on(out, total_rs_mem_sz());
     }
 
-    out->print_cr("   Static structures = " SIZE_FORMAT "%s,"
-                  " free_lists = " SIZE_FORMAT "%s.",
-                  byte_size_in_proper_unit(HeapRegionRemSet::static_mem_size()),
-                  proper_unit_for_byte_size(HeapRegionRemSet::static_mem_size()),
-                  byte_size_in_proper_unit(HeapRegionRemSet::fl_mem_size()),
-                  proper_unit_for_byte_size(HeapRegionRemSet::fl_mem_size()));
+    out->print_cr("   Static structures = "SIZE_FORMAT"K,"
+                  " free_lists = "SIZE_FORMAT"K.",
+                  round_to_K(HeapRegionRemSet::static_mem_size()),
+                  round_to_K(HeapRegionRemSet::fl_mem_size()));
 
     out->print_cr("    "SIZE_FORMAT" occupied cards represented.",
                   total_cards_occupied());
@@ -307,21 +301,17 @@
     // Largest sized rem set region statistics
     HeapRegionRemSet* rem_set = max_rs_mem_sz_region()->rem_set();
     out->print_cr("    Region with largest rem set = "HR_FORMAT", "
-                  "size = "SIZE_FORMAT "%s, occupied = "SIZE_FORMAT "%s.",
+                  "size = "SIZE_FORMAT "K, occupied = "SIZE_FORMAT"K.",
                   HR_FORMAT_PARAMS(max_rs_mem_sz_region()),
-                  byte_size_in_proper_unit(rem_set->mem_size()),
-                  proper_unit_for_byte_size(rem_set->mem_size()),
-                  byte_size_in_proper_unit(rem_set->occupied()),
-                  proper_unit_for_byte_size(rem_set->occupied()));
+                  round_to_K(rem_set->mem_size()),
+                  round_to_K(rem_set->occupied()));
+
     // Strong code root statistics
     HeapRegionRemSet* max_code_root_rem_set = max_code_root_mem_sz_region()->rem_set();
-    out->print_cr("  Total heap region code root sets sizes = " SIZE_FORMAT "%s."
-                  "  Max = " SIZE_FORMAT "%s.",
-                  byte_size_in_proper_unit(total_code_root_mem_sz()),
-                  proper_unit_for_byte_size(total_code_root_mem_sz()),
-                  byte_size_in_proper_unit(max_code_root_rem_set->strong_code_roots_mem_size()),
-                  proper_unit_for_byte_size(max_code_root_rem_set->strong_code_roots_mem_size()));
-
+    out->print_cr("  Total heap region code root sets sizes = "SIZE_FORMAT"K."
+                  "  Max = "SIZE_FORMAT"K.",
+                  round_to_K(total_code_root_mem_sz()),
+                  round_to_K(max_code_root_rem_set->strong_code_roots_mem_size()));
     for (RegionTypeCounter** current = &counters[0]; *current != NULL; current++) {
       (*current)->print_code_root_mem_info_on(out, total_code_root_mem_sz());
     }
@@ -333,12 +323,10 @@
     }
 
     out->print_cr("    Region with largest amount of code roots = "HR_FORMAT", "
-                  "size = "SIZE_FORMAT "%s, num_elems = "SIZE_FORMAT".",
+                  "size = "SIZE_FORMAT "K, num_elems = "SIZE_FORMAT".",
                   HR_FORMAT_PARAMS(max_code_root_mem_sz_region()),
-                  byte_size_in_proper_unit(max_code_root_rem_set->strong_code_roots_mem_size()),
-                  proper_unit_for_byte_size(max_code_root_rem_set->strong_code_roots_mem_size()),
-                  max_code_root_rem_set->strong_code_roots_list_length());
-
+                  round_to_K(max_code_root_rem_set->strong_code_roots_mem_size()),
+                  round_to_K(max_code_root_rem_set->strong_code_roots_list_length()));
   }
 };
 
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupTable.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupTable.cpp
index 71e7e53..2b41688 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupTable.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupTable.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -28,23 +28,22 @@
 #include "gc_implementation/g1/g1CollectedHeap.inline.hpp"
 #include "gc_implementation/g1/g1SATBCardTableModRefBS.hpp"
 #include "gc_implementation/g1/g1StringDedupTable.hpp"
-#include "gc_implementation/shared/concurrentGCThread.hpp"
 #include "memory/gcLocker.hpp"
 #include "memory/padded.inline.hpp"
 #include "oops/typeArrayOop.hpp"
 #include "runtime/mutexLocker.hpp"
 
 //
-// List of deduplication table entries. Links table
+// Freelist in the deduplication table entry cache. Links table
 // entries together using their _next fields.
 //
-class G1StringDedupEntryList : public CHeapObj<mtGC> {
+class G1StringDedupEntryFreeList : public CHeapObj<mtGC> {
 private:
   G1StringDedupEntry* _list;
   size_t              _length;
 
 public:
-  G1StringDedupEntryList() :
+  G1StringDedupEntryFreeList() :
     _list(NULL),
     _length(0) {
   }
@@ -64,12 +63,6 @@
     return entry;
   }
 
-  G1StringDedupEntry* remove_all() {
-    G1StringDedupEntry* list = _list;
-    _list = NULL;
-    return list;
-  }
-
   size_t length() {
     return _length;
   }
@@ -91,53 +84,43 @@
 //
 class G1StringDedupEntryCache : public CHeapObj<mtGC> {
 private:
-  // One cache/overflow list per GC worker to allow lock less freeing of
-  // entries while doing a parallel scan of the table. Using PaddedEnd to
-  // avoid false sharing.
-  size_t                             _nlists;
-  size_t                             _max_list_length;
-  PaddedEnd<G1StringDedupEntryList>* _cached;
-  PaddedEnd<G1StringDedupEntryList>* _overflowed;
+  // One freelist per GC worker to allow lock less freeing of
+  // entries while doing a parallel scan of the table. Using
+  // PaddedEnd to avoid false sharing.
+  PaddedEnd<G1StringDedupEntryFreeList>* _lists;
+  size_t                                 _nlists;
 
 public:
-  G1StringDedupEntryCache(size_t max_size);
+  G1StringDedupEntryCache();
   ~G1StringDedupEntryCache();
 
-  // Set max number of table entries to cache.
-  void set_max_size(size_t max_size);
-
-  // Get a table entry from the cache, or allocate a new entry if the cache is empty.
+  // Get a table entry from the cache freelist, or allocate a new
+  // entry if the cache is empty.
   G1StringDedupEntry* alloc();
 
-  // Insert a table entry into the cache.
+  // Insert a table entry into the cache freelist.
   void free(G1StringDedupEntry* entry, uint worker_id);
 
   // Returns current number of entries in the cache.
   size_t size();
 
-  // Deletes overflowed entries.
-  void delete_overflowed();
+  // If the cache has grown above the given max size, trim it down
+  // and deallocate the memory occupied by trimmed of entries.
+  void trim(size_t max_size);
 };
 
-G1StringDedupEntryCache::G1StringDedupEntryCache(size_t max_size) :
-  _nlists(MAX2(ParallelGCThreads, (size_t)1)),
-  _max_list_length(0),
-  _cached(PaddedArray<G1StringDedupEntryList, mtGC>::create_unfreeable((uint)_nlists)),
-  _overflowed(PaddedArray<G1StringDedupEntryList, mtGC>::create_unfreeable((uint)_nlists)) {
-  set_max_size(max_size);
+G1StringDedupEntryCache::G1StringDedupEntryCache() {
+  _nlists = MAX2(ParallelGCThreads, (size_t)1);
+  _lists = PaddedArray<G1StringDedupEntryFreeList, mtGC>::create_unfreeable((uint)_nlists);
 }
 
 G1StringDedupEntryCache::~G1StringDedupEntryCache() {
   ShouldNotReachHere();
 }
 
-void G1StringDedupEntryCache::set_max_size(size_t size) {
-  _max_list_length = size / _nlists;
-}
-
 G1StringDedupEntry* G1StringDedupEntryCache::alloc() {
   for (size_t i = 0; i < _nlists; i++) {
-    G1StringDedupEntry* entry = _cached[i].remove();
+    G1StringDedupEntry* entry = _lists[i].remove();
     if (entry != NULL) {
       return entry;
     }
@@ -148,55 +131,31 @@
 void G1StringDedupEntryCache::free(G1StringDedupEntry* entry, uint worker_id) {
   assert(entry->obj() != NULL, "Double free");
   assert(worker_id < _nlists, "Invalid worker id");
-
   entry->set_obj(NULL);
   entry->set_hash(0);
-
-  if (_cached[worker_id].length() < _max_list_length) {
-    // Cache is not full
-    _cached[worker_id].add(entry);
-  } else {
-    // Cache is full, add to overflow list for later deletion
-    _overflowed[worker_id].add(entry);
-  }
+  _lists[worker_id].add(entry);
 }
 
 size_t G1StringDedupEntryCache::size() {
   size_t size = 0;
   for (size_t i = 0; i < _nlists; i++) {
-    size += _cached[i].length();
+    size += _lists[i].length();
   }
   return size;
 }
 
-void G1StringDedupEntryCache::delete_overflowed() {
-  double start = os::elapsedTime();
-  uintx count = 0;
-
+void G1StringDedupEntryCache::trim(size_t max_size) {
+  size_t cache_size = 0;
   for (size_t i = 0; i < _nlists; i++) {
-    G1StringDedupEntry* entry;
-
-    {
-      // The overflow list can be modified during safepoints, therefore
-      // we temporarily join the suspendible thread set while removing
-      // all entries from the list.
-      SuspendibleThreadSetJoiner sts_join;
-      entry = _overflowed[i].remove_all();
-    }
-
-    // Delete all entries
-    while (entry != NULL) {
-      G1StringDedupEntry* next = entry->next();
+    G1StringDedupEntryFreeList* list = &_lists[i];
+    cache_size += list->length();
+    while (cache_size > max_size) {
+      G1StringDedupEntry* entry = list->remove();
+      assert(entry != NULL, "Should not be null");
+      cache_size--;
       delete entry;
-      entry = next;
-      count++;
     }
   }
-
-  double end = os::elapsedTime();
-  if (PrintStringDeduplicationStatistics) {
-    gclog_or_tty->print_cr("[GC concurrent-string-deduplication, deleted " UINTX_FORMAT " entries, " G1_STRDEDUP_TIME_FORMAT "]", count, end - start);
-  }
 }
 
 G1StringDedupTable*      G1StringDedupTable::_table = NULL;
@@ -233,7 +192,7 @@
 
 void G1StringDedupTable::create() {
   assert(_table == NULL, "One string deduplication table allowed");
-  _entry_cache = new G1StringDedupEntryCache((size_t)(_min_size * _max_cache_factor));
+  _entry_cache = new G1StringDedupEntryCache();
   _table = new G1StringDedupTable(_min_size);
 }
 
@@ -416,9 +375,6 @@
   // Update statistics
   _resize_count++;
 
-  // Update max cache size
-  _entry_cache->set_max_size((size_t)(size * _max_cache_factor));
-
   // Allocate the new table. The new table will be populated by workers
   // calling unlink_or_oops_do() and finally installed by finish_resize().
   return new G1StringDedupTable(size, _table->_hash_seed);
@@ -471,7 +427,7 @@
     removed += unlink_or_oops_do(cl, table_half + partition_begin, table_half + partition_end, worker_id);
   }
 
-  // Delayed update to avoid contention on the table lock
+  // Delayed update avoid contention on the table lock
   if (removed > 0) {
     MutexLockerEx ml(StringDedupTable_lock, Mutex::_no_safepoint_check_flag);
     _table->_entries -= removed;
@@ -589,8 +545,10 @@
   }
 }
 
-void G1StringDedupTable::clean_entry_cache() {
-  _entry_cache->delete_overflowed();
+void G1StringDedupTable::trim_entry_cache() {
+  MutexLockerEx ml(StringDedupTable_lock, Mutex::_no_safepoint_check_flag);
+  size_t max_cache_size = (size_t)(_table->_size * _max_cache_factor);
+  _entry_cache->trim(max_cache_size);
 }
 
 void G1StringDedupTable::print_statistics(outputStream* st) {
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupTable.hpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupTable.hpp
index d771219..f357523 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupTable.hpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupTable.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -218,8 +218,8 @@
   // and deletes the previously active table.
   static void finish_rehash(G1StringDedupTable* rehashed_table);
 
-  // If the table entry cache has grown too large, delete overflowed entries.
-  static void clean_entry_cache();
+  // If the table entry cache has grown too large, trim it down according to policy
+  static void trim_entry_cache();
 
   static void unlink_or_oops_do(G1StringDedupUnlinkOrOopsDoClosure* cl, uint worker_id);
 
diff --git a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.cpp b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.cpp
index 09c567e..e59efa7 100644
--- a/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.cpp
+++ b/hotspot/src/share/vm/gc_implementation/g1/g1StringDedupThread.cpp
@@ -100,14 +100,14 @@
         }
       }
 
+      G1StringDedupTable::trim_entry_cache();
+
       stat.mark_done();
 
       // Print statistics
       total_stat.add(stat);
       print(gclog_or_tty, stat, total_stat);
     }
-
-    G1StringDedupTable::clean_entry_cache();
   }
 
   terminate();
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp
index 7d85c34..260dc72 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/pcTasks.cpp
@@ -171,7 +171,7 @@
   ParallelScavengeHeap* heap = PSParallelCompact::gc_heap();
   uint parallel_gc_threads = heap->gc_task_manager()->workers();
   uint active_gc_threads = heap->gc_task_manager()->active_workers();
-  OopTaskQueueSet* qset = ParCompactionManager::stack_array();
+  RegionTaskQueueSet* qset = ParCompactionManager::region_array();
   ParallelTaskTerminator terminator(active_gc_threads, qset);
   GCTaskQueue* q = GCTaskQueue::create();
   for(uint i=0; i<parallel_gc_threads; i++) {
diff --git a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
index b2c3b06..8175ded 100644
--- a/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
+++ b/hotspot/src/share/vm/gc_implementation/parallelScavenge/psParallelCompact.cpp
@@ -2355,7 +2355,7 @@
   ParallelScavengeHeap* heap = gc_heap();
   uint parallel_gc_threads = heap->gc_task_manager()->workers();
   uint active_gc_threads = heap->gc_task_manager()->active_workers();
-  TaskQueueSetSuper* qset = ParCompactionManager::stack_array();
+  TaskQueueSetSuper* qset = ParCompactionManager::region_array();
   ParallelTaskTerminator terminator(active_gc_threads, qset);
 
   PSParallelCompact::MarkAndPushClosure mark_and_push_closure(cm);
diff --git a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp
index 59e1fb9..eed4a35 100644
--- a/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp
+++ b/hotspot/src/share/vm/interpreter/bytecodeInterpreter.cpp
@@ -593,9 +593,8 @@
 /* 0xDC */ &&opc_default,     &&opc_default,        &&opc_default,      &&opc_default,
 
 /* 0xE0 */ &&opc_default,     &&opc_default,        &&opc_default,      &&opc_default,
-/* 0xE4 */ &&opc_default,     &&opc_default,        &&opc_fast_aldc,    &&opc_fast_aldc_w,
-/* 0xE8 */ &&opc_return_register_finalizer,
-                              &&opc_invokehandle,   &&opc_default,      &&opc_default,
+/* 0xE4 */ &&opc_default,     &&opc_fast_aldc,      &&opc_fast_aldc_w,  &&opc_return_register_finalizer,
+/* 0xE8 */ &&opc_invokehandle,&&opc_default,        &&opc_default,      &&opc_default,
 /* 0xEC */ &&opc_default,     &&opc_default,        &&opc_default,      &&opc_default,
 
 /* 0xF0 */ &&opc_default,     &&opc_default,        &&opc_default,      &&opc_default,
diff --git a/hotspot/src/share/vm/oops/instanceKlass.cpp b/hotspot/src/share/vm/oops/instanceKlass.cpp
index 4ecc87e..481742d 100644
--- a/hotspot/src/share/vm/oops/instanceKlass.cpp
+++ b/hotspot/src/share/vm/oops/instanceKlass.cpp
@@ -616,11 +616,7 @@
 
 bool InstanceKlass::link_class_impl(
     instanceKlassHandle this_oop, bool throw_verifyerror, TRAPS) {
-  // check for error state.
-  // This is checking for the wrong state.  If the state is initialization_error,
-  // then this class *was* linked.  The CDS code does a try_link_class and uses
-  // initialization_error to mark classes to not include in the archive during
-  // DumpSharedSpaces.  This should be removed when the CDS bug is fixed.
+  // check for error state
   if (this_oop->is_in_error_state()) {
     ResourceMark rm(THREAD);
     THROW_MSG_(vmSymbols::java_lang_NoClassDefFoundError(),
@@ -805,22 +801,37 @@
 }
 
 // Eagerly initialize superinterfaces that declare default methods (concrete instance: any access)
-void InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_k, TRAPS) {
-  assert (this_k->has_default_methods(), "caller should have checked this");
-  for (int i = 0; i < this_k->local_interfaces()->length(); ++i) {
-    Klass* iface = this_k->local_interfaces()->at(i);
-    InstanceKlass* ik = InstanceKlass::cast(iface);
+void InstanceKlass::initialize_super_interfaces(instanceKlassHandle this_oop, TRAPS) {
+  if (this_oop->has_default_methods()) {
+    for (int i = 0; i < this_oop->local_interfaces()->length(); ++i) {
+      Klass* iface = this_oop->local_interfaces()->at(i);
+      InstanceKlass* ik = InstanceKlass::cast(iface);
+      if (ik->should_be_initialized()) {
+        if (ik->has_default_methods()) {
+          ik->initialize_super_interfaces(ik, THREAD);
+        }
+        // Only initialize() interfaces that "declare" concrete methods.
+        // has_default_methods drives searching superinterfaces since it
+        // means has_default_methods in its superinterface hierarchy
+        if (!HAS_PENDING_EXCEPTION && ik->declares_default_methods()) {
+          ik->initialize(THREAD);
+        }
+        if (HAS_PENDING_EXCEPTION) {
+          Handle e(THREAD, PENDING_EXCEPTION);
+          CLEAR_PENDING_EXCEPTION;
+          {
+            EXCEPTION_MARK;
+            // Locks object, set state, and notify all waiting threads
+            this_oop->set_initialization_state_and_notify(
+                initialization_error, THREAD);
 
-    // Initialization is depth first search ie. we start with top of the inheritance tree
-    // has_default_methods drives searching superinterfaces since it
-    // means has_default_methods in its superinterface hierarchy
-    if (ik->has_default_methods()) {
-      ik->initialize_super_interfaces(ik, CHECK);
-    }
-
-    // Only initialize() interfaces that "declare" concrete methods.
-    if (ik->should_be_initialized() && ik->declares_default_methods()) {
-      ik->initialize(CHECK);
+            // ignore any exception thrown, superclass initialization error is
+            // thrown below
+            CLEAR_PENDING_EXCEPTION;
+          }
+          THROW_OOP(e());
+        }
+      }
     }
   }
 }
@@ -886,36 +897,30 @@
   }
 
   // Step 7
-  // Next, if C is a class rather than an interface, initialize its super class and super
-  // interfaces.
-  if (!this_oop->is_interface()) {
-    Klass* super_klass = this_oop->super();
-    if (super_klass != NULL && super_klass->should_be_initialized()) {
-      super_klass->initialize(THREAD);
-    }
-    // If C implements any interfaces that declares a non-abstract, non-static method,
-    // the initialization of C triggers initialization of its super interfaces.
-    // Only need to recurse if has_default_methods which includes declaring and
-    // inheriting default methods
-    if (!HAS_PENDING_EXCEPTION && this_oop->has_default_methods()) {
-      this_oop->initialize_super_interfaces(this_oop, THREAD);
-    }
+  Klass* super_klass = this_oop->super();
+  if (super_klass != NULL && !this_oop->is_interface() && super_klass->should_be_initialized()) {
+    super_klass->initialize(THREAD);
 
-    // If any exceptions, complete abruptly, throwing the same exception as above.
     if (HAS_PENDING_EXCEPTION) {
       Handle e(THREAD, PENDING_EXCEPTION);
       CLEAR_PENDING_EXCEPTION;
       {
         EXCEPTION_MARK;
-        // Locks object, set state, and notify all waiting threads
-        this_oop->set_initialization_state_and_notify(initialization_error, THREAD);
-        CLEAR_PENDING_EXCEPTION;
+        this_oop->set_initialization_state_and_notify(initialization_error, THREAD); // Locks object, set state, and notify all waiting threads
+        CLEAR_PENDING_EXCEPTION;   // ignore any exception thrown, superclass initialization error is thrown below
       }
       DTRACE_CLASSINIT_PROBE_WAIT(super__failed, InstanceKlass::cast(this_oop()), -1,wait);
       THROW_OOP(e());
     }
   }
 
+  // Recursively initialize any superinterfaces that declare default methods
+  // Only need to recurse if has_default_methods which includes declaring and
+  // inheriting default methods
+  if (this_oop->has_default_methods()) {
+    this_oop->initialize_super_interfaces(this_oop, CHECK);
+  }
+
   // Step 8
   {
     assert(THREAD->is_Java_thread(), "non-JavaThread in initialize_impl");
@@ -976,15 +981,10 @@
 
 void InstanceKlass::set_initialization_state_and_notify_impl(instanceKlassHandle this_oop, ClassState state, TRAPS) {
   oop init_lock = this_oop->init_lock();
-  if (init_lock != NULL) {
-    ObjectLocker ol(init_lock, THREAD);
-    this_oop->set_init_state(state);
-    this_oop->fence_and_clear_init_lock();
-    ol.notify_all(CHECK);
-  } else {
-    assert(init_lock != NULL, "The initialization state should never be set twice");
-    this_oop->set_init_state(state);
-  }
+  ObjectLocker ol(init_lock, THREAD, init_lock != NULL);
+  this_oop->set_init_state(state);
+  this_oop->fence_and_clear_init_lock();
+  ol.notify_all(CHECK);
 }
 
 // The embedded _implementor field can only record one implementor.
diff --git a/hotspot/src/share/vm/oops/method.cpp b/hotspot/src/share/vm/oops/method.cpp
index b1db4dc..172c612 100644
--- a/hotspot/src/share/vm/oops/method.cpp
+++ b/hotspot/src/share/vm/oops/method.cpp
@@ -111,7 +111,6 @@
 // Release Method*.  The nmethod will be gone when we get here because
 // we've walked the code cache.
 void Method::deallocate_contents(ClassLoaderData* loader_data) {
-  clear_jmethod_id(loader_data);
   MetadataFactory::free_metadata(loader_data, constMethod());
   set_constMethod(NULL);
   MetadataFactory::free_metadata(loader_data, method_data());
@@ -1801,24 +1800,13 @@
 #endif // ASSERT
     *m = _free_method;
   }
-  void clear_method(Method* m) {
-    for (JNIMethodBlock* b = this; b != NULL; b = b->_next) {
-      for (int i = 0; i < number_of_methods; i++) {
-        if (b->_methods[i] == m) {
-          b->_methods[i] = NULL;
-          return;
-        }
-      }
-    }
-    // not found
-  }
 
   // During class unloading the methods are cleared, which is different
   // than freed.
   void clear_all_methods() {
     for (JNIMethodBlock* b = this; b != NULL; b = b->_next) {
       for (int i = 0; i< number_of_methods; i++) {
-        b->_methods[i] = NULL;
+        _methods[i] = NULL;
       }
     }
   }
@@ -1828,7 +1816,7 @@
     int count = 0;
     for (JNIMethodBlock* b = this; b != NULL; b = b->_next) {
       for (int i = 0; i< number_of_methods; i++) {
-        if (b->_methods[i] != _free_method) count++;
+        if (_methods[i] != _free_method) count++;
       }
     }
     return count;
@@ -1884,13 +1872,8 @@
 
 bool Method::is_method_id(jmethodID mid) {
   Method* m = resolve_jmethod_id(mid);
-  if (m == NULL) {
-    return false;
-  }
+  assert(m != NULL, "should be called with non-null method");
   InstanceKlass* ik = m->method_holder();
-  if (ik == NULL) {
-    return false;
-  }
   ClassLoaderData* cld = ik->class_loader_data();
   if (cld->jmethod_ids() == NULL) return false;
   return (cld->jmethod_ids()->contains((Method**)mid));
@@ -1898,9 +1881,6 @@
 
 Method* Method::checked_resolve_jmethod_id(jmethodID mid) {
   if (mid == NULL) return NULL;
-  if (!Method::is_method_id(mid)) {
-    return NULL;
-  }
   Method* o = resolve_jmethod_id(mid);
   if (o == NULL || o == JNIMethodBlock::_free_method || !((Metadata*)o)->is_method()) {
     return NULL;
@@ -1919,10 +1899,6 @@
   }
 }
 
-void Method::clear_jmethod_id(ClassLoaderData* loader_data) {
-  loader_data->jmethod_ids()->clear_method(this);
-}
-
 // Called when the class loader is unloaded to make all methods weak.
 void Method::clear_jmethod_ids(ClassLoaderData* loader_data) {
   loader_data->jmethod_ids()->clear_all_methods();
diff --git a/hotspot/src/share/vm/oops/method.hpp b/hotspot/src/share/vm/oops/method.hpp
index 974bced..2126033 100644
--- a/hotspot/src/share/vm/oops/method.hpp
+++ b/hotspot/src/share/vm/oops/method.hpp
@@ -768,8 +768,6 @@
 
   // Helper routines for intrinsic_id() and vmIntrinsics::method().
   void init_intrinsic_id();     // updates from _none if a match
-  void clear_jmethod_id(ClassLoaderData* loader_data);
-
   static vmSymbols::SID klass_id_for_intrinsics(Klass* holder);
 
   bool     jfr_towrite()                { return _jfr_towrite;              }
diff --git a/hotspot/src/share/vm/opto/block.cpp b/hotspot/src/share/vm/opto/block.cpp
index 245ce42..f0599a1 100644
--- a/hotspot/src/share/vm/opto/block.cpp
+++ b/hotspot/src/share/vm/opto/block.cpp
@@ -1208,9 +1208,6 @@
       if (j >= 1 && n->is_Mach() && n->as_Mach()->ideal_Opcode() == Op_CreateEx) {
         assert(j == 1 || block->get_node(j-1)->is_Phi(), "CreateEx must be first instruction in block");
       }
-      if (n->needs_anti_dependence_check()) {
-        verify_anti_dependences(block, n);
-      }
       for (uint k = 0; k < n->req(); k++) {
         Node *def = n->in(k);
         if (def && def != n) {
diff --git a/hotspot/src/share/vm/opto/block.hpp b/hotspot/src/share/vm/opto/block.hpp
index 0c7363e..d085b29 100644
--- a/hotspot/src/share/vm/opto/block.hpp
+++ b/hotspot/src/share/vm/opto/block.hpp
@@ -185,13 +185,14 @@
   Block* lone_fall_through();   // Return lone fall-through Block or null
 
   Block* dom_lca(Block* that);  // Compute LCA in dominator tree.
-
+#ifdef ASSERT
   bool dominates(Block* that) {
     int dom_diff = this->_dom_depth - that->_dom_depth;
     if (dom_diff > 0)  return false;
     for (; dom_diff < 0; dom_diff++)  that = that->_idom;
     return this == that;
   }
+#endif
 
   // Report the alignment required by this block.  Must be a power of 2.
   // The previous block will insert nops to get this alignment.
@@ -472,9 +473,9 @@
   MachNode* _goto;
 
   Block* insert_anti_dependences(Block* LCA, Node* load, bool verify = false);
-  void verify_anti_dependences(Block* LCA, Node* load) const {
+  void verify_anti_dependences(Block* LCA, Node* load) {
     assert(LCA == get_block_for_node(load), "should already be scheduled");
-    const_cast<PhaseCFG*>(this)->insert_anti_dependences(LCA, load, true);
+    insert_anti_dependences(LCA, load, true);
   }
 
   bool move_to_next(Block* bx, uint b_index);
diff --git a/hotspot/src/share/vm/opto/cfgnode.hpp b/hotspot/src/share/vm/opto/cfgnode.hpp
index 74461aa..e795483 100644
--- a/hotspot/src/share/vm/opto/cfgnode.hpp
+++ b/hotspot/src/share/vm/opto/cfgnode.hpp
@@ -119,9 +119,6 @@
 // input in slot 0.
 class PhiNode : public TypeNode {
   const TypePtr* const _adr_type; // non-null only for Type::MEMORY nodes.
-  // The following fields are only used for data PhiNodes to indicate
-  // that the PhiNode represents the value of a known instance field.
-        int _inst_mem_id; // Instance memory id (node index of the memory Phi)
   const int _inst_id;     // Instance id of the memory slice.
   const int _inst_index;  // Alias index of the instance memory slice.
   // Array elements references have the same alias_idx but different offset.
@@ -141,13 +138,11 @@
   };
 
   PhiNode( Node *r, const Type *t, const TypePtr* at = NULL,
-           const int imid = -1,
            const int iid = TypeOopPtr::InstanceTop,
            const int iidx = Compile::AliasIdxTop,
            const int ioffs = Type::OffsetTop )
     : TypeNode(t,r->req()),
       _adr_type(at),
-      _inst_mem_id(imid),
       _inst_id(iid),
       _inst_index(iidx),
       _inst_offset(ioffs)
@@ -192,14 +187,11 @@
   virtual bool pinned() const { return in(0) != 0; }
   virtual const TypePtr *adr_type() const { verify_adr_type(true); return _adr_type; }
 
-  void  set_inst_mem_id(int inst_mem_id) { _inst_mem_id = inst_mem_id; }
-  const int inst_mem_id() const { return _inst_mem_id; }
   const int inst_id()     const { return _inst_id; }
   const int inst_index()  const { return _inst_index; }
   const int inst_offset() const { return _inst_offset; }
-  bool is_same_inst_field(const Type* tp, int mem_id, int id, int index, int offset) {
+  bool is_same_inst_field(const Type* tp, int id, int index, int offset) {
     return type()->basic_type() == tp->basic_type() &&
-           inst_mem_id() == mem_id &&
            inst_id()     == id     &&
            inst_index()  == index  &&
            inst_offset() == offset &&
diff --git a/hotspot/src/share/vm/opto/compile.cpp b/hotspot/src/share/vm/opto/compile.cpp
index e021924..dc88381 100644
--- a/hotspot/src/share/vm/opto/compile.cpp
+++ b/hotspot/src/share/vm/opto/compile.cpp
@@ -608,10 +608,6 @@
     n->as_MachBranch()->label_set(&fakeL, 0);
   }
   n->emit(buf, this->regalloc());
-
-  // Emitting into the scratch buffer should not fail
-  assert (!failing(), err_msg_res("Must not have pending failure. Reason is: %s", failure_reason()));
-
   if (is_branch) // Restore label.
     n->as_MachBranch()->label_set(saveL, save_bnum);
 
diff --git a/hotspot/src/share/vm/opto/connode.cpp b/hotspot/src/share/vm/opto/connode.cpp
index 3d99249..00aee51 100644
--- a/hotspot/src/share/vm/opto/connode.cpp
+++ b/hotspot/src/share/vm/opto/connode.cpp
@@ -446,9 +446,7 @@
 }
 
 uint CastIINode::cmp(const Node &n) const {
-  return TypeNode::cmp(n) &&
-         ((CastIINode&)n)._carry_dependency == _carry_dependency &&
-         ((CastIINode&)n)._range_check_dependency == _range_check_dependency;
+  return TypeNode::cmp(n) && ((CastIINode&)n)._carry_dependency == _carry_dependency;
 }
 
 Node *CastIINode::Identity(PhaseTransform *phase) {
@@ -525,7 +523,7 @@
 }
 
 Node *CastIINode::Ideal_DU_postCCP(PhaseCCP *ccp) {
-  if (_carry_dependency || _range_check_dependency) {
+  if (_carry_dependency) {
     return NULL;
   }
   return ConstraintCastNode::Ideal_DU_postCCP(ccp);
diff --git a/hotspot/src/share/vm/opto/doCall.cpp b/hotspot/src/share/vm/opto/doCall.cpp
index fee6eb7..f4ed1ae 100644
--- a/hotspot/src/share/vm/opto/doCall.cpp
+++ b/hotspot/src/share/vm/opto/doCall.cpp
@@ -205,22 +205,16 @@
 
       int morphism = profile.morphism();
       if (speculative_receiver_type != NULL) {
-        if (!too_many_traps(caller, bci, Deoptimization::Reason_speculate_class_check)) {
-          // We have a speculative type, we should be able to resolve
-          // the call. We do that before looking at the profiling at
-          // this invoke because it may lead to bimorphic inlining which
-          // a speculative type should help us avoid.
-          receiver_method = callee->resolve_invoke(jvms->method()->holder(),
-                                                   speculative_receiver_type);
-          if (receiver_method == NULL) {
-            speculative_receiver_type = NULL;
-          } else {
-            morphism = 1;
-          }
-        } else {
-          // speculation failed before. Use profiling at the call
-          // (could allow bimorphic inlining for instance).
+        // We have a speculative type, we should be able to resolve
+        // the call. We do that before looking at the profiling at
+        // this invoke because it may lead to bimorphic inlining which
+        // a speculative type should help us avoid.
+        receiver_method = callee->resolve_invoke(jvms->method()->holder(),
+                                                 speculative_receiver_type);
+        if (receiver_method == NULL) {
           speculative_receiver_type = NULL;
+        } else {
+          morphism = 1;
         }
       }
       if (receiver_method == NULL &&
@@ -258,7 +252,7 @@
                                     Deoptimization::Reason_bimorphic :
                                     (speculative_receiver_type == NULL ? Deoptimization::Reason_class_check : Deoptimization::Reason_speculate_class_check);
           if ((morphism == 1 || (morphism == 2 && next_hit_cg != NULL)) &&
-              !too_many_traps(caller, bci, reason)
+              !too_many_traps(jvms->method(), jvms->bci(), reason)
              ) {
             // Generate uncommon trap for class check failure path
             // in case of monomorphic or bimorphic virtual call site.
diff --git a/hotspot/src/share/vm/opto/graphKit.cpp b/hotspot/src/share/vm/opto/graphKit.cpp
index bfba3e9..38e0ce2 100644
--- a/hotspot/src/share/vm/opto/graphKit.cpp
+++ b/hotspot/src/share/vm/opto/graphKit.cpp
@@ -1683,9 +1683,6 @@
   const Type* elemtype = arytype->elem();
   BasicType elembt = elemtype->array_element_basic_type();
   Node* adr = array_element_address(ary, idx, elembt, arytype->size());
-  if (elembt == T_NARROWOOP) {
-    elembt = T_OBJECT; // To satisfy switch in LoadNode::make()
-  }
   Node* ld = make_load(ctl, adr, elemtype, elembt, arytype, MemNode::unordered);
   return ld;
 }
diff --git a/hotspot/src/share/vm/opto/lcm.cpp b/hotspot/src/share/vm/opto/lcm.cpp
index dd93b0f..8f6844f 100644
--- a/hotspot/src/share/vm/opto/lcm.cpp
+++ b/hotspot/src/share/vm/opto/lcm.cpp
@@ -246,14 +246,6 @@
       continue;
     }
 
-    // Check that node's control edge is not-null block's head or dominates it,
-    // otherwise we can't hoist it because there are other control dependencies.
-    Node* ctrl = mach->in(0);
-    if (ctrl != NULL && !(ctrl == not_null_block->head() ||
-        get_block_for_node(ctrl)->dominates(not_null_block))) {
-      continue;
-    }
-
     // check if the offset is not too high for implicit exception
     {
       intptr_t offset = 0;
@@ -391,12 +383,9 @@
   block->add_inst(best);
   map_node_to_block(best, block);
 
-  // Move the control dependence if it is pinned to not-null block.
-  // Don't change it in other cases: NULL or dominating control.
-  if (best->in(0) == not_null_block->head()) {
-    // Set it to control edge of null check.
-    best->set_req(0, proj->in(0)->in(0));
-  }
+  // Move the control dependence
+  if (best->in(0) && best->in(0) == old_block->head())
+    best->set_req(0, block->head());
 
   // Check for flag-killing projections that also need to be hoisted
   // Should be DU safe because no edge updates.
@@ -452,18 +441,6 @@
 
   latency_from_uses(nul_chk);
   latency_from_uses(best);
-
-  // insert anti-dependences to defs in this block
-  if (! best->needs_anti_dependence_check()) {
-    for (uint k = 1; k < block->number_of_nodes(); k++) {
-      Node *n = block->get_node(k);
-      if (n->needs_anti_dependence_check() &&
-          n->in(LoadNode::Memory) == best->in(StoreNode::Memory)) {
-        // Found anti-dependent load
-        insert_anti_dependences(block, n);
-      }
-    }
-  }
 }
 
 
@@ -1111,12 +1088,11 @@
     Block *sb = block->_succs[i];
     // Clone the entire area; ignoring the edge fixup for now.
     for( uint j = end; j > beg; j-- ) {
+      // It is safe here to clone a node with anti_dependence
+      // since clones dominate on each path.
       Node *clone = block->get_node(j-1)->clone();
       sb->insert_node(clone, 1);
       map_node_to_block(clone, sb);
-      if (clone->needs_anti_dependence_check()) {
-        insert_anti_dependences(sb, clone);
-      }
     }
   }
 
diff --git a/hotspot/src/share/vm/opto/library_call.cpp b/hotspot/src/share/vm/opto/library_call.cpp
index eb99517..f2a2937 100644
--- a/hotspot/src/share/vm/opto/library_call.cpp
+++ b/hotspot/src/share/vm/opto/library_call.cpp
@@ -6459,20 +6459,7 @@
 
 //------------------------------get_key_start_from_aescrypt_object-----------------------
 Node * LibraryCallKit::get_key_start_from_aescrypt_object(Node *aescrypt_object) {
-#ifdef PPC64
-  // MixColumns for decryption can be reduced by preprocessing MixColumns with round keys.
-  // Intel's extention is based on this optimization and AESCrypt generates round keys by preprocessing MixColumns.
-  // However, ppc64 vncipher processes MixColumns and requires the same round keys with encryption.
-  // The ppc64 stubs of encryption and decryption use the same round keys (sessionK[0]).
-  Node* objSessionK = load_field_from_object(aescrypt_object, "sessionK", "[[I", /*is_exact*/ false);
-  assert (objSessionK != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
-  if (objSessionK == NULL) {
-    return (Node *) NULL;
-  }
-  Node* objAESCryptKey = load_array_element(control(), objSessionK, intcon(0), TypeAryPtr::OOPS);
-#else
   Node* objAESCryptKey = load_field_from_object(aescrypt_object, "K", "[I", /*is_exact*/ false);
-#endif // PPC64
   assert (objAESCryptKey != NULL, "wrong version of com.sun.crypto.provider.AESCrypt");
   if (objAESCryptKey == NULL) return (Node *) NULL;
 
diff --git a/hotspot/src/share/vm/opto/loopnode.cpp b/hotspot/src/share/vm/opto/loopnode.cpp
index 8f2f228..e653557 100644
--- a/hotspot/src/share/vm/opto/loopnode.cpp
+++ b/hotspot/src/share/vm/opto/loopnode.cpp
@@ -278,16 +278,8 @@
     return false;
 
   // Allow funny placement of Safepoint
-  if (back_control->Opcode() == Op_SafePoint) {
-    if (UseCountedLoopSafepoints) {
-      // Leaving the safepoint on the backedge and creating a
-      // CountedLoop will confuse optimizations. We can't move the
-      // safepoint around because its jvm state wouldn't match a new
-      // location. Give up on that loop.
-      return false;
-    }
+  if (back_control->Opcode() == Op_SafePoint)
     back_control = back_control->in(TypeFunc::Control);
-  }
 
   // Controlling test for loop
   Node *iftrue = back_control;
diff --git a/hotspot/src/share/vm/opto/macro.cpp b/hotspot/src/share/vm/opto/macro.cpp
index d1e1f32..01b329c 100644
--- a/hotspot/src/share/vm/opto/macro.cpp
+++ b/hotspot/src/share/vm/opto/macro.cpp
@@ -401,7 +401,7 @@
   for (DUIterator_Fast kmax, k = region->fast_outs(kmax); k < kmax; k++) {
     Node* phi = region->fast_out(k);
     if (phi->is_Phi() && phi != mem &&
-        phi->as_Phi()->is_same_inst_field(phi_type, (int)mem->_idx, instance_id, alias_idx, offset)) {
+        phi->as_Phi()->is_same_inst_field(phi_type, instance_id, alias_idx, offset)) {
       return phi;
     }
   }
@@ -420,7 +420,7 @@
   GrowableArray <Node *> values(length, length, NULL, false);
 
   // create a new Phi for the value
-  PhiNode *phi = new (C) PhiNode(mem->in(0), phi_type, NULL, mem->_idx, instance_id, alias_idx, offset);
+  PhiNode *phi = new (C) PhiNode(mem->in(0), phi_type, NULL, instance_id, alias_idx, offset);
   transform_later(phi);
   value_phis->push(phi, mem->_idx);
 
diff --git a/hotspot/src/share/vm/opto/memnode.cpp b/hotspot/src/share/vm/opto/memnode.cpp
index a922a4e..80e25c9 100644
--- a/hotspot/src/share/vm/opto/memnode.cpp
+++ b/hotspot/src/share/vm/opto/memnode.cpp
@@ -1155,7 +1155,7 @@
     for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
       Node* phi = region->fast_out(i);
       if (phi->is_Phi() && phi != mem &&
-          phi->as_Phi()->is_same_inst_field(this_type, (int)mem->_idx, this_iid, this_index, this_offset)) {
+          phi->as_Phi()->is_same_inst_field(this_type, this_iid, this_index, this_offset)) {
         return phi;
       }
     }
@@ -1400,7 +1400,7 @@
     this_iid = base->_idx;
   }
   PhaseIterGVN* igvn = phase->is_IterGVN();
-  Node* phi = new (C) PhiNode(region, this_type, NULL, mem->_idx, this_iid, this_index, this_offset);
+  Node* phi = new (C) PhiNode(region, this_type, NULL, this_iid, this_index, this_offset);
   for (uint i = 1; i < region->req(); i++) {
     Node* x;
     Node* the_clone = NULL;
diff --git a/hotspot/src/share/vm/opto/output.cpp b/hotspot/src/share/vm/opto/output.cpp
index 95de2d6..0563ebb 100644
--- a/hotspot/src/share/vm/opto/output.cpp
+++ b/hotspot/src/share/vm/opto/output.cpp
@@ -1502,13 +1502,6 @@
       n->emit(*cb, _regalloc);
       current_offset  = cb->insts_size();
 
-      // Above we only verified that there is enough space in the instruction section.
-      // However, the instruction may emit stubs that cause code buffer expansion.
-      // Bail out here if expansion failed due to a lack of code cache space.
-      if (failing()) {
-        return;
-      }
-
 #ifdef ASSERT
       if (n->size(_regalloc) < (current_offset-instr_offset)) {
         n->dump();
@@ -1637,14 +1630,11 @@
   if (_method) {
     // Emit the exception handler code.
     _code_offsets.set_value(CodeOffsets::Exceptions, HandlerImpl::emit_exception_handler(*cb));
-    if (failing()) {
-      return; // CodeBuffer::expand failed
-    }
     // Emit the deopt handler code.
     _code_offsets.set_value(CodeOffsets::Deopt, HandlerImpl::emit_deopt_handler(*cb));
 
     // Emit the MethodHandle deopt handler code (if required).
-    if (has_method_handle_invokes() && !failing()) {
+    if (has_method_handle_invokes()) {
       // We can use the same code as for the normal deopt handler, we
       // just need a different entry point address.
       _code_offsets.set_value(CodeOffsets::DeoptMH, HandlerImpl::emit_deopt_handler(*cb));
diff --git a/hotspot/src/share/vm/opto/phaseX.cpp b/hotspot/src/share/vm/opto/phaseX.cpp
index 1782cb9..f090fcc 100644
--- a/hotspot/src/share/vm/opto/phaseX.cpp
+++ b/hotspot/src/share/vm/opto/phaseX.cpp
@@ -481,8 +481,6 @@
   uint current_idx = 0; // The current new node ID. Incremented after every assignment.
   for (uint i = 0; i < _useful.size(); i++) {
     Node* n = _useful.at(i);
-    // Sanity check that fails if we ever decide to execute this phase after EA
-    assert(!n->is_Phi() || n->as_Phi()->inst_mem_id() == -1, "should not be linked to data Phi");
     const Type* type = gvn->type_or_null(n);
     new_type_array.map(current_idx, type);
 
@@ -1380,18 +1378,6 @@
     i -= num_edges;    // we deleted 1 or more copies of this edge
   }
 
-  // Search for instance field data PhiNodes in the same region pointing to the old
-  // memory PhiNode and update their instance memory ids to point to the new node.
-  if (old->is_Phi() && old->as_Phi()->type()->has_memory() && old->in(0) != NULL) {
-    Node* region = old->in(0);
-    for (DUIterator_Fast imax, i = region->fast_outs(imax); i < imax; i++) {
-      PhiNode* phi = region->fast_out(i)->isa_Phi();
-      if (phi != NULL && phi->inst_mem_id() == (int)old->_idx) {
-        phi->set_inst_mem_id((int)nn->_idx);
-      }
-    }
-  }
-
   // Smash all inputs to 'old', isolating him completely
   Node *temp = new (C) Node(1);
   temp->init_req(0,nn);     // Add a use to nn to prevent him from dying
diff --git a/hotspot/src/share/vm/opto/stringopts.cpp b/hotspot/src/share/vm/opto/stringopts.cpp
index 70962e3..0f8e671 100644
--- a/hotspot/src/share/vm/opto/stringopts.cpp
+++ b/hotspot/src/share/vm/opto/stringopts.cpp
@@ -1641,11 +1641,16 @@
     }
     kit.store_String_value(kit.control(), result, char_array);
 
-    // The value field is final. Emit a barrier here to ensure that the effect
-    // of the initialization is committed to memory before any code publishes
-    // a reference to the newly constructed object (see Parse::do_exits()).
-    assert(AllocateNode::Ideal_allocation(result, _gvn) != NULL, "should be newly allocated");
-    kit.insert_mem_bar(Op_MemBarRelease, result);
+    // Do not let stores that initialize this object be reordered with
+    // a subsequent store that would make this object accessible by
+    // other threads.
+    // Record what AllocateNode this StoreStore protects so that
+    // escape analysis can go from the MemBarStoreStoreNode to the
+    // AllocateNode and eliminate the MemBarStoreStoreNode if possible
+    // based on the escape status of the AllocateNode.
+    AllocateNode* alloc = AllocateNode::Ideal_allocation(result, _gvn);
+    assert(alloc != NULL, "should be newly allocated");
+    kit.insert_mem_bar(Op_MemBarStoreStore, alloc->proj_out(AllocateNode::RawAddress));
   } else {
     result = C->top();
   }
diff --git a/hotspot/src/share/vm/opto/subnode.cpp b/hotspot/src/share/vm/opto/subnode.cpp
index 303d333..1e6c061 100644
--- a/hotspot/src/share/vm/opto/subnode.cpp
+++ b/hotspot/src/share/vm/opto/subnode.cpp
@@ -547,12 +547,8 @@
     // All unsigned values are LE -1 and GE 0.
     if (lo0 == 0 && hi0 == 0) {
       return TypeInt::CC_LE;            //   0 <= bot
-    } else if ((jint)lo0 == -1 && (jint)hi0 == -1) {
-      return TypeInt::CC_GE;            // -1 >= bot
     } else if (lo1 == 0 && hi1 == 0) {
       return TypeInt::CC_GE;            // bot >= 0
-    } else if ((jint)lo1 == -1 && (jint)hi1 == -1) {
-      return TypeInt::CC_LE;            // bot <= -1
     }
   } else {
     // We can use ranges of the form [lo..hi] if signs are the same.
diff --git a/hotspot/src/share/vm/opto/type.hpp b/hotspot/src/share/vm/opto/type.hpp
index 3c69445..4506c3a 100644
--- a/hotspot/src/share/vm/opto/type.hpp
+++ b/hotspot/src/share/vm/opto/type.hpp
@@ -882,7 +882,7 @@
 
   // If not InstanceTop or InstanceBot, indicates that this is
   // a particular instance of this type which is distinct.
-  // This is the node index of the allocation node creating this instance.
+  // This is the the node index of the allocation node creating this instance.
   int           _instance_id;
 
   // Extra type information profiling gave us. We propagate it the
diff --git a/hotspot/src/share/vm/prims/jniCheck.cpp b/hotspot/src/share/vm/prims/jniCheck.cpp
index 07e40ae..e95937a 100644
--- a/hotspot/src/share/vm/prims/jniCheck.cpp
+++ b/hotspot/src/share/vm/prims/jniCheck.cpp
@@ -461,11 +461,16 @@
 
 Method* jniCheck::validate_jmethod_id(JavaThread* thr, jmethodID method_id) {
   ASSERT_OOPS_ALLOWED;
-  // Do the jmethodID check
+  // do the fast jmethodID check first
   Method* moop = Method::checked_resolve_jmethod_id(method_id);
   if (moop == NULL) {
     ReportJNIFatalError(thr, fatal_wrong_class_or_method);
   }
+  // jmethodIDs are supposed to be weak handles in the class loader data,
+  // but that can be expensive so check it last
+  else if (!Method::is_method_id(method_id)) {
+    ReportJNIFatalError(thr, fatal_non_weak_method);
+  }
   return moop;
 }
 
diff --git a/hotspot/src/share/vm/prims/jvm.cpp b/hotspot/src/share/vm/prims/jvm.cpp
index f1b13f2..e6f5e88 100644
--- a/hotspot/src/share/vm/prims/jvm.cpp
+++ b/hotspot/src/share/vm/prims/jvm.cpp
@@ -1290,22 +1290,18 @@
 // and null permissions - which gives no permissions.
 oop create_dummy_access_control_context(TRAPS) {
   InstanceKlass* pd_klass = InstanceKlass::cast(SystemDictionary::ProtectionDomain_klass());
-  Handle obj = pd_klass->allocate_instance_handle(CHECK_NULL);
-  // Call constructor ProtectionDomain(null, null);
-  JavaValue result(T_VOID);
-  JavaCalls::call_special(&result, obj, KlassHandle(THREAD, pd_klass),
-                          vmSymbols::object_initializer_name(),
-                          vmSymbols::codesource_permissioncollection_signature(),
-                          Handle(), Handle(), CHECK_NULL);
+  // new ProtectionDomain(null,null);
+  oop null_protection_domain = pd_klass->allocate_instance(CHECK_NULL);
+  Handle null_pd(THREAD, null_protection_domain);
 
   // new ProtectionDomain[] {pd};
   objArrayOop context = oopFactory::new_objArray(pd_klass, 1, CHECK_NULL);
-  context->obj_at_put(0, obj());
+  context->obj_at_put(0, null_pd());
 
   // new AccessControlContext(new ProtectionDomain[] {pd})
   objArrayHandle h_context(THREAD, context);
-  oop acc = java_security_AccessControlContext::create(h_context, false, Handle(), CHECK_NULL);
-  return acc;
+  oop result = java_security_AccessControlContext::create(h_context, false, Handle(), CHECK_NULL);
+  return result;
 }
 
 JVM_ENTRY(jobject, JVM_DoPrivileged(JNIEnv *env, jclass cls, jobject action, jobject context, jboolean wrapException))
diff --git a/hotspot/src/share/vm/prims/unsafe.cpp b/hotspot/src/share/vm/prims/unsafe.cpp
index 5e39b38..0846b20 100644
--- a/hotspot/src/share/vm/prims/unsafe.cpp
+++ b/hotspot/src/share/vm/prims/unsafe.cpp
@@ -985,6 +985,14 @@
   }
 UNSAFE_END
 
+static jobject get_class_loader(JNIEnv* env, jclass cls) {
+  if (java_lang_Class::is_primitive(JNIHandles::resolve_non_null(cls))) {
+    return NULL;
+  }
+  Klass* k = java_lang_Class::as_Klass(JNIHandles::resolve_non_null(cls));
+  oop loader = k->class_loader();
+  return JNIHandles::make_local(env, loader);
+}
 
 UNSAFE_ENTRY(jclass, Unsafe_DefineClass0(JNIEnv *env, jobject unsafe, jstring name, jbyteArray data, int offset, int length))
   UnsafeWrapper("Unsafe_DefineClass");
@@ -993,7 +1001,7 @@
 
     int depthFromDefineClass0 = 1;
     jclass  caller = JVM_GetCallerClass(env, depthFromDefineClass0);
-    jobject loader = (caller == NULL) ? NULL : JVM_GetClassLoader(env, caller);
+    jobject loader = (caller == NULL) ? NULL : get_class_loader(env, caller);
     jobject pd     = (caller == NULL) ? NULL : JVM_GetProtectionDomain(env, caller);
 
     return Unsafe_DefineClass_impl(env, name, data, offset, length, loader, pd);
diff --git a/hotspot/src/share/vm/utilities/taskqueue.hpp b/hotspot/src/share/vm/utilities/taskqueue.hpp
index 8bdb38d..fb9ea61 100644
--- a/hotspot/src/share/vm/utilities/taskqueue.hpp
+++ b/hotspot/src/share/vm/utilities/taskqueue.hpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 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
@@ -453,9 +453,6 @@
   // Push task t onto the queue or onto the overflow stack.  Return true.
   inline bool push(E t);
 
-  // Try to push task t onto the queue only. Returns true if successful, false otherwise.
-  inline bool try_push_to_taskqueue(E t);
-
   // Attempt to pop from the overflow stack; return true if anything was popped.
   inline bool pop_overflow(E& t);
 
@@ -489,10 +486,6 @@
   return true;
 }
 
-template <class E, MEMFLAGS F, unsigned int N>
-bool OverflowTaskQueue<E, F, N>::try_push_to_taskqueue(E t) {
-  return taskqueue_t::push(t);
-}
 class TaskQueueSetSuper {
 protected:
   static int randomParkAndMiller(int* seed0);
diff --git a/hotspot/test/compiler/jsr292/VMAnonymousClasses.java b/hotspot/test/compiler/jsr292/VMAnonymousClasses.java
index 3b0a0c1..dc8b577 100644
--- a/hotspot/test/compiler/jsr292/VMAnonymousClasses.java
+++ b/hotspot/test/compiler/jsr292/VMAnonymousClasses.java
@@ -24,7 +24,7 @@
 /**
  * @test
  * @bug 8058828
- * @run main/bootclasspath/othervm -Xbatch VMAnonymousClasses
+ * @run main/bootclasspath -Xbatch VMAnonymousClasses
  */
 
 import jdk.internal.org.objectweb.asm.ClassWriter;
diff --git a/hotspot/test/compiler/native/TestDirtyInt.sh b/hotspot/test/compiler/native/TestDirtyInt.sh
index 31f253f..79749b4 100644
--- a/hotspot/test/compiler/native/TestDirtyInt.sh
+++ b/hotspot/test/compiler/native/TestDirtyInt.sh
@@ -30,19 +30,20 @@
 ## @run shell/timeout=30 TestDirtyInt.sh
 ##
 
-if [ -z "${TESTSRC}" ]; then
-    TESTSRC="${PWD}"
-    echo "TESTSRC not set.  Using "${TESTSRC}" as default"
+if [ "${TESTSRC}" = "" ]
+then
+  TESTSRC=${PWD}
+  echo "TESTSRC not set.  Using "${TESTSRC}" as default"
 fi
 echo "TESTSRC=${TESTSRC}"
 ## Adding common setup Variables for running shell tests.
 . ${TESTSRC}/../../test_env.sh
 
 # set platform-dependent variables
-if [ "$VM_OS" = "linux" -a "$VM_CPU" = "sparcv9" ]; then
+if [ $VM_OS == "linux" -a $VM_CPU == "sparcv9" ]; then
     echo "Testing on linux-sparc"
     gcc_cmd=`which gcc`
-    if [ -z "$gcc_cmd" ]; then
+    if [ "x$gcc_cmd" == "x" ]; then
         echo "WARNING: gcc not found. Cannot execute test." 2>&1
         exit 0;
     fi
@@ -67,9 +68,10 @@
     -Djava.library.path=${TESTSRC}${FS} TestDirtyInt"
 
 echo "$cmd"
-eval $cmd
+eval $cmd 
 
-if [ $? = 0 ]; then
+if [ $? = 0 ]
+then
     echo "Test Passed"
     exit 0
 fi
diff --git a/hotspot/test/compiler/stringopts/TestStringObjectInitialization.java b/hotspot/test/compiler/stringopts/TestStringObjectInitialization.java
index 2d09be1..6c6fa7e 100644
--- a/hotspot/test/compiler/stringopts/TestStringObjectInitialization.java
+++ b/hotspot/test/compiler/stringopts/TestStringObjectInitialization.java
@@ -27,7 +27,6 @@
 /*
  * @test
  * @bug 8159244
- * @requires vm.gc == "Parallel" | vm.gc == "null"
  * @summary Verifies that no partially initialized String object escapes from
  *          C2's String concat optimization in a highly concurrent setting.
  *          This test triggers the bug in about 1 out of 10 runs.
diff --git a/hotspot/test/gc/TestSoftReferencesBehaviorOnOOME.java b/hotspot/test/gc/TestSoftReferencesBehaviorOnOOME.java
index 87e5616..55fa598 100644
--- a/hotspot/test/gc/TestSoftReferencesBehaviorOnOOME.java
+++ b/hotspot/test/gc/TestSoftReferencesBehaviorOnOOME.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, Oracle and/or its affiliates. All rights reserved.
+ * 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
diff --git a/hotspot/test/runtime/lambda-features/TestInterfaceInit.java b/hotspot/test/runtime/lambda-features/TestInterfaceInit.java
index a6f057c..0493a60 100644
--- a/hotspot/test/runtime/lambda-features/TestInterfaceInit.java
+++ b/hotspot/test/runtime/lambda-features/TestInterfaceInit.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2014, 2016, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -25,8 +25,7 @@
 /*
  * @test
  * @bug 8034275
- * @bug 8163969
- * @summary [JDK 8u40] Test interface init: only for interfaces declaring default methods, when subclass inits
+ * @summary [JDK 8u40] Test interface initialization: only for interfaces declaring default methods
  * @run main TestInterfaceInit
  */
 import java.util.List;
@@ -40,59 +39,43 @@
    // Declares a default method and initializes
    interface I {
        boolean v = TestInterfaceInit.out(I.class);
-        default void ix() {}
+        default void x() {}
    }
 
    // Declares a default method and initializes
    interface J extends I {
        boolean v = TestInterfaceInit.out(J.class);
-       default void jx() {}
+       default void x() {}
    }
-   // No default method, has an abstract method, does not initialize
+   // No default method, does not initialize
    interface JN extends J {
        boolean v = TestInterfaceInit.out(JN.class);
-       public abstract void jnx();
    }
 
    // Declares a default method and initializes
    interface K extends I {
        boolean v = TestInterfaceInit.out(K.class);
-        default void kx() {}
+        default void x() {}
    }
 
-   // No default method, has a static method, does not initialize
+   // No default method, does not initialize
    interface KN extends K {
        boolean v = TestInterfaceInit.out(KN.class);
-       static void knx() {}
    }
 
    interface L extends JN, KN {
        boolean v = TestInterfaceInit.out(L.class);
-        default void lx() {}
-   }
-
-   static class ChildClass implements JN, KN {
-       boolean v = TestInterfaceInit.out(ChildClass.class);
-       public void jnx() {}
+        default void x() {}
    }
 
    public static void main(String[] args) {
        // Trigger initialization
        boolean v = L.v;
 
-       List<Class<?>> expectedCInitOrder = Arrays.asList(L.class);
+       List<Class<?>> expectedCInitOrder = Arrays.asList(I.class,J.class,K.class,L.class);
        if (!cInitOrder.equals(expectedCInitOrder)) {
          throw new RuntimeException(String.format("Class initialization array %s not equal to expected array %s", cInitOrder, expectedCInitOrder));
        }
-
-       ChildClass myC = new ChildClass();
-       boolean w = myC.v;
-
-       expectedCInitOrder = Arrays.asList(L.class,I.class,J.class,K.class,ChildClass.class);
-       if (!cInitOrder.equals(expectedCInitOrder)) {
-         throw new RuntimeException(String.format("Class initialization array %s not equal to expected array %s", cInitOrder, expectedCInitOrder));
-       }
-
    }
 
    static boolean out(Class c) {
diff --git a/hotspot/test/testlibrary/com/oracle/java/testlibrary/OutputAnalyzer.java b/hotspot/test/testlibrary/com/oracle/java/testlibrary/OutputAnalyzer.java
index 191a75c..b81f21a 100644
--- a/hotspot/test/testlibrary/com/oracle/java/testlibrary/OutputAnalyzer.java
+++ b/hotspot/test/testlibrary/com/oracle/java/testlibrary/OutputAnalyzer.java
@@ -24,8 +24,6 @@
 package com.oracle.java.testlibrary;
 
 import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
 
@@ -71,58 +69,6 @@
   }
 
   /**
-   * Verify that the stdout contents of output buffer is empty
-   *
-   * @throws RuntimeException
-   *             If stdout was not empty
-   */
-  public void stdoutShouldBeEmpty() {
-    if (!getStdout().isEmpty()) {
-      reportDiagnosticSummary();
-      throw new RuntimeException("stdout was not empty");
-    }
-  }
-
-  /**
-   * Verify that the stderr contents of output buffer is empty
-   *
-   * @throws RuntimeException
-   *             If stderr was not empty
-   */
-  public void stderrShouldBeEmpty() {
-    if (!getStderr().isEmpty()) {
-      reportDiagnosticSummary();
-      throw new RuntimeException("stderr was not empty");
-    }
-  }
-
-  /**
-   * Verify that the stdout contents of output buffer is not empty
-   *
-   * @throws RuntimeException
-   *             If stdout was empty
-   */
-  public void stdoutShouldNotBeEmpty() {
-    if (getStdout().isEmpty()) {
-      reportDiagnosticSummary();
-      throw new RuntimeException("stdout was empty");
-    }
-  }
-
-  /**
-   * Verify that the stderr contents of output buffer is not empty
-   *
-   * @throws RuntimeException
-   *             If stderr was empty
-   */
-  public void stderrShouldNotBeEmpty() {
-    if (getStderr().isEmpty()) {
-      reportDiagnosticSummary();
-      throw new RuntimeException("stderr was empty");
-    }
-  }
-
-    /**
    * Verify that the stdout and stderr contents of output buffer contains the string
    *
    * @param expectedString String that buffer should contain
@@ -419,18 +365,4 @@
   public int getExitValue() {
     return exitValue;
   }
-
-  /**
-   * Get the contents of the output buffer (stdout and stderr) as list of strings.
-   * Output will be split by newlines.
-   *
-   * @return Contents of the output buffer as list of strings
-   */
-  public List<String> asLines() {
-    return asLines(getOutput());
-  }
-
-  private List<String> asLines(String buffer) {
-    return Arrays.asList(buffer.split("(\\r\\n|\\n|\\r)"));
-  }
 }
diff --git a/hotspot/test/testlibrary/com/oracle/java/testlibrary/ProcessTools.java b/hotspot/test/testlibrary/com/oracle/java/testlibrary/ProcessTools.java
index 1953d18..649b7a1 100644
--- a/hotspot/test/testlibrary/com/oracle/java/testlibrary/ProcessTools.java
+++ b/hotspot/test/testlibrary/com/oracle/java/testlibrary/ProcessTools.java
@@ -187,36 +187,23 @@
     return executeProcess(pb);
   }
 
-    /**
-     * Executes a process, waits for it to finish and returns the process output.
-     * The process will have exited before this method returns.
-     * @param pb The ProcessBuilder to execute.
-     * @return The {@linkplain OutputAnalyzer} instance wrapping the process.
-     */
-    public static OutputAnalyzer executeProcess(ProcessBuilder pb) throws Exception {
-        OutputAnalyzer output = null;
-        Process p = null;
-        boolean failed = false;
-        try {
-            p = pb.start();
-            output = new OutputAnalyzer(p);
-            p.waitFor();
-
-            return output;
-        } catch (Throwable t) {
-            if (p != null) {
-                p.destroyForcibly().waitFor();
-            }
-
-            failed = true;
-            System.out.println("executeProcess() failed: " + t);
-            throw t;
-        } finally {
-            if (failed) {
-                System.err.println(getProcessLog(pb, output));
-            }
-        }
+  /**
+   * Executes a process, waits for it to finish and returns the process output.
+   * @param pb The ProcessBuilder to execute.
+   * @return The output from the process.
+   */
+  public static OutputAnalyzer executeProcess(ProcessBuilder pb) throws Throwable {
+    OutputAnalyzer output = null;
+    try {
+      output = new OutputAnalyzer(pb.start());
+      return output;
+    } catch (Throwable t) {
+      System.out.println("executeProcess() failed: " + t);
+      throw t;
+    } finally {
+      System.out.println(getProcessLog(pb, output));
     }
+  }
 
   /**
    * Executes a process, waits for it to finish and returns the process output.
diff --git a/hotspot/test/testlibrary/com/oracle/java/testlibrary/Utils.java b/hotspot/test/testlibrary/com/oracle/java/testlibrary/Utils.java
index b332c1e..8421519 100644
--- a/hotspot/test/testlibrary/com/oracle/java/testlibrary/Utils.java
+++ b/hotspot/test/testlibrary/com/oracle/java/testlibrary/Utils.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 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
@@ -260,8 +260,8 @@
             output = ProcessTools.executeProcess(jcmdLauncher.getCommand());
             output.shouldHaveExitValue(0);
 
-            // Search for a line starting with numbers (pid), followed by the key.
-            Pattern pattern = Pattern.compile("^([0-9]+)\\s.*(" + key + ")", Pattern.MULTILINE);
+            // Search for a line starting with numbers (pid), follwed by the key.
+            Pattern pattern = Pattern.compile("([0-9]+)\\s.*(" + key + ").*\\r?\\n");
             Matcher matcher = pattern.matcher(output.getStdout());
 
             int pid = -1;
diff --git a/hotspot/test/testlibrary_tests/whitebox/vm_flags/UintxTest.java b/hotspot/test/testlibrary_tests/whitebox/vm_flags/UintxTest.java
index 7141221..688962f 100644
--- a/hotspot/test/testlibrary_tests/whitebox/vm_flags/UintxTest.java
+++ b/hotspot/test/testlibrary_tests/whitebox/vm_flags/UintxTest.java
@@ -34,7 +34,7 @@
 import com.oracle.java.testlibrary.Platform;
 
 public class UintxTest {
-    private static final String FLAG_NAME = "VerifyGCStartAt";
+    private static final String FLAG_NAME = "TypeProfileLevel";
     private static final Long[] TESTS = {0L, 100L, (long) Integer.MAX_VALUE,
         (1L << 32L) - 1L, 1L << 32L};
     private static final Long[] EXPECTED_64 = TESTS;
diff --git a/hotspot/test/testlibrary_tests/whitebox/vm_flags/VmFlagTest.java b/hotspot/test/testlibrary_tests/whitebox/vm_flags/VmFlagTest.java
index 0818f21..fa8915f 100644
--- a/hotspot/test/testlibrary_tests/whitebox/vm_flags/VmFlagTest.java
+++ b/hotspot/test/testlibrary_tests/whitebox/vm_flags/VmFlagTest.java
@@ -55,7 +55,9 @@
     }
 
     private T getValue() {
-        return get.apply(flagName);
+        T t = get.apply(flagName);
+        System.out.println("T = " + t);
+        return t;
     }
 
     protected static <T> void runTest(String existentFlag, T[] tests,
diff --git a/jaxp/ASSEMBLY_EXCEPTION b/jaxp/ASSEMBLY_EXCEPTION
index 065b8d9..8b7ac1d 100644
--- a/jaxp/ASSEMBLY_EXCEPTION
+++ b/jaxp/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
-openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
-General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Sun at openjdk.java.net and
+openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
+GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Oracle gives you permission to link this
-    OpenJDK Code with certain code licensed by Oracle as indicated at
+    As a special exception, Sun gives you permission to link this
+    OpenJDK Code with certain code licensed by Sun as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Oracle.
+    governed by the licenses under which they were offered by Sun.
 
-As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
-to build an executable that includes those portions of necessary code that
-Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
-with the Classpath exception).  If you modify or add to the OpenJDK code,
-that new GPL2 code may still be combined with Designated Exception Modules
-if the new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
+build an executable that includes those portions of necessary code that Sun
+could not provide under GPL2 (or that Sun has provided under GPL2 with the
+Classpath exception).  If you modify or add to the OpenJDK code, that new
+GPL2 code may still be combined with Designated Exception Modules if the
+new code is made subject to this exception by its copyright holder.
diff --git a/jaxp/LICENSE b/jaxp/LICENSE
index 8b400c7..b40a0f4 100644
--- a/jaxp/LICENSE
+++ b/jaxp/LICENSE
@@ -3,7 +3,7 @@
 Version 2, June 1991
 
 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Everyone is permitted to copy and distribute verbatim copies of this license
 document, but changing it is not allowed.
@@ -287,8 +287,8 @@
     more details.
 
     You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+    with this program; if not, write to the Free Software Foundation, Inc., 59
+    Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Also add information on how to contact you by electronic and paper mail.
 
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/LiteralElement.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/LiteralElement.java
index c392cbe..e136357 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/LiteralElement.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/LiteralElement.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -9,7 +9,7 @@
  * (the "License"); you may not use this file except in compliance with
  * the License.  You may obtain a copy of the License at
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
@@ -17,6 +17,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+/*
+ * $Id: LiteralElement.java,v 1.2.4.1 2005/09/13 12:38:33 pvedula Exp $
+ */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler;
 
@@ -55,6 +58,8 @@
     // names are not known at compile time.
     private boolean _allAttributesUnique = false;
 
+    private final static String XMLNS_STRING = "xmlns";
+
     /**
      * Returns the QName for this literal element
      */
@@ -135,8 +140,8 @@
         // Treat default namespace as "" and not null
         if (prefix == null)
             prefix = Constants.EMPTYSTRING;
-        else if (prefix.equals(XMLNS_PREFIX))
-            return(XMLNS_PREFIX);
+        else if (prefix.equals(XMLNS_STRING))
+            return(XMLNS_STRING);
 
         // Check if we must translate the prefix
         final String alternative = stable.lookupPrefixAlias(prefix);
@@ -261,7 +266,7 @@
                 // Ignore special attributes (e.g. xmlns:prefix and xmlns)
                 final String prefix = qname.getPrefix();
                 if (prefix != null && prefix.equals(XMLNS_PREFIX) ||
-                    prefix == null && qname.getLocalPart().equals(XMLNS_PREFIX) ||
+                    prefix == null && qname.getLocalPart().equals("xmlns") ||
                     uri != null && uri.equals(XSLT_URI))
                 {
                     continue;
@@ -334,9 +339,9 @@
         il.append(methodGen.startElement());
 
         // The value of an attribute may depend on a (sibling) variable
-        int j = 0;
+        int j=0;
         while (j < elementCount())  {
-            final SyntaxTreeNode item = elementAt(j);
+            final SyntaxTreeNode item = (SyntaxTreeNode) elementAt(j);
             if (item instanceof Variable) {
                 item.translate(classGen, methodGen);
             }
@@ -345,12 +350,35 @@
 
         // Compile code to emit namespace attributes
         if (_accessedPrefixes != null) {
+            boolean declaresDefaultNS = false;
+
             for (Map.Entry<String, String> entry : _accessedPrefixes.entrySet()) {
                 final String prefix = entry.getKey();
                 final String uri = entry.getValue();
+
+                if (uri != Constants.EMPTYSTRING ||
+                        prefix != Constants.EMPTYSTRING)
+                {
+                    if (prefix == Constants.EMPTYSTRING) {
+                        declaresDefaultNS = true;
+                    }
+                    il.append(methodGen.loadHandler());
+                    il.append(new PUSH(cpg,prefix));
+                    il.append(new PUSH(cpg,uri));
+                    il.append(methodGen.namespace());
+                }
+            }
+
+            /*
+             * If our XslElement parent redeclares the default NS, and this
+             * element doesn't, it must be redeclared one more time.
+             */
+            if (!declaresDefaultNS && (_parent instanceof XslElement)
+                    && ((XslElement) _parent).declaresDefaultNS())
+            {
                 il.append(methodGen.loadHandler());
-                il.append(new PUSH(cpg, prefix));
-                il.append(new PUSH(cpg, uri));
+                il.append(new PUSH(cpg, Constants.EMPTYSTRING));
+                il.append(new PUSH(cpg, Constants.EMPTYSTRING));
                 il.append(methodGen.namespace());
             }
         }
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java
index 7088850..d15d90e 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Parser.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,6 +17,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+/*
+ * $Id: Parser.java,v 1.2.4.1 2005/09/13 12:14:32 pvedula Exp $
+ */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler;
 
@@ -34,7 +37,6 @@
 import java.io.File;
 import java.io.IOException;
 import java.io.StringReader;
-import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.List;
@@ -42,6 +44,7 @@
 import java.util.Properties;
 import java.util.Stack;
 import java.util.StringTokenizer;
+import java.util.Vector;
 import javax.xml.XMLConstants;
 import javax.xml.parsers.ParserConfigurationException;
 import javax.xml.parsers.SAXParser;
@@ -65,20 +68,20 @@
  */
 public class Parser implements Constants, ContentHandler {
 
-    private static final String XSL = "xsl";           // standard prefix
+    private static final String XSL = "xsl";            // standard prefix
     private static final String TRANSLET = "translet"; // extension prefix
 
     private Locator _locator = null;
 
-    private XSLTC _xsltc;                  // Reference to the compiler object.
-    private XPathParser _xpathParser;      // Reference to the XPath parser.
-    private ArrayList<ErrorMsg> _errors;   // Contains all compilation errors
-    private ArrayList<ErrorMsg> _warnings; // Contains all compilation warnings
+    private XSLTC _xsltc;             // Reference to the compiler object.
+    private XPathParser _xpathParser; // Reference to the XPath parser.
+    private Vector _errors;           // Contains all compilation errors
+    private Vector _warnings;         // Contains all compilation errors
 
     private Map<String, String>   _instructionClasses; // Maps instructions to classes
     private Map<String, String[]> _instructionAttrs;  // reqd and opt attrs
-    private Map<String, QName>    _qNames;
-    private Map<String, Map<String, QName>> _namespaces;
+    private Map<String, QName>   _qNames;
+    private Map<String, Map>     _namespaces;
     private QName       _useAttributeSets;
     private QName       _excludeResultPrefixes;
     private QName       _extensionElementPrefixes;
@@ -110,8 +113,8 @@
         _instructionAttrs    = new HashMap<>();
         _variableScope       = new HashMap<>();
         _template            = null;
-        _errors              = new ArrayList<>();
-        _warnings            = new ArrayList<>();
+        _errors              = new Vector();
+        _warnings            = new Vector();
         _symbolTable         = new SymbolTable();
         _xpathParser         = new XPathParser(this);
         _currentStylesheet   = null;
@@ -136,6 +139,7 @@
     public void setOutput(Output output) {
         if (_output != null) {
             if (_output.getImportPrecedence() <= output.getImportPrecedence()) {
+                String cdata = _output.getCdata();
                 output.mergeOutput(_output);
                 _output.disable();
                 _output = output;
@@ -169,13 +173,12 @@
         Object existing = _variableScope.get(var.getName().getStringRep());
         if (existing != null) {
             if (existing instanceof Stack) {
-                @SuppressWarnings("unchecked")
-                Stack<VariableBase> stack = (Stack<VariableBase>)existing;
+                Stack stack = (Stack)existing;
                 stack.push(var);
             }
             else if (existing instanceof VariableBase) {
-                Stack<VariableBase> stack = new Stack<>();
-                stack.push((VariableBase)existing);
+                Stack stack = new Stack();
+                stack.push(existing);
                 stack.push(var);
                 _variableScope.put(var.getName().getStringRep(), stack);
             }
@@ -188,8 +191,7 @@
     public void removeVariable(QName name) {
         Object existing = _variableScope.get(name.getStringRep());
         if (existing instanceof Stack) {
-            @SuppressWarnings("unchecked")
-            Stack<VariableBase> stack = (Stack<VariableBase>)existing;
+            Stack stack = (Stack)existing;
             if (!stack.isEmpty()) stack.pop();
             if (!stack.isEmpty()) return;
         }
@@ -199,14 +201,13 @@
     public VariableBase lookupVariable(QName name) {
         Object existing = _variableScope.get(name.getStringRep());
         if (existing instanceof VariableBase) {
-            return (VariableBase)existing;
+            return((VariableBase)existing);
         }
         else if (existing instanceof Stack) {
-            @SuppressWarnings("unchecked")
-            Stack<VariableBase> stack = (Stack<VariableBase>)existing;
-            return stack.peek();
+            Stack stack = (Stack)existing;
+            return((VariableBase)stack.peek());
         }
-        return null;
+        return(null);
     }
 
     public void setXSLTC(XSLTC xsltc) {
@@ -396,6 +397,7 @@
         try {
             if (stylesheet != null) {
                 stylesheet.parseContents(this);
+                final int precedence = stylesheet.getImportPrecedence();
                 final Iterator<SyntaxTreeNode> elements = stylesheet.elements();
                 while (elements.hasNext()) {
                     SyntaxTreeNode child = elements.next();
@@ -702,6 +704,8 @@
            new String[] {"stylesheet-prefix", "result-prefix"});
     }
 
+
+
     /**
      * Initialize the _instructionClasses map, which maps XSL element
      * names to Java classes in this package.
@@ -775,7 +779,6 @@
     /**
      * Add primops and base functions to the symbol table.
      */
-    @SuppressWarnings("unused")
     private void initSymbolTable() {
         MethodType I_V  = new MethodType(Type.Int, Type.Void);
         MethodType I_R  = new MethodType(Type.Int, Type.Real);
@@ -968,12 +971,12 @@
         String local, Attributes attributes)
     {
         SyntaxTreeNode node = null;
-        QName qname = getQName(uri, prefix, local);
+        QName  qname = getQName(uri, prefix, local);
         String className = _instructionClasses.get(qname.getStringRep());
 
         if (className != null) {
             try {
-                final Class<?> clazz = ObjectFactory.findProviderClass(className, true);
+                final Class clazz = ObjectFactory.findProviderClass(className, true);
                 node = (SyntaxTreeNode)clazz.newInstance();
                 node.setQName(qname);
                 node.setParser(this);
@@ -1020,7 +1023,7 @@
                 else {
                     Stylesheet sheet = _xsltc.getStylesheet();
                     if ((sheet != null) && (sheet.isExtension(uri))) {
-                        if (sheet != _parentStack.peek()) {
+                        if (sheet != (SyntaxTreeNode)_parentStack.peek()) {
                             node = new UnsupportedElement(uri, prefix, local, true);
                             UnsupportedElement elem = (UnsupportedElement)node;
                             ErrorMsg msg =
@@ -1153,6 +1156,7 @@
                     node.setParser(this);
                     node.setParent(parent);
                     node.setLineNumber(line);
+// System.out.println("e = " + text + " " + node);
                     return node;
                 }
             }
@@ -1187,7 +1191,7 @@
         if (size > 0) {
             System.err.println(new ErrorMsg(ErrorMsg.COMPILER_ERROR_KEY));
             for (int i = 0; i < size; i++) {
-                System.err.println("  " + _errors.get(i));
+                System.err.println("  " + _errors.elementAt(i));
             }
         }
     }
@@ -1200,7 +1204,7 @@
         if (size > 0) {
             System.err.println(new ErrorMsg(ErrorMsg.COMPILER_WARNING_KEY));
             for (int i = 0; i < size; i++) {
-                System.err.println("  " + _warnings.get(i));
+                System.err.println("  " + _warnings.elementAt(i));
             }
         }
     }
@@ -1213,42 +1217,42 @@
         case Constants.INTERNAL:
             // Unexpected internal errors, such as null-ptr exceptions, etc.
             // Immediately terminates compilation, no translet produced
-            _errors.add(error);
+            _errors.addElement(error);
             break;
         case Constants.UNSUPPORTED:
             // XSLT elements that are not implemented and unsupported ext.
             // Immediately terminates compilation, no translet produced
-            _errors.add(error);
+            _errors.addElement(error);
             break;
         case Constants.FATAL:
             // Fatal error in the stylesheet input (parsing or content)
             // Immediately terminates compilation, no translet produced
-            _errors.add(error);
+            _errors.addElement(error);
             break;
         case Constants.ERROR:
             // Other error in the stylesheet input (parsing or content)
             // Does not terminate compilation, no translet produced
-            _errors.add(error);
+            _errors.addElement(error);
             break;
         case Constants.WARNING:
             // Other error in the stylesheet input (content errors only)
             // Does not terminate compilation, a translet is produced
-            _warnings.add(error);
+            _warnings.addElement(error);
             break;
         }
     }
 
-    public ArrayList<ErrorMsg> getErrors() {
+    public Vector getErrors() {
         return _errors;
     }
 
-    public ArrayList<ErrorMsg> getWarnings() {
+    public Vector getWarnings() {
         return _warnings;
     }
 
     /************************ SAX2 ContentHandler INTERFACE *****************/
 
-    private Stack<SyntaxTreeNode> _parentStack = null;
+    private Stack _parentStack = null;
     private Map<String, String> _prefixMapping = null;
 
     /**
@@ -1258,7 +1262,7 @@
         _root = null;
         _target = null;
         _prefixMapping = null;
-        _parentStack = new Stack<>();
+        _parentStack = new Stack();
     }
 
     /**
@@ -1314,7 +1318,7 @@
             _root = element;
         }
         else {
-            SyntaxTreeNode parent = _parentStack.peek();
+            SyntaxTreeNode parent = (SyntaxTreeNode)_parentStack.peek();
             parent.addElement(element);
             element.setParent(parent);
         }
@@ -1345,7 +1349,7 @@
      */
     public void characters(char[] ch, int start, int length) {
         String string = new String(ch, start, length);
-        SyntaxTreeNode parent = _parentStack.peek();
+        SyntaxTreeNode parent = (SyntaxTreeNode)_parentStack.peek();
 
         if (string.length() == 0) return;
 
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Stylesheet.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Stylesheet.java
index 09061ea..5894996 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Stylesheet.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/Stylesheet.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -31,7 +31,6 @@
 import com.sun.org.apache.bcel.internal.generic.GETSTATIC;
 import com.sun.org.apache.bcel.internal.generic.INVOKEINTERFACE;
 import com.sun.org.apache.bcel.internal.generic.INVOKESPECIAL;
-import com.sun.org.apache.bcel.internal.generic.INVOKESTATIC;
 import com.sun.org.apache.bcel.internal.generic.INVOKEVIRTUAL;
 import com.sun.org.apache.bcel.internal.generic.ISTORE;
 import com.sun.org.apache.bcel.internal.generic.InstructionHandle;
@@ -1253,10 +1252,6 @@
                                 classGen.getConstantPool());
         transf.addException("com.sun.org.apache.xalan.internal.xsltc.TransletException");
 
-        // call resetPrefixIndex at the beginning of transform
-        final int check = cpg.addMethodref(BASIS_LIBRARY_CLASS, "resetPrefixIndex", "()V");
-        il.append(new INVOKESTATIC(check));
-
         // Define and initialize current with the root node
         final LocalVariableGen current =
             transf.addLocalVariable("current",
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/SyntaxTreeNode.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/SyntaxTreeNode.java
index 01ef38b..1e8ad86 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/SyntaxTreeNode.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/SyntaxTreeNode.java
@@ -73,7 +73,7 @@
     protected QName _qname;                    // The element QName
     private int _line;                         // Source file line number
     protected AttributesImpl _attributes = null;   // Attributes of this element
-    private Map<String, String> _prefixMapping = null; // Namespace declarations
+    private   Map<String, String> _prefixMapping = null; // Namespace declarations
 
     // Sentinel - used to denote unrecognised syntaxt tree nodes.
     protected static final SyntaxTreeNode Dummy = new AbsolutePathPattern(null);
@@ -829,7 +829,7 @@
      * @param pos The child node's position.
      * @return The child node.
      */
-    protected final SyntaxTreeNode elementAt(int pos) {
+    protected final Object elementAt(int pos) {
         return _contents.get(pos);
     }
 
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
index 631edbd..3218181 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XSLTC.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 2015, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,6 +17,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+/*
+ * $Id: XSLTC.java,v 1.2.4.1 2005/09/05 09:51:38 pvedula Exp $
+ */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler;
 
@@ -36,7 +39,6 @@
 import java.io.IOException;
 import java.io.InputStream;
 import java.net.URL;
-import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Date;
 import java.util.Enumeration;
@@ -281,7 +283,7 @@
     }
 
     /*
-     * Function loads an external extension function.
+     * Function loads an external extension functions.
      * The filtering of function types (external,internal) takes place in FunctionCall class
      *
      */
@@ -596,18 +598,18 @@
     }
 
     /**
-     * Get a list of all compile error messages
-     * @return A List containing all compile error messages
+     * Get a Vector containing all compile error messages
+     * @return A Vector containing all compile error messages
      */
-    public ArrayList<ErrorMsg> getErrors() {
+    public Vector getErrors() {
         return _parser.getErrors();
     }
 
     /**
-     * Get a list of all compile warning messages
-     * @return A List containing all compile error messages
+     * Get a Vector containing all compile warning messages
+     * @return A Vector containing all compile error messages
      */
-    public ArrayList<ErrorMsg> getWarnings() {
+    public Vector getWarnings() {
         return _parser.getWarnings();
     }
 
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XslElement.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XslElement.java
index e94ebb1..e04bab7 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XslElement.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/compiler/XslElement.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2015, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,6 +17,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+/*
+ * $Id: XslElement.java,v 1.2.4.1 2005/09/12 11:39:55 pvedula Exp $
+ */
 
 package com.sun.org.apache.xalan.internal.xsltc.compiler;
 
@@ -57,6 +60,14 @@
         displayContents(indent + IndentIncrement);
     }
 
+    /**
+     * This method is now deprecated. The new implemation of this class
+     * never declares the default NS.
+     */
+    public boolean declaresDefaultNS() {
+        return false;
+    }
+
     public void parseContents(Parser parser) {
         final SymbolTable stable = parser.getSymbolTable();
 
@@ -199,6 +210,7 @@
      * on the handler (vii) evaluates the contents (viii) calls endElement().
      */
     public void translate(ClassGenerator classGen, MethodGenerator methodGen) {
+        LocalVariableGen local = null;
         final ConstantPoolGen cpg = classGen.getConstantPool();
         final InstructionList il = methodGen.getInstructionList();
 
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/runtime/BasisLibrary.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/runtime/BasisLibrary.java
index 804b154..dc3a3ce 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/runtime/BasisLibrary.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/runtime/BasisLibrary.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -48,7 +48,6 @@
 import java.text.NumberFormat;
 import java.util.Locale;
 import java.util.ResourceBundle;
-import java.util.concurrent.atomic.AtomicInteger;
 import javax.xml.transform.dom.DOMSource;
 import org.w3c.dom.Attr;
 import org.w3c.dom.Document;
@@ -1531,25 +1530,16 @@
     }
 
     /**
-     * These functions are used in the execution of xsl:element to generate
-     * and reset namespace prefix index local to current transformation process
+     * This function is used in the execution of xsl:element
      */
+    private static int prefixIndex = 0;
+
     public static String generatePrefix() {
-        return ("ns" + threadLocalPrefixIndex.get().getAndIncrement());
+        synchronized (BasisLibrary.class) {
+            return ("ns" + prefixIndex++);
+        }
     }
 
-    public static void resetPrefixIndex() {
-        threadLocalPrefixIndex.get().set(0);
-    }
-
-    private static final ThreadLocal<AtomicInteger> threadLocalPrefixIndex =
-        new ThreadLocal<AtomicInteger>() {
-            @Override
-            protected AtomicInteger initialValue() {
-                return new AtomicInteger();
-            }
-        };
-
     public static final String RUN_TIME_INTERNAL_ERR =
                                            "RUN_TIME_INTERNAL_ERR";
     public static final String RUN_TIME_COPY_ERR =
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java
index bce2c3a..8bbc541 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TemplatesHandlerImpl.java
@@ -1,13 +1,13 @@
 /*
- * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
  */
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
+ * Copyright 2001-2004 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
  *     http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -17,9 +17,18 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+/*
+ * $Id: TemplatesHandlerImpl.java,v 1.2.4.1 2005/09/06 12:09:03 pvedula Exp $
+ */
 
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
+import javax.xml.XMLConstants;
+import javax.xml.transform.Source;
+import javax.xml.transform.Templates;
+import javax.xml.transform.TransformerException;
+import javax.xml.transform.URIResolver;
+import javax.xml.transform.sax.TemplatesHandler;
 import com.sun.org.apache.xalan.internal.XalanConstants;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.CompilerException;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.Parser;
@@ -28,19 +37,15 @@
 import com.sun.org.apache.xalan.internal.xsltc.compiler.SyntaxTreeNode;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.XSLTC;
 import com.sun.org.apache.xalan.internal.xsltc.compiler.util.ErrorMsg;
-import java.util.ArrayList;
-import javax.xml.XMLConstants;
-import javax.xml.transform.Source;
-import javax.xml.transform.Templates;
-import javax.xml.transform.TransformerException;
-import javax.xml.transform.URIResolver;
-import javax.xml.transform.sax.TemplatesHandler;
+
 import org.xml.sax.ContentHandler;
 import org.xml.sax.InputSource;
 import org.xml.sax.Locator;
 import org.xml.sax.SAXException;
 import org.xml.sax.Attributes;
 
+import java.util.Vector;
+
 /**
  * Implementation of a JAXP1.1 TemplatesHandler
  * @author Morten Jorgensen
@@ -263,13 +268,13 @@
                 }
             }
             else {
-                StringBuilder errorMessage = new StringBuilder();
-                ArrayList<ErrorMsg> errors = _parser.getErrors();
+                StringBuffer errorMessage = new StringBuffer();
+                Vector errors = _parser.getErrors();
                 final int count = errors.size();
                 for (int i = 0; i < count; i++) {
                     if (errorMessage.length() > 0)
                         errorMessage.append('\n');
-                    errorMessage.append(errors.get(i).toString());
+                    errorMessage.append(errors.elementAt(i).toString());
                 }
                 throw new SAXException(ErrorMsg.JAXP_COMPILE_ERR, new TransformerException(errorMessage.toString()));
             }
diff --git a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java
index e30fffd..b37c8f4 100644
--- a/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java
+++ b/jaxp/src/com/sun/org/apache/xalan/internal/xsltc/trax/TransformerFactoryImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2007, 2015, Oracle and/or its affiliates. All rights reserved.
  */
 /*
  * Licensed to the Apache Software Foundation (ASF) under one or more
@@ -17,6 +17,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+/*
+ * $Id: TransformerFactoryImpl.java,v 1.8 2007/04/09 21:30:41 joehw Exp $
+ */
 
 package com.sun.org.apache.xalan.internal.xsltc.trax;
 
@@ -45,7 +48,6 @@
 import java.io.InputStream;
 import java.net.MalformedURLException;
 import java.net.URL;
-import java.util.ArrayList;
 import java.util.Enumeration;
 import java.util.Map;
 import java.util.Properties;
@@ -590,7 +592,7 @@
         }
 
         // Inefficient, but array is small
-        for (int i = 0; i < features.length; i++) {
+        for (int i =0; i < features.length; i++) {
             if (name.equals(features[i])) {
                 return true;
             }
@@ -797,7 +799,7 @@
     /**
      * Pass warning messages from the compiler to the error listener
      */
-    private void passWarningsToListener(ArrayList<ErrorMsg> messages)
+    private void passWarningsToListener(Vector messages)
         throws TransformerException
     {
         if (_errorListener == null || messages == null) {
@@ -806,7 +808,7 @@
         // Pass messages to listener, one by one
         final int count = messages.size();
         for (int pos = 0; pos < count; pos++) {
-            ErrorMsg msg = messages.get(pos);
+            ErrorMsg msg = (ErrorMsg)messages.elementAt(pos);
             // Workaround for the TCK failure ErrorListener.errorTests.error001.
             if (msg.isWarningError())
                 _errorListener.error(
@@ -820,7 +822,7 @@
     /**
      * Pass error messages from the compiler to the error listener
      */
-    private void passErrorsToListener(ArrayList<ErrorMsg> messages) {
+    private void passErrorsToListener(Vector messages) {
         try {
             if (_errorListener == null || messages == null) {
                 return;
@@ -828,7 +830,7 @@
             // Pass messages to listener, one by one
             final int count = messages.size();
             for (int pos = 0; pos < count; pos++) {
-                String message = messages.get(pos).toString();
+                String message = messages.elementAt(pos).toString();
                 _errorListener.error(new TransformerException(message));
             }
         }
@@ -1002,39 +1004,40 @@
         }
 
         // Check that the transformation went well before returning
-        if (bytecodes == null) {
-            ArrayList<ErrorMsg> errs = xsltc.getErrors();
-            ErrorMsg err;
-            if (errs != null) {
-                err = errs.get(errs.size() - 1);
-            } else {
-                err = new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR);
-            }
-            Throwable cause = err.getCause();
-            TransformerConfigurationException exc;
-            if (cause != null) {
-                exc =  new TransformerConfigurationException(cause.getMessage(), cause);
-            } else {
-                exc =  new TransformerConfigurationException(err.toString());
-            }
-
-            // Pass compiler errors to the error listener
-            if (_errorListener != null) {
-                passErrorsToListener(xsltc.getErrors());
-
-                // As required by TCK 1.2, send a fatalError to the
-                // error listener because compilation of the stylesheet
-                // failed and no further processing will be possible.
-                try {
-                    _errorListener.fatalError(exc);
-                } catch (TransformerException te) {
-                    // well, we tried.
-                }
-            } else {
-                xsltc.printErrors();
-            }
-            throw exc;
+    if (bytecodes == null) {
+        Vector errs = xsltc.getErrors();
+        ErrorMsg err;
+        if (errs != null) {
+            err = (ErrorMsg)errs.elementAt(errs.size()-1);
+        } else {
+            err = new ErrorMsg(ErrorMsg.JAXP_COMPILE_ERR);
         }
+        Throwable cause = err.getCause();
+        TransformerConfigurationException exc;
+        if (cause != null) {
+            exc =  new TransformerConfigurationException(cause.getMessage(), cause);
+        } else {
+            exc =  new TransformerConfigurationException(err.toString());
+        }
+
+        // Pass compiler errors to the error listener
+        if (_errorListener != null) {
+            passErrorsToListener(xsltc.getErrors());
+
+            // As required by TCK 1.2, send a fatalError to the
+            // error listener because compilation of the stylesheet
+            // failed and no further processing will be possible.
+            try {
+                _errorListener.fatalError(exc);
+            } catch (TransformerException te) {
+                // well, we tried.
+            }
+        }
+        else {
+            xsltc.printErrors();
+        }
+        throw exc;
+    }
 
         return new TemplatesImpl(bytecodes, transletName,
             xsltc.getOutputProperties(), _indentNumber, this);
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java b/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java
index c4268dc..3758f39 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/dom/DOMNormalizer.java
@@ -26,7 +26,6 @@
 import java.io.StringReader;
 import java.util.Vector;
 
-import com.sun.org.apache.xerces.internal.dom.AbortException;
 import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.RevalidationHandler;
 import com.sun.org.apache.xerces.internal.impl.dtd.DTDGrammar;
@@ -159,6 +158,11 @@
     // attribute value normalization
     final XMLString fNormalizedValue = new XMLString(new char[16], 0, 0);
 
+    /**
+     * If the user stops the process, this exception will be thrown.
+     */
+    public static final RuntimeException abort = new RuntimeException();
+
     //DTD validator
     private XMLDTDValidator fDTDValidator;
 
@@ -239,10 +243,11 @@
                                         XMLGrammarDescription.XML_SCHEMA, fValidationHandler);
                                 fValidationHandler = null;
                         }
-                } catch (AbortException e) {
-                    return;
-                } catch (RuntimeException e) {
-                    throw e;    // otherwise re-throw.
+                }
+                catch (RuntimeException e) {
+            if( e==abort )
+                return; // processing aborted by the user
+            throw e;    // otherwise re-throw.
                 }
 
         }
@@ -1367,10 +1372,10 @@
             error.fRelatedData = locator.fRelatedNode;
 
             if(!errorHandler.handleError(error))
-                throw new AbortException();
+                throw abort;
         }
         if( severity==DOMError.SEVERITY_FATAL_ERROR )
-            throw new AbortException();
+            throw abort;
     }
 
     protected final void updateQName (Node node, QName qname){
@@ -2039,4 +2044,5 @@
         return null;
     }
 
+
 }  // DOMNormalizer class
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java
index e29d296..ac26f80 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XML11EntityScanner.java
@@ -752,7 +752,7 @@
             load(0, true, true);
         }
         else if (fCurrentEntity.position == fCurrentEntity.count - 1) {
-            invokeListeners(1);
+            invokeListeners(0);
             fCurrentEntity.ch[0] = fCurrentEntity.ch[fCurrentEntity.count - 1];
             load(1, false, false);
             fCurrentEntity.position = 0;
@@ -904,7 +904,7 @@
             load(0, true, true);
         }
         else if (fCurrentEntity.position == fCurrentEntity.count - 1) {
-            invokeListeners(1);
+            invokeListeners(0);
             fCurrentEntity.ch[0] = fCurrentEntity.ch[fCurrentEntity.count - 1];
             load(1, false, false);
             fCurrentEntity.startPosition = 0;
@@ -1352,7 +1352,7 @@
                         fCurrentEntity.lineNumber++;
                         fCurrentEntity.columnNumber = 1;
                         if (fCurrentEntity.position == fCurrentEntity.count - 1) {
-                            invokeListeners(1);
+                            invokeListeners(0);
                             fCurrentEntity.ch[0] = (char)c;
                             entityChanged = load(1, true, false);
                             if (!entityChanged) {
@@ -1406,9 +1406,8 @@
                     fCurrentEntity.lineNumber++;
                     fCurrentEntity.columnNumber = 1;
                     if (fCurrentEntity.position == fCurrentEntity.count - 1) {
-                        invokeListeners(1);
                         fCurrentEntity.ch[0] = (char)c;
-                        entityChanged = load(1, true, false);
+                        entityChanged = load(1, true, true);
                         if (!entityChanged) {
                             // the load change the position to be 1,
                             // need to restore it when entity not changed
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java
index d63df64..135eb5e 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDTDScannerImpl.java
@@ -3,13 +3,11 @@
  */
 
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
-
+ * Copyright 2005 The Apache Software Foundation.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
  *
  *      http://www.apache.org/licenses/LICENSE-2.0
  *
@@ -21,19 +19,17 @@
  */
 
 package com.sun.org.apache.xerces.internal.impl;
+import com.sun.xml.internal.stream.dtd.nonvalidating.DTDGrammar;
+import java.io.EOFException;
+import java.io.IOException;
 
-import com.sun.org.apache.xerces.internal.impl.Constants;
 import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter;
 
-import com.sun.org.apache.xerces.internal.impl.XMLErrorReporter;
-import com.sun.org.apache.xerces.internal.impl.XMLEntityHandler;
 import com.sun.org.apache.xerces.internal.util.SymbolTable;
 import com.sun.org.apache.xerces.internal.util.XMLAttributesImpl;
 import com.sun.org.apache.xerces.internal.util.XMLChar;
 import com.sun.org.apache.xerces.internal.util.XMLStringBuffer;
 
-import com.sun.org.apache.xerces.internal.utils.XMLLimitAnalyzer;
-import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 import com.sun.org.apache.xerces.internal.xni.XMLDTDContentModelHandler;
 import com.sun.org.apache.xerces.internal.xni.XMLDTDHandler;
 import com.sun.org.apache.xerces.internal.xni.XMLResourceIdentifier;
@@ -45,9 +41,8 @@
 import com.sun.org.apache.xerces.internal.xni.parser.XMLDTDScanner;
 import com.sun.org.apache.xerces.internal.xni.parser.XMLInputSource;
 import com.sun.org.apache.xerces.internal.xni.Augmentations;
-import com.sun.xml.internal.stream.dtd.nonvalidating.DTDGrammar;
-import java.io.EOFException;
-import java.io.IOException;
+import com.sun.org.apache.xerces.internal.utils.XMLLimitAnalyzer;
+import com.sun.org.apache.xerces.internal.utils.XMLSecurityManager;
 
 /**
  * This class is responsible for scanning the declarations found
@@ -391,25 +386,15 @@
      */
     @Override
     public boolean skipDTD(boolean supportDTD) throws IOException {
-        if (supportDTD)
-            return false;
-
-        fStringBuffer.clear();
-        while (fEntityScanner.scanData("]", fStringBuffer)) {
-            int c = fEntityScanner.peekChar();
-            if (c != -1) {
-                if (XMLChar.isHighSurrogate(c)) {
-                    scanSurrogates(fStringBuffer);
-                }
-                if (isInvalidLiteral(c)) {
-                    reportFatalError("InvalidCharInDTD",
-                        new Object[] { Integer.toHexString(c) });
-                    fEntityScanner.scanChar(null);
-                }
+        if (!supportDTD) {
+            fStringBuffer.clear();
+            if (!fEntityScanner.scanData("]", fStringBuffer)) {
+                fEntityScanner.fCurrentEntity.position--;
             }
+
+            return true;
         }
-        fEntityScanner.fCurrentEntity.position--;
-        return true;
+        return false;
     }
 
     //
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
index 6d197c5..ef118f0 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentFragmentScannerImpl.java
@@ -3,14 +3,13 @@
  */
 
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
+ * Copyright 2005 The Apache Software Foundation.
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
@@ -19,6 +18,7 @@
  * limitations under the License.
  */
 
+
 package com.sun.org.apache.xerces.internal.impl;
 
 import com.sun.org.apache.xerces.internal.impl.msg.XMLMessageFormatter;
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java
index 6c62345..4330492 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLDocumentScannerImpl.java
@@ -3,14 +3,13 @@
  */
 
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
+ * Copyright 2005 The Apache Software Foundation.
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,6 +20,7 @@
 
 package com.sun.org.apache.xerces.internal.impl;
 
+
 import com.sun.org.apache.xerces.internal.impl.dtd.XMLDTDDescription;
 import com.sun.org.apache.xerces.internal.impl.validation.ValidationManager;
 import com.sun.org.apache.xerces.internal.util.NamespaceSupport;
@@ -1107,7 +1107,8 @@
                             if (!moreToScan) {
                                 // end doctype declaration
                                 if (!fEntityScanner.skipChar(']', null)) {
-                                    reportFatalError("DoctypedeclNotClosed", new Object[]{fDoctypeName});
+                                    reportFatalError("EXPECTED_SQUARE_BRACKET_TO_CLOSE_INTERNAL_SUBSET",
+                                            null);
                                 }
                                 fEntityScanner.skipSpaces();
                                 if (!fEntityScanner.skipChar('>', null)) {
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java
index ff02bba..8b02b2e 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLEntityScanner.java
@@ -44,8 +44,8 @@
 import java.io.InputStream;
 import java.io.InputStreamReader;
 import java.io.Reader;
-import java.util.ArrayList;
 import java.util.Locale;
+import java.util.Vector;
 
 /**
  * Implements the entity scanner methods.
@@ -58,10 +58,11 @@
  */
 public class XMLEntityScanner implements XMLLocator  {
 
-    protected Entity.ScannedEntity fCurrentEntity = null;
+
+    protected Entity.ScannedEntity fCurrentEntity = null ;
     protected int fBufferSize = XMLEntityManager.DEFAULT_BUFFER_SIZE;
 
-    protected XMLEntityManager fEntityManager;
+    protected XMLEntityManager fEntityManager ;
 
     /** Security manager. */
     protected XMLSecurityManager fSecurityManager = null;
@@ -71,9 +72,8 @@
 
     /** Debug switching readers for encodings. */
     private static final boolean DEBUG_ENCODINGS = false;
-
     /** Listeners which should know when load is being called */
-    private ArrayList<XMLBufferListener> listeners = new ArrayList<>();
+    private Vector listeners = new Vector();
 
     private static final boolean [] VALID_NAMES = new boolean[127];
 
@@ -140,10 +140,9 @@
         VALID_NAMES[58]=true;
         VALID_NAMES[95]=true;
     }
-
-    // Remember, that the XML version has explicitly been set,
+    // SAPJVM: Remember, that the XML version has explicitly been set,
     // so that XMLStreamReader.getVersion() can find that out.
-    protected boolean xmlVersionSetExplicitly = false;
+    boolean xmlVersionSetExplicitly = false;
 
     // indicates that the operation is for detecting XML version
     boolean detectingVersion = false;
@@ -262,7 +261,7 @@
      * @param xmlVersion the XML version of the current entity
      */
     public final void setXMLVersion(String xmlVersion) {
-        xmlVersionSetExplicitly = true;
+        xmlVersionSetExplicitly = true; // SAPJVM
         fCurrentEntity.xmlVersion = xmlVersion;
     } // setXMLVersion(String)
 
@@ -554,7 +553,8 @@
         // scan character
         int offset = fCurrentEntity.position;
         int c = fCurrentEntity.ch[fCurrentEntity.position++];
-        if (c == '\n' || (c == '\r' && isExternal)) {
+        if (c == '\n' ||
+                (c == '\r' && isExternal)) {
             fCurrentEntity.lineNumber++;
             fCurrentEntity.columnNumber = 1;
             if (fCurrentEntity.position == fCurrentEntity.count) {
@@ -1027,7 +1027,7 @@
         if (fCurrentEntity.position == fCurrentEntity.count) {
             load(0, true, true);
         } else if (fCurrentEntity.position == fCurrentEntity.count - 1) {
-            invokeListeners(1);
+            invokeListeners(0);
             fCurrentEntity.ch[0] = fCurrentEntity.ch[fCurrentEntity.count - 1];
             load(1, false, false);
             fCurrentEntity.position = 0;
@@ -1186,7 +1186,7 @@
         if (fCurrentEntity.position == fCurrentEntity.count) {
             load(0, true, true);
         } else if (fCurrentEntity.position == fCurrentEntity.count - 1) {
-            invokeListeners(1);
+            invokeListeners(0);
             fCurrentEntity.ch[0] = fCurrentEntity.ch[fCurrentEntity.count - 1];
             load(1, false, false);
             fCurrentEntity.position = 0;
@@ -1339,8 +1339,8 @@
      * <p>
      * <strong>Note:</strong> The characters are consumed.
      * <p>
-     * <strong>Note:</strong> This assumes that the delimiter contains at
-     * least one character.
+     * <strong>Note:</strong> This assumes that the length of the delimiter
+     * and that the delimiter contains at least one character.
      * <p>
      * <strong>Note:</strong> This method does not guarantee to return
      * the longest run of character data. This method may return before
@@ -1523,7 +1523,7 @@
         } while (!done);
         return !done;
 
-    } // scanData(String, XMLStringBuffer)
+    } // scanData(String,XMLString)
 
     /**
      * Skips a character appearing immediately on the input.
@@ -1650,7 +1650,7 @@
                     fCurrentEntity.lineNumber++;
                     fCurrentEntity.columnNumber = 1;
                     if (fCurrentEntity.position == fCurrentEntity.count - 1) {
-                        invokeListeners(1);
+                        invokeListeners(0);
                         fCurrentEntity.ch[0] = (char)c;
                         entityChanged = load(1, true, false);
                         if (!entityChanged){
@@ -1827,7 +1827,8 @@
         final int length = s.length;
         //first make sure that required capacity is avaible
         if(arrangeCapacity(length, false)){
-            int beforeSkip = fCurrentEntity.position;
+            int beforeSkip = fCurrentEntity.position ;
+            int afterSkip = fCurrentEntity.position + length  ;
 
             if(DEBUG_SKIP_STRING){
                 System.out.println("skipString,length = " + new String(s) + "," + length);
@@ -2209,9 +2210,8 @@
      * is being changed.
      */
     public void registerListener(XMLBufferListener listener) {
-        if (!listeners.contains(listener)) {
+        if(!listeners.contains(listener))
             listeners.add(listener);
-        }
     }
 
     /**
@@ -2219,8 +2219,9 @@
      * @param loadPos Starting position from which new data is being loaded into scanner buffer.
      */
     public void invokeListeners(int loadPos){
-        for (int i=0; i<listeners.size(); i++) {
-            listeners.get(i).refresh(loadPos);
+        for(int i=0;i<listeners.size();i++){
+            XMLBufferListener listener =(XMLBufferListener) listeners.get(i);
+            listener.refresh(loadPos);
         }
     }
 
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java
index fb12b42..7645cce 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/XMLScanner.java
@@ -3,14 +3,13 @@
  */
 
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
+ * Copyright 2005 The Apache Software Foundation.
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
@@ -21,6 +20,7 @@
 
 package com.sun.org.apache.xerces.internal.impl;
 
+
 import com.sun.org.apache.xerces.internal.util.Status;
 import com.sun.xml.internal.stream.XMLEntityStorage;
 import java.io.IOException;
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties
index 01531f7..c7a23c2 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages.properties
@@ -145,7 +145,6 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = White space is required after \"<!DOCTYPE\" in the document type declaration.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = The root element type must appear after \"<!DOCTYPE\" in the document type declaration.
         DoctypedeclUnterminated = The document type declaration for root element type \"{0}\" must end with ''>''.
-        DoctypedeclNotClosed = The document type declaration for root element type \"{0}\" must be closed with '']''.
         PEReferenceWithinMarkup = The parameter entity reference \"%{0};\" cannot occur within markup in the internal subset of the DTD.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = The markup declarations contained or pointed to by the document type declaration must be well-formed.
 # 2.10 White Space Handling
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_de.properties b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_de.properties
index 0848270..91ff0dc 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_de.properties
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_de.properties
@@ -145,7 +145,6 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = Leerstelle nach "<!DOCTYPE" in der Dokumenttypdeklaration erforderlich.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = Root-Elementtyp muss nach "<!DOCTYPE" in der Dokumenttypdeklaration enthalten sein.
         DoctypedeclUnterminated = Dokumenttypdeklaration f\u00FCr Root-Elementtyp "{0}" muss mit ">" enden.
-        DoctypedeclNotClosed = Dokumenttypdeklaration f\u00FCr Root-Elementtyp "{0}" muss mit '']'' enden.
         PEReferenceWithinMarkup = Parameterentityreferenz "%{0};" darf nicht in Markup in der internen Teilmenge der DTD vorkommen.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = Die Markup-Deklarationen, die in der Dokumenttypdeklaration enthalten sind bzw. auf die von der Dokumenttypdeklaration verwiesen wird, m\u00FCssen ordnungsgem\u00E4\u00DF formatiert sein.
 # 2.10 White Space Handling
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_es.properties b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_es.properties
index 108eeeb..9c4d5b0 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_es.properties
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_es.properties
@@ -145,7 +145,6 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = Es necesario un espacio en blanco despu\u00E9s de "<!DOCTYPE" en la declaraci\u00F3n de tipo de documento.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = El tipo de elemento ra\u00EDz debe aparecer despu\u00E9s de "<!DOCTYPE" en la declaraci\u00F3n de tipo de documento.
         DoctypedeclUnterminated = La declaraci\u00F3n de tipo de documento para el tipo de elemento ra\u00EDz "{0}" debe finalizar en ''>''.
-        DoctypedeclNotClosed = La declaraci\u00F3n de tipo de documento para el tipo de elemento ra\u00EDz "{0}" debe finalizar en '']''.
         PEReferenceWithinMarkup = La referencia de entidad del par\u00E1metro "%{0};" no puede producirse en el marcador en el subconjunto interno del DTD.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = Las declaraciones de marcador que se incluyen o a las que apunta la declaraci\u00F3n de tipo de documento deben tener el formato correcto.
 # 2.10 White Space Handling
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_fr.properties b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_fr.properties
index c9c31bb..300ff03 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_fr.properties
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_fr.properties
@@ -145,7 +145,6 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = Un espace est obligatoire apr\u00E8s "<!DOCTYPE" dans la d\u00E9claration de type de document.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = Le type d'\u00E9l\u00E9ment racine doit figurer apr\u00E8s "<!DOCTYPE" dans la d\u00E9claration de type de document.
         DoctypedeclUnterminated = La d\u00E9claration de type de document pour le type d''\u00E9l\u00E9ment racine "{0}" doit se terminer par ''>''.
-        DoctypedeclNotClosed = La d\u00E9claration de type de document pour le type d''\u00E9l\u00E9ment racine "{0}" doit se terminer par '']''.
         PEReferenceWithinMarkup = La r\u00E9f\u00E9rence d''entit\u00E9 de param\u00E8tre "%{0};" ne peut pas survenir dans le balisage du sous-ensemble interne de la DTD.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = Les d\u00E9clarations de balisage contenues dans la d\u00E9claration de type de document ou sur lesquelles pointe cette derni\u00E8re doivent avoir un format correct.
 # 2.10 White Space Handling
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_it.properties b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_it.properties
index 1cca604..fbb95d3 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_it.properties
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_it.properties
@@ -145,7 +145,6 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = \u00C8 richiesto uno spazio dopo "<!DOCTYPE" nella dichiarazione del tipo di documento.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = Il tipo di elemento radice deve comparire dopo "<!DOCTYPE" nella dichiarazione del tipo di documento.
         DoctypedeclUnterminated = La dichiarazione del tipo di documento per il tipo di elemento radice "{0}" deve terminare con ''>''.
-        DoctypedeclNotClosed = La dichiarazione del tipo di documento per il tipo di elemento radice "{0}" deve terminare con '']''.
         PEReferenceWithinMarkup = Il riferimento di entit\u00E0 di parametro "%{0};" non pu\u00F2 essere presente nel markup del set secondario interno del DTD.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = Le dichiarazioni di markup contenute o indicate dalla dichiarazione del tipo di documento devono avere un formato corretto.
 # 2.10 White Space Handling
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ja.properties b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ja.properties
index 74e0594..e656dd8 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ja.properties
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ja.properties
@@ -145,7 +145,6 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = \u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u30FB\u30BF\u30A4\u30D7\u5BA3\u8A00\u3067\u306F\u3001"<!DOCTYPE"\u306E\u5F8C\u306B\u7A7A\u767D\u304C\u5FC5\u8981\u3067\u3059\u3002
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = \u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u30FB\u30BF\u30A4\u30D7\u5BA3\u8A00\u3067\u306F\u3001"<!DOCTYPE"\u306E\u5F8C\u306B\u30EB\u30FC\u30C8\u8981\u7D20\u30BF\u30A4\u30D7\u304C\u5FC5\u8981\u3067\u3059\u3002
         DoctypedeclUnterminated = \u30EB\u30FC\u30C8\u8981\u7D20\u30BF\u30A4\u30D7"{0}"\u306E\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u30FB\u30BF\u30A4\u30D7\u5BA3\u8A00\u306F''>''\u3067\u7D42\u4E86\u3059\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002
-        DoctypedeclNotClosed = \u30EB\u30FC\u30C8\u8981\u7D20\u30BF\u30A4\u30D7"{0}"\u306E\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u30FB\u30BF\u30A4\u30D7\u5BA3\u8A00\u306F'']''\u3067\u9589\u3058\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002
         PEReferenceWithinMarkup = \u30D1\u30E9\u30E1\u30FC\u30BF\u30FB\u30A8\u30F3\u30C6\u30A3\u30C6\u30A3\u53C2\u7167"%{0};"\u306F\u3001DTD\u306E\u5185\u90E8\u30B5\u30D6\u30BB\u30C3\u30C8\u306E\u30DE\u30FC\u30AF\u30A2\u30C3\u30D7\u5185\u306B\u306F\u6307\u5B9A\u3067\u304D\u307E\u305B\u3093\u3002
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = \u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u30FB\u30BF\u30A4\u30D7\u5BA3\u8A00\u306B\u542B\u307E\u308C\u308B\u304B\u3001\u30C9\u30AD\u30E5\u30E1\u30F3\u30C8\u30FB\u30BF\u30A4\u30D7\u5BA3\u8A00\u304C\u6307\u3057\u3066\u3044\u308B\u30DE\u30FC\u30AF\u30A2\u30C3\u30D7\u5BA3\u8A00\u306F\u6574\u5F62\u5F0F\u3067\u3042\u308B\u5FC5\u8981\u304C\u3042\u308A\u307E\u3059\u3002
 # 2.10 White Space Handling
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ko.properties b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ko.properties
index e90be33..099855e 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ko.properties
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_ko.properties
@@ -145,7 +145,6 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = \uBB38\uC11C \uC720\uD615 \uC120\uC5B8\uC5D0\uC11C\uB294 "<!DOCTYPE" \uB2E4\uC74C\uC5D0 \uACF5\uBC31\uC774 \uD544\uC694\uD569\uB2C8\uB2E4.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = \uBB38\uC11C \uC720\uD615 \uC120\uC5B8\uC5D0\uC11C\uB294 "<!DOCTYPE" \uB2E4\uC74C\uC5D0 \uB8E8\uD2B8 \uC694\uC18C \uC720\uD615\uC774 \uB098\uD0C0\uB098\uC57C \uD569\uB2C8\uB2E4.
         DoctypedeclUnterminated = \uB8E8\uD2B8 \uC694\uC18C \uC720\uD615 "{0}"\uC5D0 \uB300\uD55C \uBB38\uC11C \uC720\uD615 \uC120\uC5B8\uC740 ''>''\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4.
-        DoctypedeclNotClosed = \uB8E8\uD2B8 \uC694\uC18C \uC720\uD615 "{0}"\uC5D0 \uB300\uD55C \uBB38\uC11C \uC720\uD615 \uC120\uC5B8\uC740 '']''\uB85C \uB05D\uB098\uC57C \uD569\uB2C8\uB2E4.
         PEReferenceWithinMarkup = \uB9E4\uAC1C\uBCC0\uC218 \uC5D4\uD2F0\uD2F0 \uCC38\uC870 "%{0};"\uC740 DTD\uC758 \uB0B4\uBD80 \uBD80\uBD84 \uC9D1\uD569\uC5D0 \uC788\uB294 \uB9C8\uD06C\uC5C5 \uC548\uC5D0 \uD45C\uC2DC\uB420 \uC218 \uC5C6\uC2B5\uB2C8\uB2E4.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = \uBB38\uC11C \uC720\uD615 \uC120\uC5B8\uC744 \uD3EC\uD568\uD558\uAC70\uB098 \uBB38\uC11C \uC720\uD615 \uC120\uC5B8\uC774 \uAC00\uB9AC\uD0A4\uB294 \uB9C8\uD06C\uC5C5 \uC120\uC5B8\uC740 \uC62C\uBC14\uB978 \uD615\uC2DD\uC774\uC5B4\uC57C \uD569\uB2C8\uB2E4.
 # 2.10 White Space Handling
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_pt_BR.properties b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_pt_BR.properties
index 93ae48e..1e00587 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_pt_BR.properties
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_pt_BR.properties
@@ -145,7 +145,6 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = O espa\u00E7o em branco \u00E9 necess\u00E1rio ap\u00F3s "<!DOCTYPE" na declara\u00E7\u00E3o do tipo de documento.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = O tipo de elemento-raiz deve aparecer ap\u00F3s "<!DOCTYPE" na declara\u00E7\u00E3o do tipo de documento.
         DoctypedeclUnterminated = A declara\u00E7\u00E3o do tipo de documento do tipo de elemento "{0}" deve terminar com ''>''.
-        DoctypedeclNotClosed = A declara\u00E7\u00E3o do tipo de documento do tipo de elemento "{0}" deve terminar com '']''.
         PEReferenceWithinMarkup = A refer\u00EAncia da entidade do par\u00E2metro "%{0};" n\u00E3o pode ocorrer na marca\u00E7\u00E3o no subconjunto interno do DTD.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = As declara\u00E7\u00F5es de marca\u00E7\u00E3o contidas ou apontadas pela declara\u00E7\u00E3o do tipo de documento devem estar corretas.
 # 2.10 White Space Handling
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_sv.properties b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_sv.properties
index 4f54e5f..add473e 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_sv.properties
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_sv.properties
@@ -145,7 +145,6 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = Tomt utrymme kr\u00E4vs efter "<!DOCTYPE" i dokumenttypdeklarationen.
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = Rotelementtyp m\u00E5ste anges efter "<!DOCTYPE" i dokumenttypdeklarationen.
         DoctypedeclUnterminated = Dokumenttypdeklarationen f\u00F6r rotelementtyp "{0}" m\u00E5ste avslutas med ''>''.
-        DoctypedeclNotClosed = Dokumenttypsdeklarationen f\u00F6r rotelementtypen "{0}" m\u00E5ste st\u00E4ngas med '']''.
         PEReferenceWithinMarkup = Parameterreferensen "%{0};" f\u00E5r inte f\u00F6rekomma i kodtexten i den interna delm\u00E4ngden i DTD.
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = Kodtextdeklarationerna som finns med eller pekas till fr\u00E5n dokumenttypdeklarationen m\u00E5ste vara v\u00E4lformulerade.
 # 2.10 White Space Handling
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_CN.properties b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_CN.properties
index dc2e1d0..dc6bca0 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_CN.properties
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_CN.properties
@@ -145,7 +145,6 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = \u5728\u6587\u6863\u7C7B\u578B\u58F0\u660E\u4E2D\u7684 "<!DOCTYPE" \u540E\u9762\u9700\u8981\u6709\u7A7A\u683C\u3002
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = \u5728\u6587\u6863\u7C7B\u578B\u58F0\u660E\u4E2D, \u6839\u5143\u7D20\u7C7B\u578B\u5FC5\u987B\u51FA\u73B0\u5728 "<!DOCTYPE" \u540E\u9762\u3002
         DoctypedeclUnterminated = \u6839\u5143\u7D20\u7C7B\u578B "{0}" \u7684\u6587\u6863\u7C7B\u578B\u58F0\u660E\u5FC5\u987B\u4EE5 ''>'' \u7ED3\u5C3E\u3002
-        DoctypedeclNotClosed = \u6839\u5143\u7D20\u7C7B\u578B "{0}" \u7684\u6587\u6863\u7C7B\u578B\u58F0\u660E\u5FC5\u987B\u4EE5 '']'' \u7ED3\u5C3E\u3002
         PEReferenceWithinMarkup = \u53C2\u6570\u5B9E\u4F53\u5F15\u7528 "%{0};" \u4E0D\u80FD\u51FA\u73B0\u5728 DTD \u7684\u5185\u90E8\u5B50\u96C6\u4E2D\u7684\u6807\u8BB0\u5185\u3002
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = \u6587\u6863\u7C7B\u578B\u58F0\u660E\u5305\u542B\u6216\u6307\u5411\u7684\u6807\u8BB0\u58F0\u660E\u5FC5\u987B\u683C\u5F0F\u6B63\u786E\u3002
 # 2.10 White Space Handling
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_TW.properties b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_TW.properties
index 80e01f2..9d22569 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_TW.properties
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/impl/msg/XMLMessages_zh_TW.properties
@@ -145,7 +145,6 @@
         MSG_SPACE_REQUIRED_BEFORE_ROOT_ELEMENT_TYPE_IN_DOCTYPEDECL = \u5728\u6587\u4EF6\u985E\u578B\u5BA3\u544A\u4E2D "<!DOCTYPE" \u4E4B\u5F8C\u9700\u8981\u7A7A\u683C\u3002
         MSG_ROOT_ELEMENT_TYPE_REQUIRED = \u5728\u6587\u4EF6\u985E\u578B\u5BA3\u544A\u4E2D\uFF0C\u6839\u5143\u7D20\u985E\u578B\u5FC5\u9808\u51FA\u73FE\u5728 "<!DOCTYPE" \u4E4B\u5F8C\u3002
         DoctypedeclUnterminated = \u6839\u5143\u7D20\u985E\u578B "{0}" \u7684\u6587\u4EF6\u985E\u578B\u5BA3\u544A\u7D50\u5C3E\u5FC5\u9808\u70BA ''>''\u3002
-        DoctypedeclNotClosed = \u6839\u5143\u7D20\u985E\u578B "{0}" \u7684\u6587\u4EF6\u985E\u578B\u5BA3\u544A\u7D50\u5C3E\u5FC5\u9808\u70BA '']''\u3002
         PEReferenceWithinMarkup = DTD \u5167\u90E8\u5B57\u96C6\u7684\u6A19\u8A18\u5167\u4E0D\u80FD\u51FA\u73FE\u53C3\u6578\u5BE6\u9AD4\u53C3\u7167 "%{0};"\u3002
         MSG_MARKUP_NOT_RECOGNIZED_IN_DTD = \u6587\u4EF6\u985E\u578B\u5BA3\u544A\u5305\u542B\u6216\u6307\u5411\u7684\u6A19\u8A18\u5BA3\u544A\u5FC5\u9808\u683C\u5F0F\u6B63\u78BA\u3002
 # 2.10 White Space Handling
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java
index 84543ec..dac7fbf 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/jaxp/datatype/XMLGregorianCalendarImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2006, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -2671,9 +2671,6 @@
             customTimezoneId.append(sign);
             customTimezoneId.append(hour);
             if (minutes != 0) {
-                if (minutes < 10) {
-                    customTimezoneId.append('0');
-                }
                 customTimezoneId.append(minutes);
             }
             result = TimeZone.getTimeZone(customTimezoneId.toString());
diff --git a/jaxp/src/com/sun/org/apache/xerces/internal/util/HTTPInputSource.java b/jaxp/src/com/sun/org/apache/xerces/internal/util/HTTPInputSource.java
index c9bbed9..bdd0750 100644
--- a/jaxp/src/com/sun/org/apache/xerces/internal/util/HTTPInputSource.java
+++ b/jaxp/src/com/sun/org/apache/xerces/internal/util/HTTPInputSource.java
@@ -1,16 +1,15 @@
 /*
- * Copyright (c) 2007, 2016, Oracle and/or its affiliates. All rights reserved.
+ * reserved comment block
+ * DO NOT REMOVE OR ALTER!
  */
-
 /*
- * Licensed to the Apache Software Foundation (ASF) under one or more
- * contributor license agreements.  See the NOTICE file distributed with
- * this work for additional information regarding copyright ownership.
- * The ASF licenses this file to You under the Apache License, Version 2.0
- * (the "License"); you may not use this file except in compliance with
- * the License.  You may obtain a copy of the License at
+ * Copyright 2004,2005 The Apache Software Foundation.
  *
- *     http://www.apache.org/licenses/LICENSE-2.0
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
  *
  * Unless required by applicable law or agreed to in writing, software
  * distributed under the License is distributed on an "AS IS" BASIS,
@@ -18,17 +17,18 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-
 package com.sun.org.apache.xerces.internal.util;
 
-import com.sun.org.apache.xerces.internal.xni.XMLResourceIdentifier;
-import com.sun.org.apache.xerces.internal.xni.parser.XMLInputSource;
 import java.io.InputStream;
 import java.io.Reader;
+
 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;
 
+import com.sun.org.apache.xerces.internal.xni.XMLResourceIdentifier;
+import com.sun.org.apache.xerces.internal.xni.parser.XMLInputSource;
+
 /**
  * This class represents an input source for an XML resource
  * retrievable over HTTP. In addition to the properties
diff --git a/jaxp/src/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java b/jaxp/src/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java
index 8f14d74..d17cf33 100644
--- a/jaxp/src/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java
+++ b/jaxp/src/com/sun/org/apache/xml/internal/serialize/DOMSerializerImpl.java
@@ -33,7 +33,6 @@
 import java.util.StringTokenizer;
 import java.util.Vector;
 
-import com.sun.org.apache.xerces.internal.dom.AbortException;
 import com.sun.org.apache.xerces.internal.dom.CoreDocumentImpl;
 import com.sun.org.apache.xerces.internal.dom.DOMErrorImpl;
 import com.sun.org.apache.xerces.internal.dom.DOMLocatorImpl;
@@ -118,6 +117,7 @@
     private DOMErrorHandler fErrorHandler = null;
     private final DOMErrorImpl fError = new DOMErrorImpl();
     private final DOMLocatorImpl fLocator = new DOMLocatorImpl();
+    private static final RuntimeException abort = new RuntimeException();
 
     /**
      * Constructs a new LSSerializer.
@@ -539,9 +539,11 @@
         } catch (LSException lse) {
             // Rethrow LSException.
             throw lse;
-        } catch (AbortException e) {
-            return null;
         } catch (RuntimeException e) {
+            if (e == DOMNormalizer.abort){
+                // stopped at user request
+                return null;
+            }
             throw (LSException) new LSException(LSException.SERIALIZE_ERR, e.toString()).initCause(e);
         } catch (IOException ioe) {
             // REVISIT: A generic IOException doesn't provide enough information
@@ -834,9 +836,11 @@
         } catch (LSException lse) {
             // Rethrow LSException.
             throw lse;
-        } catch (AbortException e) {
-            return false;
         } catch (RuntimeException e) {
+            if (e == DOMNormalizer.abort){
+                // stopped at user request
+                return false;
+            }
             throw (LSException) DOMUtil.createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
         } catch (Exception e) {
             if (ser.fDOMErrorHandler != null) {
@@ -988,9 +992,11 @@
         } catch (LSException lse) {
             // Rethrow LSException.
             throw lse;
-        } catch (AbortException e) {
-            return false;
         } catch (RuntimeException e) {
+            if (e == DOMNormalizer.abort){
+                // stopped at user request
+                return false;
+            }
             throw (LSException) DOMUtil.createLSException(LSException.SERIALIZE_ERR, e).fillInStackTrace();
         } catch (Exception e) {
             if (ser.fDOMErrorHandler != null) {
diff --git a/jaxws/ASSEMBLY_EXCEPTION b/jaxws/ASSEMBLY_EXCEPTION
index 065b8d9..8b7ac1d 100644
--- a/jaxws/ASSEMBLY_EXCEPTION
+++ b/jaxws/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
-openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
-General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Sun at openjdk.java.net and
+openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
+GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Oracle gives you permission to link this
-    OpenJDK Code with certain code licensed by Oracle as indicated at
+    As a special exception, Sun gives you permission to link this
+    OpenJDK Code with certain code licensed by Sun as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Oracle.
+    governed by the licenses under which they were offered by Sun.
 
-As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
-to build an executable that includes those portions of necessary code that
-Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
-with the Classpath exception).  If you modify or add to the OpenJDK code,
-that new GPL2 code may still be combined with Designated Exception Modules
-if the new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
+build an executable that includes those portions of necessary code that Sun
+could not provide under GPL2 (or that Sun has provided under GPL2 with the
+Classpath exception).  If you modify or add to the OpenJDK code, that new
+GPL2 code may still be combined with Designated Exception Modules if the
+new code is made subject to this exception by its copyright holder.
diff --git a/jaxws/LICENSE b/jaxws/LICENSE
index 8b400c7..b40a0f4 100644
--- a/jaxws/LICENSE
+++ b/jaxws/LICENSE
@@ -3,7 +3,7 @@
 Version 2, June 1991
 
 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Everyone is permitted to copy and distribute verbatim copies of this license
 document, but changing it is not allowed.
@@ -287,8 +287,8 @@
     more details.
 
     You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+    with this program; if not, write to the Free Software Foundation, Inc., 59
+    Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Also add information on how to contact you by electronic and paper mail.
 
diff --git a/jdk/ASSEMBLY_EXCEPTION b/jdk/ASSEMBLY_EXCEPTION
index 065b8d9..8b7ac1d 100644
--- a/jdk/ASSEMBLY_EXCEPTION
+++ b/jdk/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
-openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
-General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Sun at openjdk.java.net and
+openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
+GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Oracle gives you permission to link this
-    OpenJDK Code with certain code licensed by Oracle as indicated at
+    As a special exception, Sun gives you permission to link this
+    OpenJDK Code with certain code licensed by Sun as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Oracle.
+    governed by the licenses under which they were offered by Sun.
 
-As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
-to build an executable that includes those portions of necessary code that
-Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
-with the Classpath exception).  If you modify or add to the OpenJDK code,
-that new GPL2 code may still be combined with Designated Exception Modules
-if the new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
+build an executable that includes those portions of necessary code that Sun
+could not provide under GPL2 (or that Sun has provided under GPL2 with the
+Classpath exception).  If you modify or add to the OpenJDK code, that new
+GPL2 code may still be combined with Designated Exception Modules if the
+new code is made subject to this exception by its copyright holder.
diff --git a/jdk/LICENSE b/jdk/LICENSE
index 8b400c7..b40a0f4 100644
--- a/jdk/LICENSE
+++ b/jdk/LICENSE
@@ -3,7 +3,7 @@
 Version 2, June 1991
 
 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Everyone is permitted to copy and distribute verbatim copies of this license
 document, but changing it is not allowed.
@@ -287,8 +287,8 @@
     more details.
 
     You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+    with this program; if not, write to the Free Software Foundation, Inc., 59
+    Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Also add information on how to contact you by electronic and paper mail.
 
diff --git a/jdk/make/CopyFiles.gmk b/jdk/make/CopyFiles.gmk
index bc070f0..9c7e7bc 100644
--- a/jdk/make/CopyFiles.gmk
+++ b/jdk/make/CopyFiles.gmk
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 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
@@ -357,21 +357,18 @@
 RESTRICTED_PKGS_SRC := $(JDK_TOPDIR)/src/closed/share/lib/security/restricted.pkgs
 RESTRICTED_PKGS := $(shell $(CAT) $(RESTRICTED_PKGS_SRC) | $(TR) "\n" " ")
 
-endif
-
 $(PROPS_DST): $(PROPS_SRC)
 	$(MKDIR) -p $(@D)
-        ifndef OPENJDK
-	  $(TOOL_ADDTORESTRICTEDPKGS) $^ $@.tmp $(RESTRICTED_PKGS)
-        else
-	  $(CP) $^ $@.tmp
-        endif
-        ifeq ($(UNLIMITED_CRYPTO), true)
-	  $(TOOL_CRYPTOLEVEL) $@.tmp $@.tmp2 unlimited
-	  $(MV) $@.tmp2 $@.tmp
-        endif
+	$(TOOL_ADDTORESTRICTEDPKGS) $^ $@.tmp $(RESTRICTED_PKGS)
 	$(MV) $@.tmp $@
 
+else
+
+$(PROPS_DST): $(PROPS_SRC)
+	$(call install-file)
+
+endif
+
 COPY_FILES += $(PROPS_DST)
 
 ##########################################################################################
diff --git a/jdk/make/CreateSecurityJars.gmk b/jdk/make/CreateSecurityJars.gmk
index da9cc20..d5b3b8e 100644
--- a/jdk/make/CreateSecurityJars.gmk
+++ b/jdk/make/CreateSecurityJars.gmk
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
 # DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 #
 # This code is free software; you can redistribute it and/or modify it
@@ -178,10 +178,7 @@
 
 ##########################################################################################
 
-US_EXPORT_POLICY_JAR_UNLIMITED_DST := \
-    $(JDK_OUTPUTDIR)/lib/security/policy/unlimited/US_export_policy.jar
-US_EXPORT_POLICY_JAR_LIMITED_DST := \
-    $(JDK_OUTPUTDIR)/lib/security/policy/limited/US_export_policy.jar
+US_EXPORT_POLICY_JAR_DST := $(JDK_OUTPUTDIR)/lib/security/US_export_policy.jar
 
 ifneq ($(BUILD_CRYPTO), no)
 
@@ -223,29 +220,27 @@
 endif
 
 ifndef OPENJDK
-  $(US_EXPORT_POLICY_JAR_UNLIMITED_DST): \
-    $(JDK_TOPDIR)/make/closed/tools/crypto/jce/unlimited/US_export_policy.jar
-	$(ECHO) $(LOG_INFO) Copying prebuilt $(@F)
-	$(install-file)
-  $(US_EXPORT_POLICY_JAR_LIMITED_DST): \
-    $(JDK_TOPDIR)/make/closed/tools/crypto/jce/limited/US_export_policy.jar
+  ifeq ($(UNLIMITED_CRYPTO), true)
+    $(error No prebuilt unlimited crypto jars available)
+  endif
+  $(US_EXPORT_POLICY_JAR_DST): $(JDK_TOPDIR)/make/closed/tools/crypto/jce/US_export_policy.jar
 	$(ECHO) $(LOG_INFO) Copying prebuilt $(@F)
 	$(install-file)
 else
-  $(US_EXPORT_POLICY_JAR_UNLIMITED_DST): $(US_EXPORT_POLICY_JAR_UNLIMITED_UNSIGNED)
+  ifeq ($(UNLIMITED_CRYPTO), true)
+    $(US_EXPORT_POLICY_JAR_DST): $(US_EXPORT_POLICY_JAR_UNLIMITED_UNSIGNED)
 	$(install-file)
-  $(US_EXPORT_POLICY_JAR_LIMITED_DST): $(US_EXPORT_POLICY_JAR_LIMITED_UNSIGNED)
+  else
+    $(US_EXPORT_POLICY_JAR_DST): $(US_EXPORT_POLICY_JAR_LIMITED_UNSIGNED)
 	$(install-file)
   endif
+endif
 
-TARGETS += $(US_EXPORT_POLICY_JAR_UNLIMITED_DST) $(US_EXPORT_POLICY_JAR_LIMITED_DST)
+TARGETS += $(US_EXPORT_POLICY_JAR_DST)
 
 ##########################################################################################
 
-LOCAL_POLICY_JAR_LIMITED_DST := \
-    $(JDK_OUTPUTDIR)/lib/security/policy/limited/local_policy.jar
-LOCAL_POLICY_JAR_UNLIMITED_DST := \
-    $(JDK_OUTPUTDIR)/lib/security/policy/unlimited/local_policy.jar
+LOCAL_POLICY_JAR_DST := $(JDK_OUTPUTDIR)/lib/security/local_policy.jar
 
 ifneq ($(BUILD_CRYPTO), no)
 
@@ -298,20 +293,20 @@
 endif
 
 ifndef OPENJDK
-  $(LOCAL_POLICY_JAR_UNLIMITED_DST): $(JDK_TOPDIR)/make/closed/tools/crypto/jce/unlimited/local_policy.jar
-	$(ECHO) $(LOG_INFO) Copying prebuilt $(@F)
-	$(install-file)
-  $(LOCAL_POLICY_JAR_LIMITED_DST): $(JDK_TOPDIR)/make/closed/tools/crypto/jce/limited/local_policy.jar
+  $(LOCAL_POLICY_JAR_DST): $(JDK_TOPDIR)/make/closed/tools/crypto/jce/local_policy.jar
 	$(ECHO) $(LOG_INFO) Copying prebuilt $(@F)
 	$(install-file)
 else
-  $(LOCAL_POLICY_JAR_UNLIMITED_DST): $(LOCAL_POLICY_JAR_UNLIMITED_UNSIGNED)
+  ifeq ($(UNLIMITED_CRYPTO), true)
+    $(LOCAL_POLICY_JAR_DST): $(LOCAL_POLICY_JAR_UNLIMITED_UNSIGNED)
 	$(install-file)
-  $(LOCAL_POLICY_JAR_LIMITED_DST): $(LOCAL_POLICY_JAR_LIMITED_UNSIGNED)
+  else
+    $(LOCAL_POLICY_JAR_DST): $(LOCAL_POLICY_JAR_LIMITED_UNSIGNED)
 	$(install-file)
   endif
+endif
 
-TARGETS += $(LOCAL_POLICY_JAR_UNLIMITED_DST) $(LOCAL_POLICY_JAR_LIMITED_DST)
+TARGETS += $(LOCAL_POLICY_JAR_DST)
 
 ##########################################################################################
 
diff --git a/jdk/make/Tools.gmk b/jdk/make/Tools.gmk
index afb9f86..b45d5dc 100644
--- a/jdk/make/Tools.gmk
+++ b/jdk/make/Tools.gmk
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2011, 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
@@ -132,10 +132,7 @@
     build.tools.deps.CheckDeps
 
 TOOL_ADDTORESTRICTEDPKGS=$(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
-    build.tools.customizesecurityfile.AddToRestrictedPkgs
-
-TOOL_CRYPTOLEVEL=$(JAVA_SMALL) -cp $(JDK_OUTPUTDIR)/btclasses \
-    build.tools.customizesecurityfile.CryptoLevel
+    build.tools.addtorestrictedpkgs.AddToRestrictedPkgs
 
 ##########################################################################################
 
diff --git a/jdk/make/data/tzdata/VERSION b/jdk/make/data/tzdata/VERSION
index f587cb7..6bf3661 100644
--- a/jdk/make/data/tzdata/VERSION
+++ b/jdk/make/data/tzdata/VERSION
@@ -21,4 +21,4 @@
 # or visit www.oracle.com if you need additional information or have any
 # questions.
 #
-tzdata2016g
+tzdata2016f
diff --git a/jdk/make/data/tzdata/africa b/jdk/make/data/tzdata/africa
index cbde238..b523dc3 100644
--- a/jdk/make/data/tzdata/africa
+++ b/jdk/make/data/tzdata/africa
@@ -487,7 +487,7 @@
 # http://www.libyaherald.com/2013/10/24/correction-no-time-change-tomorrow/
 #
 # From Paul Eggert (2013-10-25):
-# For now, assume they're reverting to the pre-2012 rules of permanent UT +02.
+# For now, assume they're reverting to the pre-2012 rules of permanent UTC+2.
 
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Libya	1951	only	-	Oct	14	2:00	1:00	S
diff --git a/jdk/make/data/tzdata/antarctica b/jdk/make/data/tzdata/antarctica
index f96947a..e12c764 100644
--- a/jdk/make/data/tzdata/antarctica
+++ b/jdk/make/data/tzdata/antarctica
@@ -33,7 +33,9 @@
 # http://www.spri.cam.ac.uk/bob/periant.htm
 # for information.
 # Unless otherwise specified, we have no time zone information.
-
+#
+# Except for the French entries,
+# I made up all time zone abbreviations mentioned here; corrections welcome!
 # FORMAT is '-00' and GMTOFF is 0 for locations while uninhabited.
 
 # Argentina - year-round bases
@@ -50,7 +52,7 @@
 #	previously sealers and scientific personnel wintered
 #	Margaret Turner reports
 #	http://web.archive.org/web/20021204222245/http://www.dstc.qut.edu.au/DST/marg/daylight.html
-#	(1999-09-30) that they're UT +05, with no DST;
+#	(1999-09-30) that they're UTC+5, with no DST;
 #	presumably this is when they have visitors.
 #
 # year-round bases
@@ -89,22 +91,23 @@
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Antarctica/Casey	0	-	-00	1969
-			8:00	-	+08	2009 Oct 18  2:00
-			11:00	-	+11	2010 Mar  5  2:00
-			8:00	-	+08	2011 Oct 28  2:00
-			11:00	-	+11	2012 Feb 21 17:00u
-			8:00	-	+08
+			8:00	-	AWST	2009 Oct 18  2:00
+						# Australian Western Std Time
+			11:00	-	CAST	2010 Mar  5  2:00  # Casey Time
+			8:00	-	AWST	2011 Oct 28  2:00
+			11:00	-	CAST	2012 Feb 21 17:00u
+			8:00	-	AWST
 Zone Antarctica/Davis	0	-	-00	1957 Jan 13
-			7:00	-	+07	1964 Nov
+			7:00	-	DAVT	1964 Nov    # Davis Time
 			0	-	-00	1969 Feb
-			7:00	-	+07	2009 Oct 18  2:00
-			5:00	-	+05	2010 Mar 10 20:00u
-			7:00	-	+07	2011 Oct 28  2:00
-			5:00	-	+05	2012 Feb 21 20:00u
-			7:00	-	+07
+			7:00	-	DAVT	2009 Oct 18  2:00
+			5:00	-	DAVT	2010 Mar 10 20:00u
+			7:00	-	DAVT	2011 Oct 28  2:00
+			5:00	-	DAVT	2012 Feb 21 20:00u
+			7:00	-	DAVT
 Zone Antarctica/Mawson	0	-	-00	1954 Feb 13
-			6:00	-	+06	2009 Oct 18  2:00
-			5:00	-	+05
+			6:00	-	MAWT	2009 Oct 18  2:00 # Mawson Time
+			5:00	-	MAWT
 # References:
 # Casey Weather (1998-02-26)
 # http://www.antdiv.gov.au/aad/exop/sfo/casey/casey_aws.html
@@ -158,7 +161,7 @@
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Indian/Kerguelen	0	-	-00	1950 # Port-aux-Français
-			5:00	-	+05
+			5:00	-	TFT	# ISO code TF Time
 #
 # year-round base in the main continent
 # Dumont d'Urville, Île des Pétrels, -6640+14001, since 1956-11
@@ -169,9 +172,9 @@
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Antarctica/DumontDUrville 0 -	-00	1947
-			10:00	-	+10	1952 Jan 14
+			10:00	-	PMT	1952 Jan 14 # Port-Martin Time
 			0	-	-00	1956 Nov
-			10:00	-	+10
+			10:00	-	DDUT	# Dumont-d'Urville Time
 
 # France & Italy - year-round base
 # Concordia, -750600+1232000, since 2005
@@ -197,7 +200,7 @@
 # station of Japan, it's appropriate for the principal location.
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Antarctica/Syowa	0	-	-00	1957 Jan 29
-			3:00	-	+03
+			3:00	-	SYOT	# Syowa Time
 # See:
 # NIPR Antarctic Research Activities (1999-08-17)
 # http://www.nipr.ac.jp/english/ara01.html
@@ -234,17 +237,17 @@
 # correct, but they should be quite close to the actual dates.
 #
 # From Paul Eggert (2014-03-21):
-# The CET-switching Troll rules require zic from tz 2014b or later, so as
+# The CET-switching Troll rules require zic from tzcode 2014b or later, so as
 # suggested by Bengt-Inge Larsson comment them out for now, and approximate
 # with only UTC and CEST.  Uncomment them when 2014b is more prevalent.
 #
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
-#Rule	Troll	2005	max	-	Mar	 1	1:00u	1:00	+01
-Rule	Troll	2005	max	-	Mar	lastSun	1:00u	2:00	+02
-#Rule	Troll	2005	max	-	Oct	lastSun	1:00u	1:00	+01
-#Rule	Troll	2004	max	-	Nov	 7	1:00u	0:00	+00
+#Rule	Troll	2005	max	-	Mar	 1	1:00u	1:00	CET
+Rule	Troll	2005	max	-	Mar	lastSun	1:00u	2:00	CEST
+#Rule	Troll	2005	max	-	Oct	lastSun	1:00u	1:00	CET
+#Rule	Troll	2004	max	-	Nov	 7	1:00u	0:00	UTC
 # Remove the following line when uncommenting the above '#Rule' lines.
-Rule	Troll	2004	max	-	Oct	lastSun	1:00u	0:00	+00
+Rule	Troll	2004	max	-	Oct	lastSun	1:00u	0:00	UTC
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Antarctica/Troll	0	-	-00	2005 Feb 12
 			0:00	Troll	%s
@@ -285,10 +288,10 @@
 # changes during the year and does not necessarily correspond to mean
 # solar noon.  So the Vostok time might have been whatever the clocks
 # happened to be during their visit.  So we still don't really know what time
-# it is at Vostok.  But we'll guess +06.
+# it is at Vostok.  But we'll guess UTC+6.
 #
 Zone Antarctica/Vostok	0	-	-00	1957 Dec 16
-			6:00	-	+06
+			6:00	-	VOST	# Vostok time
 
 # S Africa - year-round bases
 # Marion Island, -4653+03752
@@ -321,7 +324,7 @@
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Antarctica/Rothera	0	-	-00	1976 Dec  1
-			-3:00	-	-03
+			-3:00	-	ROTT	# Rothera time
 
 # Uruguay - year round base
 # Artigas, King George Island, -621104-0585107
diff --git a/jdk/make/data/tzdata/asia b/jdk/make/data/tzdata/asia
index 65e5f94..35ac37c 100644
--- a/jdk/make/data/tzdata/asia
+++ b/jdk/make/data/tzdata/asia
@@ -139,11 +139,13 @@
 # http://www.worldtimezone.com/dst_news/dst_news_armenia03.html
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Yerevan	2:58:00 -	LMT	1924 May  2
-			3:00	-	+03	1957 Mar
-			4:00 RussiaAsia +04/+05	1991 Mar 31  2:00s
-			3:00 RussiaAsia	+03/+04	1995 Sep 24  2:00s
-			4:00	-	+04	1997
-			4:00 RussiaAsia	+04/+05
+			3:00	-	YERT	1957 Mar    # Yerevan Time
+			4:00 RussiaAsia YER%sT	1991 Mar 31  2:00s
+			3:00	1:00	YERST	1991 Sep 23 # independence
+			3:00 RussiaAsia	AM%sT	1995 Sep 24  2:00s
+			4:00	-	AMT	1997
+			4:00 RussiaAsia	AM%sT	2012 Feb  9
+			4:00	-	AMT
 
 # Azerbaijan
 
@@ -164,12 +166,13 @@
 Rule	Azer	1997	2015	-	Oct	lastSun	 5:00	0	-
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Baku	3:19:24 -	LMT	1924 May  2
-			3:00	-	+03	1957 Mar
-			4:00 RussiaAsia +04/+05	1991 Mar 31  2:00s
-			3:00 RussiaAsia	+03/+04	1992 Sep lastSun  2:00s
-			4:00	-	+04	1996
-			4:00	EUAsia	+04/+05	1997
-			4:00	Azer	+04/+05
+			3:00	-	BAKT	1957 Mar    # Baku Time
+			4:00 RussiaAsia BAK%sT	1991 Mar 31  2:00s
+			3:00	1:00	BAKST	1991 Aug 30 # independence
+			3:00 RussiaAsia	AZ%sT	1992 Sep lastSun  2:00s
+			4:00	-	AZT	1996     # Azerbaijan Time
+			4:00	EUAsia	AZ%sT	1997
+			4:00	Azer	AZ%sT
 
 # Bahrain
 # See Asia/Qatar.
@@ -288,7 +291,7 @@
 # Milne says 6:24:40 was the meridian of the time ball observatory at Rangoon.
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
-Zone	Asia/Yangon	6:24:40 -	LMT	1880        # or Rangoon
+Zone	Asia/Rangoon	6:24:40 -	LMT	1880        # or Yangon
 			6:24:40	-	RMT	1920        # Rangoon Mean Time?
 			6:30	-	BURT	1942 May    # Burma Time
 			9:00	-	JST	1945 May  3
@@ -403,7 +406,7 @@
 # Lewiston (ME) Daily Sun (1939-05-29), p 17, said "Even the time is
 # different - the occupied districts going by Tokyo time, an hour
 # ahead of that prevailing in the rest of Shanghai."  Guess that the
-# Xujiahui Observatory was under French control and stuck with UT +08.
+# Xujiahui Observatory was under French control and stuck with UT+8.
 #
 # In earlier versions of this file, China had many separate Zone entries, but
 # this was based on what were apparently incorrect data in Shanks & Pottenger.
@@ -412,26 +415,26 @@
 # Proposed in 1918 and theoretically in effect until 1949 (although in practice
 # mainly observed in coastal areas), the five zones were:
 #
-# Changbai Time ("Long-white Time", Long-white = Heilongjiang area) UT +08:30
+# Changbai Time ("Long-white Time", Long-white = Heilongjiang area) UT+8.5
 # Asia/Harbin (currently a link to Asia/Shanghai)
 # Heilongjiang (except Mohe county), Jilin
 #
-# Zhongyuan Time ("Central plain Time") UT +08
+# Zhongyuan Time ("Central plain Time") UT+8
 # Asia/Shanghai
 # most of China
 # This currently represents most other zones as well,
 # as apparently these regions have been the same since 1970.
 # Milne gives 8:05:43.2 for Xujiahui Observatory time; round to nearest.
-# Guo says Shanghai switched to UT +08 "from the end of the 19th century".
+# Guo says Shanghai switched to UT+8 "from the end of the 19th century".
 #
-# Long-shu Time (probably due to Long and Shu being two names of the area) UT +07
+# Long-shu Time (probably due to Long and Shu being two names of that area) UT+7
 # Asia/Chongqing (currently a link to Asia/Shanghai)
 # Guangxi, Guizhou, Hainan, Ningxia, Sichuan, Shaanxi, and Yunnan;
 # most of Gansu; west Inner Mongolia; west Qinghai; and the Guangdong
 # counties Deqing, Enping, Kaiping, Luoding, Taishan, Xinxing,
 # Yangchun, Yangjiang, Yu'nan, and Yunfu.
 #
-# Xin-zang Time ("Xinjiang-Tibet Time") UT +06
+# Xin-zang Time ("Xinjiang-Tibet Time") UT+6
 # Asia/Urumqi
 # This currently represents Kunlun Time as well,
 # as apparently the two regions have been the same since 1970.
@@ -444,7 +447,7 @@
 # Shihezi, Changji, Yanqi, Heshuo, Tuokexun, Tulufan, Shanshan, Hami,
 # Fukang, Kuitun, Kumukuli, Miquan, Qitai, and Turfan.
 #
-# Kunlun Time UT +05:30
+# Kunlun Time UT+5.5
 # Asia/Kashgar (currently a link to Asia/Urumqi)
 # West Tibet, including Pulan, Aheqi, Shufu, Shule;
 # West Xinjiang, including Aksu, Atushi, Yining, Hetian, Cele, Luopu, Nileke,
@@ -460,7 +463,7 @@
 #
 # On the other hand, ethnic Uyghurs, who make up about half the
 # population of Xinjiang, typically use "Xinjiang time" which is two
-# hours behind Beijing time, or UT +06. The government of the Xinjiang
+# hours behind Beijing time, or UTC +0600. The government of the Xinjiang
 # Uyghur Autonomous Region, (XAUR, or just Xinjiang for short) as well as
 # local governments such as the Ürümqi city government use both times in
 # publications, referring to what is popularly called Xinjiang time as
@@ -516,8 +519,8 @@
 # having the same time as Beijing.
 
 # From Paul Eggert (2014-06-30):
-# In the early days of the PRC, Tibet was given its own time zone (UT +06)
-# but this was withdrawn in 1959 and never reinstated; see Tubten Khétsun,
+# In the early days of the PRC, Tibet was given its own time zone (UT+6) but
+# this was withdrawn in 1959 and never reinstated; see Tubten Khétsun,
 # Memories of life in Lhasa under Chinese Rule, Columbia U Press, ISBN
 # 978-0231142861 (2008), translator's introduction by Matthew Akester, p x.
 # As this is before our 1970 cutoff, Tibet doesn't need a separate zone.
@@ -531,12 +534,12 @@
 # Republics, the Soviet Union, the Kuomintang, and the People's Republic of
 # China, and tracking down all these organizations' timekeeping rules would be
 # quite a trick.  Approximate this lost history by a transition from LMT to
-# UT +06 at the start of 1928, the year of accession of the warlord Jin Shuren,
+# XJT at the start of 1928, the year of accession of the warlord Jin Shuren,
 # which happens to be the date given by Shanks & Pottenger (no doubt as a
-# guess) as the transition from LMT.  Ignore the usage of +08 before
-# 1986-02-01 under the theory that the transition date to +08 is unknown and
+# guess) as the transition from LMT.  Ignore the usage of UT+8 before
+# 1986-02-01 under the theory that the transition date to UT+8 is unknown and
 # that the sort of users who prefer Asia/Urumqi now typically ignored the
-# +08 mandate back then.
+# UT+8 mandate back then.
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 # Beijing time, used throughout China; represented by Shanghai.
@@ -741,7 +744,7 @@
 # be found from historical government announcement database.
 
 # From Paul Eggert (2014-07-03):
-# As per Yu-Cheng Chuang, say that Taiwan was at UT +09 from 1937-10-01
+# As per Yu-Cheng Chuang, say that Taiwan was at UT+9 from 1937-10-01
 # until 1945-09-21 at 01:00, overriding Shanks & Pottenger.
 # Likewise, use Yu-Cheng Chuang's data for DST in Taiwan.
 
@@ -855,15 +858,16 @@
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Tbilisi	2:59:11 -	LMT	1880
 			2:59:11	-	TBMT	1924 May  2 # Tbilisi Mean Time
-			3:00	-	+03	1957 Mar
-			4:00 RussiaAsia +04/+05	1991 Mar 31  2:00s
-			3:00 RussiaAsia +03/+04	1992
-			3:00 E-EurAsia	+03/+04	1994 Sep lastSun
-			4:00 E-EurAsia	+04/+05	1996 Oct lastSun
-			4:00	1:00	+05	1997 Mar lastSun
-			4:00 E-EurAsia	+04/+05	2004 Jun 27
-			3:00 RussiaAsia	+03/+04	2005 Mar lastSun  2:00
-			4:00	-	+04
+			3:00	-	TBIT	1957 Mar    # Tbilisi Time
+			4:00 RussiaAsia TBI%sT	1991 Mar 31  2:00s
+			3:00	1:00	TBIST	1991 Apr  9 # independence
+			3:00 RussiaAsia GE%sT	1992        # Georgia Time
+			3:00 E-EurAsia	GE%sT	1994 Sep lastSun
+			4:00 E-EurAsia	GE%sT	1996 Oct lastSun
+			4:00	1:00	GEST	1997 Mar lastSun
+			4:00 E-EurAsia	GE%sT	2004 Jun 27
+			3:00 RussiaAsia	GE%sT	2005 Mar lastSun  2:00
+			4:00	-	GET
 
 # East Timor
 
@@ -940,7 +944,7 @@
 # These would be the earliest possible times for a change.
 # Régimes horaires pour le monde entier, by Henri Le Corre, (Éditions
 # Traditionnelles, 1987, Paris) says that Java and Madura switched
-# from UT +09 to +07:30 on 1945-09-23, and gives 1944-09-01 for Jayapura
+# from JST to UTC+07:30 on 1945-09-23, and gives 1944-09-01 for Jayapura
 # (Hollandia).  For now, assume all Indonesian locations other than Jayapura
 # switched on 1945-09-23.
 #
@@ -951,11 +955,11 @@
 # summary published by the Time and Frequency Laboratory of the
 # Research Center for Calibration, Instrumentation and Metrology,
 # Indonesia, <http://time.kim.lipi.go.id/time-eng.php> (2006-09-29).
-# The time zone abbreviations and UT offsets are:
+# The abbreviations are:
 #
-# WIB  - +07 - Waktu Indonesia Barat (Indonesia western time)
-# WITA - +08 - Waktu Indonesia Tengah (Indonesia central time)
-# WIT  - +09 - Waktu Indonesia Timur (Indonesia eastern time)
+# WIB  - UTC+7 - Waktu Indonesia Barat (Indonesia western time)
+# WITA - UTC+8 - Waktu Indonesia Tengah (Indonesia central time)
+# WIT  - UTC+9 - Waktu Indonesia Timur (Indonesia eastern time)
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 # Java, Sumatra
@@ -1844,11 +1848,11 @@
 Rule	Kyrgyz	1997	2004	-	Oct	lastSun	2:30	0	-
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Bishkek	4:58:24 -	LMT	1924 May  2
-			5:00	-	+05	1930 Jun 21
-			6:00 RussiaAsia +06/+07	1991 Mar 31  2:00s
-			5:00 RussiaAsia	+05/+06	1991 Aug 31  2:00
-			5:00	Kyrgyz	+05/+06	2005 Aug 12
-			6:00	-	+06
+			5:00	-	FRUT	1930 Jun 21 # Frunze Time
+			6:00 RussiaAsia FRU%sT	1991 Mar 31  2:00s
+			5:00	1:00	FRUST	1991 Aug 31  2:00 # independence
+			5:00	Kyrgyz	KG%sT	2005 Aug 12 # Kyrgyzstan Time
+			6:00	-	KGT
 
 ###############################################################################
 
@@ -1887,24 +1891,25 @@
 Rule	ROK	1987	1988	-	May	Sun>=8	2:00	1:00	D
 Rule	ROK	1987	1988	-	Oct	Sun>=8	3:00	0	S
 
-# From Paul Eggert (2016-08-23):
+# From Paul Eggert (2014-10-30):
 # The Korean Wikipedia entry gives the following sources for UT offsets:
 #
-# 1908: Official Journal Article No. 3994 (decree No. 5)
+# 1908: Official Journal Article No. 3994 (Edict No. 5)
 # 1912: Governor-General of Korea Official Gazette Issue No. 367
 #       (Announcement No. 338)
 # 1954: Presidential Decree No. 876 (1954-03-17)
 # 1961: Law No. 676 (1961-08-07)
+# 1987: Law No. 3919 (1986-12-31)
 #
-# (Another source "1987: Law No. 3919 (1986-12-31)" was in the 2014-10-30
-# edition of the Korean Wikipedia entry.)
+# The Wikipedia entry also has confusing information about a change
+# to UT+9 in April 1910, but then what would be the point of the later change
+# to UT+9 on 1912-01-01?  Omit the 1910 change for now.
 #
 # I guessed that time zone abbreviations through 1945 followed the same
 # rules as discussed under Taiwan, with nominal switches from JST to KST
 # when the respective cities were taken over by the Allies after WWII.
 #
-# For Pyongyang, guess no changes from World War II until 2015, as we
-# have no information otherwise.
+# For Pyongyang we have no information; guess no changes since World War II.
 
 # From Steffen Thorsen (2015-08-07):
 # According to many news sources, North Korea is going to change to
@@ -2064,7 +2069,7 @@
 # Bill Bonnet (2005-05-19) reports that the US Embassy in Ulaanbaatar says
 # there is only one time zone and that DST is observed, citing Microsoft
 # Windows XP as the source.  Risto Nykänen (2005-05-16) reports that
-# travelmongolia.org says there are two time zones (UT +07, +08) with no DST.
+# travelmongolia.org says there are two time zones (UTC+7, UTC+8) with no DST.
 # Oscar van Vlijmen (2005-05-20) reports that the Mongolian Embassy in
 # Washington, DC says there are two time zones, with DST observed.
 # He also found
@@ -2700,7 +2705,7 @@
 # earlier date.
 #
 # Shanks & Pottenger also state that until 1968-05-01 Saudi Arabia had two
-# time zones; the other zone, at UT +04, was in the far eastern part of
+# time zones; the other zone, at UTC+4, was in the far eastern part of
 # the country.  Ignore this, as it's before our 1970 cutoff.
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
@@ -2969,10 +2974,10 @@
 # From Shanks & Pottenger.
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Dushanbe	4:35:12 -	LMT	1924 May  2
-			5:00	-	+05	1930 Jun 21
-			6:00 RussiaAsia +06/+07	1991 Mar 31  2:00s
-			5:00	1:00	+05/+06	1991 Sep  9  2:00s
-			5:00	-	+05
+			5:00	-	DUST	1930 Jun 21 # Dushanbe Time
+			6:00 RussiaAsia DUS%sT	1991 Mar 31  2:00s
+			5:00	1:00	DUSST	1991 Sep  9  2:00s
+			5:00	-	TJT	# Tajikistan Time
 
 # Thailand
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
@@ -2986,10 +2991,11 @@
 # From Shanks & Pottenger.
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Ashgabat	3:53:32 -	LMT	1924 May  2 # or Ashkhabad
-			4:00	-	+04	1930 Jun 21
-			5:00 RussiaAsia	+05/+06	1991 Mar 31  2:00
-			4:00 RussiaAsia	+04/+05	1992 Jan 19  2:00
-			5:00	-	+05
+			4:00	-	ASHT	1930 Jun 21 # Ashkhabad Time
+			5:00 RussiaAsia	ASH%sT	1991 Mar 31  2:00
+			4:00 RussiaAsia	ASH%sT	1991 Oct 27 # independence
+			4:00 RussiaAsia	TM%sT	1992 Jan 19  2:00
+			5:00	-	TMT
 
 # United Arab Emirates
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
@@ -3001,18 +3007,20 @@
 # Byalokoz 1919 says Uzbekistan was 4:27:53.
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Samarkand	4:27:53 -	LMT	1924 May  2
-			4:00	-	+04	1930 Jun 21
-			5:00	-	+05	1981 Apr  1
-			5:00	1:00	+06	1981 Oct  1
-			6:00	-	+06	1982 Apr  1
-			5:00 RussiaAsia	+05/+06	1992
-			5:00	-	+05
+			4:00	-	SAMT	1930 Jun 21 # Samarkand Time
+			5:00	-	SAMT	1981 Apr  1
+			5:00	1:00	SAMST	1981 Oct  1
+			6:00	-	TAST	1982 Apr  1 # Tashkent Time
+			5:00 RussiaAsia	SAM%sT	1991 Sep  1 # independence
+			5:00 RussiaAsia	UZ%sT	1992
+			5:00	-	UZT
 # Milne says Tashkent was 4:37:10.8; round to nearest.
 Zone	Asia/Tashkent	4:37:11 -	LMT	1924 May  2
-			5:00	-	+05	1930 Jun 21
-			6:00 RussiaAsia	+06/+07	1991 Mar 31  2:00
-			5:00 RussiaAsia	+05/+06	1992
-			5:00	-	+05
+			5:00	-	TAST	1930 Jun 21 # Tashkent Time
+			6:00 RussiaAsia	TAS%sT	1991 Mar 31  2:00
+			5:00 RussiaAsia	TAS%sT	1991 Sep  1 # independence
+			5:00 RussiaAsia	UZ%sT	1992
+			5:00	-	UZT
 
 # Vietnam
 
diff --git a/jdk/make/data/tzdata/australasia b/jdk/make/data/tzdata/australasia
index 20a4020..134a01e 100644
--- a/jdk/make/data/tzdata/australasia
+++ b/jdk/make/data/tzdata/australasia
@@ -568,7 +568,7 @@
 # Base the Bougainville entry on the Arawa-Kieta region, which appears to have
 # the most people even though it was devastated in the Bougainville Civil War.
 #
-# Although Shanks gives 1942-03-15 / 1943-11-01 for UT +09, these dates
+# Although Shanks gives 1942-03-15 / 1943-11-01 for JST, these dates
 # are apparently rough guesswork from the starts of military campaigns.
 # The World War II entries below are instead based on Arawa-Kieta.
 # The Japanese occupied Kieta in July 1942,
@@ -576,8 +576,8 @@
 # http://pwencycl.kgbudge.com/B/o/Bougainville.htm
 # and seem to have controlled it until their 1945-08-21 surrender.
 #
-# The Autonomous Region of Bougainville switched from UT +10 to +11
-# on 2014-12-28 at 02:00.  They call +11 "Bougainville Standard Time";
+# The Autonomous Region of Bougainville plans to switch from UTC+10 to UTC+11
+# on 2014-12-28 at 02:00.  They call UTC+11 "Bougainville Standard Time";
 # abbreviate this as BST.  See:
 # http://www.bougainville24.com/bougainville-issues/bougainville-gets-own-timezone/
 #
@@ -643,7 +643,7 @@
 # From Paul Eggert (2014-06-27):
 # The International Date Line Act 2011
 # http://www.parliament.gov.ws/images/ACTS/International_Date_Line_Act__2011_-_Eng.pdf
-# changed Samoa from UT -11 to +13, effective "12 o'clock midnight, on
+# changed Samoa from UTC-11 to UTC+13, effective "12 o'clock midnight, on
 # Thursday 29th December 2011".  The International Date Line was adjusted
 # accordingly.
 
@@ -738,7 +738,7 @@
 # 1886-1891; Baker was similar but exact dates are not known.
 # Inhabited by civilians 1935-1942; U.S. military bases 1943-1944;
 # uninhabited thereafter.
-# Howland observed Hawaii Standard Time (UT -10:30) in 1937;
+# Howland observed Hawaii Standard Time (UT-10:30) in 1937;
 # see page 206 of Elgen M. Long and Marie K. Long,
 # Amelia Earhart: the Mystery Solved, Simon & Schuster (2000).
 # So most likely Howland and Baker observed Hawaii Time from 1935
@@ -1496,7 +1496,7 @@
 # Zealand time.  I understand that is the time they keep locally, anyhow."
 # For now, assume this practice goes back to the introduction of standard time
 # in New Zealand, as this would make Chatham Islands time almost exactly match
-# LMT back when New Zealand was at UT +11:30; also, assume Chatham Islands did
+# LMT back when New Zealand was at UTC+11:30; also, assume Chatham Islands did
 # not observe New Zealand's prewar DST.
 
 ###############################################################################
@@ -1552,7 +1552,7 @@
 # For now, we assume the Ladrones switched at the same time as the Philippines;
 # see Asia/Manila.
 
-# US Public Law 106-564 (2000-12-23) made UT +10 the official standard time,
+# US Public Law 106-564 (2000-12-23) made UTC+10 the official standard time,
 # under the name "Chamorro Standard Time".  There is no official abbreviation,
 # but Congressman Robert A. Underwood, author of the bill that became law,
 # wrote in a press release (2000-12-27) that he will seek the use of "ChST".
@@ -1564,15 +1564,15 @@
 # "I am certain, having lived there for the past decade, that 'Truk'
 # (now properly known as Chuuk) ... is in the time zone GMT+10."
 #
-# Shanks & Pottenger write that Truk switched from UT +10 to +11
+# Shanks & Pottenger write that Truk switched from UTC+10 to UTC+11
 # on 1978-10-01; ignore this for now.
 
 # From Paul Eggert (1999-10-29):
 # The Federated States of Micronesia Visitors Board writes in
 # The Federated States of Micronesia - Visitor Information (1999-01-26)
 # http://www.fsmgov.org/info/clocks.html
-# that Truk and Yap are UT +10, and Ponape and Kosrae are +11.
-# We don't know when Kosrae switched from +12; assume January 1 for now.
+# that Truk and Yap are UTC+10, and Ponape and Kosrae are UTC+11.
+# We don't know when Kosrae switched from UTC+12; assume January 1 for now.
 
 
 # Midway
@@ -1638,11 +1638,11 @@
 # ordaining - by a masterpiece of diplomatic flattery - that
 # the Fourth of July should be celebrated twice in that year."
 
-# Although Shanks & Pottenger says they both switched to UT -11:30
-# in 1911, and to -11 in 1950. many earlier sources give -11
+# Although Shanks & Pottenger says they both switched to UTC-11:30
+# in 1911, and to UTC-11 in 1950. many earlier sources give UTC-11
 # for American Samoa, e.g., the US National Bureau of Standards
 # circular "Standard Time Throughout the World", 1932.
-# Assume American Samoa switched to -11 in 1911, not 1950,
+# Assume American Samoa switched to UTC-11 in 1911, not 1950,
 # and that after 1950 they agreed until (western) Samoa skipped a
 # day in 2011.  Assume also that the Samoas follow the US and New
 # Zealand's "ST"/"DT" style of daylight-saving abbreviations.
diff --git a/jdk/make/data/tzdata/backward b/jdk/make/data/tzdata/backward
index ec96c7e..8352705 100644
--- a/jdk/make/data/tzdata/backward
+++ b/jdk/make/data/tzdata/backward
@@ -59,7 +59,6 @@
 Link	Asia/Urumqi		Asia/Kashgar
 Link	Asia/Kathmandu		Asia/Katmandu
 Link	Asia/Macau		Asia/Macao
-Link	Asia/Yangon		Asia/Rangoon
 Link	Asia/Ho_Chi_Minh	Asia/Saigon
 Link	Asia/Jerusalem		Asia/Tel_Aviv
 Link	Asia/Thimphu		Asia/Thimbu
diff --git a/jdk/make/data/tzdata/etcetera b/jdk/make/data/tzdata/etcetera
index ec31f1b..d2fb91c 100644
--- a/jdk/make/data/tzdata/etcetera
+++ b/jdk/make/data/tzdata/etcetera
@@ -31,13 +31,6 @@
 # need now for the entries that are not on UTC are for ships at sea
 # that cannot use POSIX TZ settings.
 
-# Starting with POSIX 1003.1-2001, the entries below are all
-# unnecessary as settings for the TZ environment variable.  E.g.,
-# instead of TZ='Etc/GMT+4' one can use the POSIX setting TZ='<-04>+4'.
-#
-# Do not use a POSIX TZ setting like TZ='GMT+4', which is four hours
-# behind GMT but uses the completely misleading abbreviation "GMT".
-
 Zone	Etc/GMT		0	-	GMT
 Zone	Etc/UTC		0	-	UTC
 Zone	Etc/UCT		0	-	UCT
@@ -56,13 +49,23 @@
 Link	Etc/GMT				Etc/GMT+0
 Link	Etc/GMT				Etc/GMT0
 
-# Be consistent with POSIX TZ settings in the Zone names,
+# We use POSIX-style signs in the Zone names and the output abbreviations,
 # even though this is the opposite of what many people expect.
 # POSIX has positive signs west of Greenwich, but many people expect
 # positive signs east of Greenwich.  For example, TZ='Etc/GMT+4' uses
-# the abbreviation "-04" and corresponds to 4 hours behind UT
+# the abbreviation "GMT+4" and corresponds to 4 hours behind UT
 # (i.e. west of Greenwich) even though many people would expect it to
 # mean 4 hours ahead of UT (i.e. east of Greenwich).
+#
+# In the draft 5 of POSIX 1003.1-200x, the angle bracket notation allows for
+# TZ='<GMT-4>+4'; if you want time zone abbreviations conforming to
+# ISO 8601 you can use TZ='<-0400>+4'.  Thus the commonly-expected
+# offset is kept within the angle bracket (and is used for display)
+# while the POSIX sign is kept outside the angle bracket (and is used
+# for calculation).
+#
+# Do not use a TZ setting like TZ='GMT+4', which is four hours behind
+# GMT but uses the completely misleading abbreviation "GMT".
 
 # Earlier incarnations of this package were not POSIX-compliant,
 # and had lines such as
@@ -71,31 +74,30 @@
 # way does a
 #		zic -l GMT-12
 # so we moved the names into the Etc subdirectory.
-# Also, the time zone abbreviations are now compatible with %z.
 
-Zone	Etc/GMT-14	14	-	+14
-Zone	Etc/GMT-13	13	-	+13
-Zone	Etc/GMT-12	12	-	+12
-Zone	Etc/GMT-11	11	-	+11
-Zone	Etc/GMT-10	10	-	+10
-Zone	Etc/GMT-9	9	-	+09
-Zone	Etc/GMT-8	8	-	+08
-Zone	Etc/GMT-7	7	-	+07
-Zone	Etc/GMT-6	6	-	+06
-Zone	Etc/GMT-5	5	-	+05
-Zone	Etc/GMT-4	4	-	+04
-Zone	Etc/GMT-3	3	-	+03
-Zone	Etc/GMT-2	2	-	+02
-Zone	Etc/GMT-1	1	-	+01
-Zone	Etc/GMT+1	-1	-	-01
-Zone	Etc/GMT+2	-2	-	-02
-Zone	Etc/GMT+3	-3	-	-03
-Zone	Etc/GMT+4	-4	-	-04
-Zone	Etc/GMT+5	-5	-	-05
-Zone	Etc/GMT+6	-6	-	-06
-Zone	Etc/GMT+7	-7	-	-07
-Zone	Etc/GMT+8	-8	-	-08
-Zone	Etc/GMT+9	-9	-	-09
-Zone	Etc/GMT+10	-10	-	-10
-Zone	Etc/GMT+11	-11	-	-11
-Zone	Etc/GMT+12	-12	-	-12
+Zone	Etc/GMT-14	14	-	GMT-14	# 14 hours ahead of GMT
+Zone	Etc/GMT-13	13	-	GMT-13
+Zone	Etc/GMT-12	12	-	GMT-12
+Zone	Etc/GMT-11	11	-	GMT-11
+Zone	Etc/GMT-10	10	-	GMT-10
+Zone	Etc/GMT-9	9	-	GMT-9
+Zone	Etc/GMT-8	8	-	GMT-8
+Zone	Etc/GMT-7	7	-	GMT-7
+Zone	Etc/GMT-6	6	-	GMT-6
+Zone	Etc/GMT-5	5	-	GMT-5
+Zone	Etc/GMT-4	4	-	GMT-4
+Zone	Etc/GMT-3	3	-	GMT-3
+Zone	Etc/GMT-2	2	-	GMT-2
+Zone	Etc/GMT-1	1	-	GMT-1
+Zone	Etc/GMT+1	-1	-	GMT+1
+Zone	Etc/GMT+2	-2	-	GMT+2
+Zone	Etc/GMT+3	-3	-	GMT+3
+Zone	Etc/GMT+4	-4	-	GMT+4
+Zone	Etc/GMT+5	-5	-	GMT+5
+Zone	Etc/GMT+6	-6	-	GMT+6
+Zone	Etc/GMT+7	-7	-	GMT+7
+Zone	Etc/GMT+8	-8	-	GMT+8
+Zone	Etc/GMT+9	-9	-	GMT+9
+Zone	Etc/GMT+10	-10	-	GMT+10
+Zone	Etc/GMT+11	-11	-	GMT+11
+Zone	Etc/GMT+12	-12	-	GMT+12
diff --git a/jdk/make/data/tzdata/europe b/jdk/make/data/tzdata/europe
index aededb1..8ed7d4b 100644
--- a/jdk/make/data/tzdata/europe
+++ b/jdk/make/data/tzdata/europe
@@ -98,7 +98,8 @@
 #        1:00       CET CEST CEMT Central Europe
 #        1:00:14    SET           Swedish (1879-1899)*
 #        2:00       EET EEST      Eastern Europe
-#        3:00       MSK MSD       Moscow
+#        3:00       FET           Further-eastern Europe (2011-2014)*
+#        3:00       MSK MSD  MSM* Minsk, Moscow
 
 # From Peter Ilieve (1994-12-04),
 # The original six [EU members]: Belgium, France, (West) Germany, Italy,
@@ -605,33 +606,16 @@
 Rule	E-Eur	1981	max	-	Mar	lastSun	 0:00	1:00	S
 Rule	E-Eur	1996	max	-	Oct	lastSun	 0:00	0	-
 
-
-# Daylight saving time for Russia and the Soviet Union
-#
-# The 1917-1921 decree URLs are from Alexander Belopolsky (2016-08-23).
-
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Russia	1917	only	-	Jul	 1	23:00	1:00	MST  # Moscow Summer Time
-#
-# Decree No. 142 (1917-12-22) http://istmat.info/node/28137
 Rule	Russia	1917	only	-	Dec	28	 0:00	0	MMT  # Moscow Mean Time
-#
-# Decree No. 497 (1918-05-30) http://istmat.info/node/30001
 Rule	Russia	1918	only	-	May	31	22:00	2:00	MDST # Moscow Double Summer Time
 Rule	Russia	1918	only	-	Sep	16	 1:00	1:00	MST
-#
-# Decree No. 258 (1919-05-29) http://istmat.info/node/37949
 Rule	Russia	1919	only	-	May	31	23:00	2:00	MDST
-#
-Rule	Russia	1919	only	-	Jul	 1	 0:00u	1:00	MSD
+Rule	Russia	1919	only	-	Jul	 1	 2:00	1:00	MSD
 Rule	Russia	1919	only	-	Aug	16	 0:00	0	MSK
-#
-# Decree No. 63 (1921-02-03) http://istmat.info/node/45840
 Rule	Russia	1921	only	-	Feb	14	23:00	1:00	MSD
-#
-# Decree No. 121 (1921-03-07) http://istmat.info/node/45949
-Rule	Russia	1921	only	-	Mar	20	23:00	2:00	+05
-#
+Rule	Russia	1921	only	-	Mar	20	23:00	2:00	MSM  # Midsummer
 Rule	Russia	1921	only	-	Sep	 1	 0:00	1:00	MSD
 Rule	Russia	1921	only	-	Oct	 1	 0:00	0	-
 # Act No. 925 of the Council of Ministers of the USSR (1980-10-24):
@@ -814,6 +798,8 @@
 # From Alexander Bokovoy (2014-10-09):
 # Belarussian government decided against changing to winter time....
 # http://eng.belta.by/all_news/society/Belarus-decides-against-adjusting-time-in-Russias-wake_i_76335.html
+# From Paul Eggert (2014-10-08):
+# Hence Belarus can share time zone abbreviations with Moscow again.
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Europe/Minsk	1:50:16 -	LMT	1880
@@ -824,7 +810,8 @@
 			3:00	Russia	MSK/MSD	1990
 			3:00	-	MSK	1991 Mar 31  2:00s
 			2:00	Russia	EE%sT	2011 Mar 27  2:00s
-			3:00	-	+03
+			3:00	-	FET	2014 Oct 26  1:00s
+			3:00	-	MSK
 
 # Belgium
 #
@@ -1332,7 +1319,7 @@
 # http://www.parlament-berlin.de/pds-fraktion.nsf/727459127c8b66ee8525662300459099/defc77cb784f180ac1256c2b0030274b/$FILE/bersarint.pdf
 # says that Bersarin issued an order to use Moscow time on May 20.
 # However, Moscow did not observe daylight saving in 1945, so
-# this was equivalent to UT +03, not +04.
+# this was equivalent to CEMT (GMT+3), not GMT+4.
 
 
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
@@ -2296,6 +2283,7 @@
 # http://www.worldtimezone.com/dst_news/dst_news_russia-map-2014-07.html
 
 # From Paul Eggert (2006-03-22):
+# Except for Moscow after 1919-07-01, I invented the time zone abbreviations.
 # Moscow time zone abbreviations after 1919-07-01, and Moscow rules after 1991,
 # are from Andrey A. Chernov.  The rest is from Shanks & Pottenger,
 # except we follow Chernov's report that 1992 DST transitions were Sat
@@ -2371,7 +2359,7 @@
 			 2:00	Poland	CE%sT	1946
 			 3:00	Russia	MSK/MSD	1989 Mar 26  2:00s
 			 2:00	Russia	EE%sT	2011 Mar 27  2:00s
-			 3:00	-	+03	2014 Oct 26  2:00s
+			 3:00	-	FET	2014 Oct 26  2:00s
 			 2:00	-	EET
 
 
@@ -2424,16 +2412,6 @@
 # 78	RU-SPE	Saint Petersburg
 # 83	RU-NEN	Nenets Autonomous Okrug
 
-# From Paul Eggert (2016-08-23):
-# The Soviets switched to UT-based time in 1919.  Decree No. 59
-# (1919-02-08) http://istmat.info/node/35567 established UT-based time
-# zones, and Decree No. 147 (1919-03-29) http://istmat.info/node/35854
-# specified a transition date of 1919-07-01, apparently at 00:00 UT.
-# No doubt only the Soviet-controlled regions switched on that date;
-# later transitions to UT-based time in other parts of Russia are
-# taken from what appear to be guesses by Shanks.
-# (Thanks to Alexander Belopolsky for pointers to the decrees.)
-
 # From Stepan Golosunov (2016-03-07):
 # 11. Regions-violators, 1981-1982.
 # Wikipedia refers to
@@ -2475,7 +2453,7 @@
 # attributes the 1982 changes to the Act of the Council of Ministers
 # of the USSR No. 126 from 18.02.1982.  1980-925.txt also adds
 # Udmurtia to the list of affected territories and lists Khatangsky
-# district separately from Taymyr Autonomous Okrug.  Probably erroneously.
+# district separately from Taymyr Autonomous Okurg.  Probably erroneously.
 #
 # The affected territories are currently listed under Europe/Moscow,
 # Asia/Yekaterinburg and Asia/Krasnoyarsk.
@@ -2535,7 +2513,7 @@
 
 Zone Europe/Moscow	 2:30:17 -	LMT	1880
 			 2:30:17 -	MMT	1916 Jul  3 # Moscow Mean Time
-			 2:31:19 Russia	%s	1919 Jul  1  0:00u
+			 2:31:19 Russia	%s	1919 Jul  1  2:00
 			 3:00	Russia	%s	1921 Oct
 			 3:00	Russia	MSK/MSD	1922 Oct
 			 2:00	-	EET	1930 Jun 21
@@ -2618,21 +2596,22 @@
 # The 1988 transition is from USSR act No. 5 (1988-01-04).
 
 Zone Europe/Volgograd	 2:57:40 -	LMT	1920 Jan  3
-			 3:00	-	+03	1930 Jun 21
-			 4:00	-	+04	1961 Nov 11
-			 4:00	Russia	+04/+05	1988 Mar 27  2:00s
-			 3:00	Russia	+03/+04	1991 Mar 31  2:00s
-			 4:00	-	+04	1992 Mar 29  2:00s
-			 3:00	Russia	+03/+04	2011 Mar 27  2:00s
-			 4:00	-	+04	2014 Oct 26  2:00s
-			 3:00	-	+03
+			 3:00	-	TSAT	1925 Apr  6 # Tsaritsyn Time
+			 3:00	-	STAT	1930 Jun 21 # Stalingrad Time
+			 4:00	-	STAT	1961 Nov 11
+			 4:00	Russia	VOL%sT	1988 Mar 27  2:00s # Volgograd T
+			 3:00	Russia	VOL%sT	1991 Mar 31  2:00s
+			 4:00	-	VOLT	1992 Mar 29  2:00s
+			 3:00	Russia	MSK/MSD	2011 Mar 27  2:00s
+			 4:00	-	MSK	2014 Oct 26  2:00s
+			 3:00	-	MSK
 
 # From Paul Eggert (2016-03-18):
 # Europe/Kirov covers:
 # 43	RU-KIR	Kirov Oblast
 # The 1989 transition is from USSR act No. 227 (1989-03-14).
 #
-Zone Europe/Kirov	 3:18:48 -	LMT	1919 Jul  1  0:00u
+Zone Europe/Kirov	 3:18:48 -	LMT	1919 Jul  1  2:00
 			 3:00	-	+03	1930 Jun 21
 			 4:00	Russia	+04/+05	1989 Mar 26  2:00s
 			 3:00	Russia	+03/+04	1991 Mar 31  2:00s
@@ -2650,16 +2629,16 @@
 # Byalokoz 1919 says Samara was 3:20:20.
 # The 1989 transition is from USSR act No. 227 (1989-03-14).
 
-Zone Europe/Samara	 3:20:20 -	LMT	1919 Jul  1  0:00u
-			 3:00	-	+03	1930 Jun 21
-			 4:00	-	+04	1935 Jan 27
-			 4:00	Russia	+04/+05	1989 Mar 26  2:00s
-			 3:00	Russia	+03/+04	1991 Mar 31  2:00s
-			 2:00	Russia	+02/+03	1991 Sep 29  2:00s
-			 3:00	-	+03	1991 Oct 20  3:00
-			 4:00	Russia	+04/+05	2010 Mar 28  2:00s
-			 3:00	Russia	+03/+04	2011 Mar 27  2:00s
-			 4:00	-	+04
+Zone Europe/Samara	 3:20:20 -	LMT	1919 Jul  1  2:00
+			 3:00	-	SAMT	1930 Jun 21 # Samara Time
+			 4:00	-	SAMT	1935 Jan 27
+			 4:00	Russia	KUY%sT	1989 Mar 26  2:00s # Kuybyshev
+			 3:00	Russia	MSK/MSD	1991 Mar 31  2:00s
+			 2:00	Russia	EE%sT	1991 Sep 29  2:00s
+			 3:00	-	SAMT	1991 Oct 20  3:00
+			 4:00	Russia	SAM%sT	2010 Mar 28  2:00s
+			 3:00	Russia	SAM%sT	2011 Mar 27  2:00s
+			 4:00	-	SAMT
 
 # From Paul Eggert (2016-03-18):
 # Europe/Ulyanovsk covers:
@@ -2674,7 +2653,7 @@
 # From Matt Johnson (2016-03-09):
 # http://publication.pravo.gov.ru/Document/View/0001201603090051
 
-Zone Europe/Ulyanovsk	 3:13:36 -	LMT	1919 Jul  1  0:00u
+Zone Europe/Ulyanovsk	 3:13:36 -	LMT	1919 Jul  1  2:00
 			 3:00	-	+03	1930 Jun 21
 			 4:00	Russia	+04/+05	1989 Mar 26  2:00s
 			 3:00	Russia	+03/+04	1991 Mar 31  2:00s
@@ -2706,12 +2685,12 @@
 
 Zone Asia/Yekaterinburg	 4:02:33 -	LMT	1916 Jul  3
 			 3:45:05 -	PMT	1919 Jul 15  4:00
-			 4:00	-	+04	1930 Jun 21
-			 5:00	Russia	+05/+06	1991 Mar 31  2:00s
-			 4:00	Russia	+04/+05	1992 Jan 19  2:00s
-			 5:00	Russia	+05/+06	2011 Mar 27  2:00s
-			 6:00	-	+06	2014 Oct 26  2:00s
-			 5:00	-	+05
+			 4:00	-	SVET	1930 Jun 21 # Sverdlovsk Time
+			 5:00	Russia	SVE%sT	1991 Mar 31  2:00s
+			 4:00	Russia	SVE%sT	1992 Jan 19  2:00s
+			 5:00	Russia	YEK%sT	2011 Mar 27  2:00s
+			 6:00	-	YEKT	2014 Oct 26  2:00s
+			 5:00	-	YEKT
 
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2001-08-25):
@@ -2721,12 +2700,12 @@
 # Byalokoz 1919 says Omsk was 4:53:30.
 
 Zone Asia/Omsk		 4:53:30 -	LMT	1919 Nov 14
-			 5:00	-	+05	1930 Jun 21
-			 6:00	Russia	+06/+07	1991 Mar 31  2:00s
-			 5:00	Russia	+05/+06	1992 Jan 19  2:00s
-			 6:00	Russia	+06/+07	2011 Mar 27  2:00s
-			 7:00	-	+07	2014 Oct 26  2:00s
-			 6:00	-	+06
+			 5:00	-	OMST	1930 Jun 21 # Omsk Time
+			 6:00	Russia	OMS%sT	1991 Mar 31  2:00s
+			 5:00	Russia	OMS%sT	1992 Jan 19  2:00s
+			 6:00	Russia	OMS%sT	2011 Mar 27  2:00s
+			 7:00	-	OMST	2014 Oct 26  2:00s
+			 6:00	-	OMST
 
 # From Paul Eggert (2016-02-22):
 # Asia/Barnaul covers:
@@ -2806,7 +2785,7 @@
 # Note that time belts (numbered from 2 (Moscow) to 12 according to their
 # GMT/UTC offset and having too many exceptions like regions formally
 # belonging to one belt but using time from another) were replaced
-# with time zones in 2011 with different numbering (there was a
+# with time zones in 2011 with different numberings (there was a
 # 2-hour gap between second and third zones in 2011-2014).
 
 # From Stepan Golosunov (2016-04-12):
@@ -2889,12 +2868,12 @@
 # Byalokoz 1919 says Krasnoyarsk was 6:11:26.
 
 Zone Asia/Krasnoyarsk	 6:11:26 -	LMT	1920 Jan  6
-			 6:00	-	+06	1930 Jun 21
-			 7:00	Russia	+07/+08	1991 Mar 31  2:00s
-			 6:00	Russia	+06/+07	1992 Jan 19  2:00s
-			 7:00	Russia	+07/+08	2011 Mar 27  2:00s
-			 8:00	-	+08	2014 Oct 26  2:00s
-			 7:00	-	+07
+			 6:00	-	KRAT	1930 Jun 21 # Krasnoyarsk Time
+			 7:00	Russia	KRA%sT	1991 Mar 31  2:00s
+			 6:00	Russia	KRA%sT	1992 Jan 19  2:00s
+			 7:00	Russia	KRA%sT	2011 Mar 27  2:00s
+			 8:00	-	KRAT	2014 Oct 26  2:00s
+			 7:00	-	KRAT
 
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2001-08-25):
@@ -2911,12 +2890,12 @@
 
 Zone Asia/Irkutsk	 6:57:05 -	LMT	1880
 			 6:57:05 -	IMT	1920 Jan 25 # Irkutsk Mean Time
-			 7:00	-	+07	1930 Jun 21
-			 8:00	Russia	+08/+09	1991 Mar 31  2:00s
-			 7:00	Russia	+07/+08	1992 Jan 19  2:00s
-			 8:00	Russia	+08/+09	2011 Mar 27  2:00s
-			 9:00	-	+09	2014 Oct 26  2:00s
-			 8:00	-	+08
+			 7:00	-	IRKT	1930 Jun 21 # Irkutsk Time
+			 8:00	Russia	IRK%sT	1991 Mar 31  2:00s
+			 7:00	Russia	IRK%sT	1992 Jan 19  2:00s
+			 8:00	Russia	IRK%sT	2011 Mar 27  2:00s
+			 9:00	-	IRKT	2014 Oct 26  2:00s
+			 8:00	-	IRKT
 
 
 # From Tim Parenti (2014-07-06):
@@ -2933,13 +2912,13 @@
 # http://publication.pravo.gov.ru/Document/View/0001201512300107
 
 Zone Asia/Chita	 7:33:52 -	LMT	1919 Dec 15
-			 8:00	-	+08	1930 Jun 21
-			 9:00	Russia	+09/+10	1991 Mar 31  2:00s
-			 8:00	Russia	+08/+09	1992 Jan 19  2:00s
-			 9:00	Russia	+09/+10	2011 Mar 27  2:00s
-			10:00	-	+10	2014 Oct 26  2:00s
-			 8:00	-	+08	2016 Mar 27  2:00
-			 9:00	-	+09
+			 8:00	-	YAKT	1930 Jun 21 # Yakutsk Time
+			 9:00	Russia	YAK%sT	1991 Mar 31  2:00s
+			 8:00	Russia	YAK%sT	1992 Jan 19  2:00s
+			 9:00	Russia	YAK%sT	2011 Mar 27  2:00s
+			10:00	-	YAKT	2014 Oct 26  2:00s
+			 8:00	-	IRKT	2016 Mar 27  2:00
+			 9:00	-	YAKT
 
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2009-11-29):
@@ -2979,12 +2958,12 @@
 # Byalokoz 1919 says Yakutsk was 8:38:58.
 
 Zone Asia/Yakutsk	 8:38:58 -	LMT	1919 Dec 15
-			 8:00	-	+08	1930 Jun 21
-			 9:00	Russia	+09/+10	1991 Mar 31  2:00s
-			 8:00	Russia	+08/+09	1992 Jan 19  2:00s
-			 9:00	Russia	+09/+10	2011 Mar 27  2:00s
-			10:00	-	+10	2014 Oct 26  2:00s
-			 9:00	-	+09
+			 8:00	-	YAKT	1930 Jun 21 # Yakutsk Time
+			 9:00	Russia	YAK%sT	1991 Mar 31  2:00s
+			 8:00	Russia	YAK%sT	1992 Jan 19  2:00s
+			 9:00	Russia	YAK%sT	2011 Mar 27  2:00s
+			10:00	-	YAKT	2014 Oct 26  2:00s
+			 9:00	-	YAKT
 
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2009-11-29):
@@ -3002,12 +2981,12 @@
 # Go with Byalokoz.
 
 Zone Asia/Vladivostok	 8:47:31 -	LMT	1922 Nov 15
-			 9:00	-	+09	1930 Jun 21
-			10:00	Russia	+10/+11	1991 Mar 31  2:00s
-			 9:00	Russia	+09/+10	1992 Jan 19  2:00s
-			10:00	Russia	+10/+11	2011 Mar 27  2:00s
-			11:00	-	+11	2014 Oct 26  2:00s
-			10:00	-	+10
+			 9:00	-	VLAT	1930 Jun 21 # Vladivostok Time
+			10:00	Russia	VLA%sT	1991 Mar 31  2:00s
+			 9:00	Russia	VLA%sT	1992 Jan 19  2:00s
+			10:00	Russia	VLA%sT	2011 Mar 27  2:00s
+			11:00	-	VLAT	2014 Oct 26  2:00s
+			10:00	-	VLAT
 
 
 # From Tim Parenti (2014-07-03):
@@ -3025,14 +3004,14 @@
 # This transition is no doubt wrong, but we have no better info.
 
 Zone Asia/Khandyga	 9:02:13 -	LMT	1919 Dec 15
-			 8:00	-	+08	1930 Jun 21
-			 9:00	Russia	+09/+10	1991 Mar 31  2:00s
-			 8:00	Russia	+08/+09	1992 Jan 19  2:00s
-			 9:00	Russia	+09/+10	2004
-			10:00	Russia	+10/+11	2011 Mar 27  2:00s
-			11:00	-	+11	2011 Sep 13  0:00s # Decree 725?
-			10:00	-	+10	2014 Oct 26  2:00s
-			 9:00	-	+09
+			 8:00	-	YAKT	1930 Jun 21 # Yakutsk Time
+			 9:00	Russia	YAK%sT	1991 Mar 31  2:00s
+			 8:00	Russia	YAK%sT	1992 Jan 19  2:00s
+			 9:00	Russia	YAK%sT	2004
+			10:00	Russia	VLA%sT	2011 Mar 27  2:00s
+			11:00	-	VLAT	2011 Sep 13  0:00s # Decree 725?
+			10:00	-	YAKT	2014 Oct 26  2:00s
+			 9:00	-	YAKT
 
 
 # From Tim Parenti (2014-07-03):
@@ -3048,14 +3027,15 @@
 
 # The Zone name should be Asia/Yuzhno-Sakhalinsk, but that's too long.
 Zone Asia/Sakhalin	 9:30:48 -	LMT	1905 Aug 23
-			 9:00	-	+09	1945 Aug 25
-			11:00	Russia	+11/+12	1991 Mar 31  2:00s # Sakhalin T
-			10:00	Russia	+10/+11	1992 Jan 19  2:00s
-			11:00	Russia	+11/+12	1997 Mar lastSun  2:00s
-			10:00	Russia	+10/+11	2011 Mar 27  2:00s
-			11:00	-	+11	2014 Oct 26  2:00s
-			10:00	-	+10	2016 Mar 27  2:00s
-			11:00	-	+11
+			 9:00	-	JCST	1937 Oct  1
+			 9:00	-	JST	1945 Aug 25
+			11:00	Russia	SAK%sT	1991 Mar 31  2:00s # Sakhalin T
+			10:00	Russia	SAK%sT	1992 Jan 19  2:00s
+			11:00	Russia	SAK%sT	1997 Mar lastSun  2:00s
+			10:00	Russia	SAK%sT	2011 Mar 27  2:00s
+			11:00	-	SAKT	2014 Oct 26  2:00s
+			10:00	-	SAKT	2016 Mar 27  2:00s
+			11:00	-	SAKT
 
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2009-11-29):
@@ -3078,13 +3058,13 @@
 # http://publication.pravo.gov.ru/Document/View/0001201604050038
 
 Zone Asia/Magadan	10:03:12 -	LMT	1924 May  2
-			10:00	-	+10	1930 Jun 21 # Magadan Time
-			11:00	Russia	+11/+12	1991 Mar 31  2:00s
-			10:00	Russia	+10/+11	1992 Jan 19  2:00s
-			11:00	Russia	+11/+12	2011 Mar 27  2:00s
-			12:00	-	+12	2014 Oct 26  2:00s
-			10:00	-	+10	2016 Apr 24  2:00s
-			11:00	-	+11
+			10:00	-	MAGT	1930 Jun 21 # Magadan Time
+			11:00	Russia	MAG%sT	1991 Mar 31  2:00s
+			10:00	Russia	MAG%sT	1992 Jan 19  2:00s
+			11:00	Russia	MAG%sT	2011 Mar 27  2:00s
+			12:00	-	MAGT	2014 Oct 26  2:00s
+			10:00	-	MAGT	2016 Apr 24  2:00s
+			11:00	-	MAGT
 
 
 # From Tim Parenti (2014-07-06):
@@ -3127,14 +3107,17 @@
 # in Russian.)  In addition, Srednekolymsk appears to be a much older
 # settlement and the population of Zyryanka seems to be declining.
 # Go with Srednekolymsk.
+#
+# Since Magadan Oblast moves to UTC+10 on 2014-10-26, we cannot keep using MAGT
+# as the abbreviation.  Use SRET instead.
 
 Zone Asia/Srednekolymsk	10:14:52 -	LMT	1924 May  2
-			10:00	-	+10	1930 Jun 21
-			11:00	Russia	+11/+12	1991 Mar 31  2:00s
-			10:00	Russia	+10/+11	1992 Jan 19  2:00s
-			11:00	Russia	+11/+12	2011 Mar 27  2:00s
-			12:00	-	+12	2014 Oct 26  2:00s
-			11:00	-	+11
+			10:00	-	MAGT	1930 Jun 21 # Magadan Time
+			11:00	Russia	MAG%sT	1991 Mar 31  2:00s
+			10:00	Russia	MAG%sT	1992 Jan 19  2:00s
+			11:00	Russia	MAG%sT	2011 Mar 27  2:00s
+			12:00	-	MAGT	2014 Oct 26  2:00s
+			11:00	-	SRET	# Srednekolymsk Time
 
 
 # From Tim Parenti (2014-07-03):
@@ -3152,14 +3135,14 @@
 # UTC+12 since at least then, too.
 
 Zone Asia/Ust-Nera	 9:32:54 -	LMT	1919 Dec 15
-			 8:00	-	+08	1930 Jun 21
-			 9:00	Russia	+09/+10	1981 Apr  1
-			11:00	Russia	+11/+12	1991 Mar 31  2:00s
-			10:00	Russia	+10/+11	1992 Jan 19  2:00s
-			11:00	Russia	+11/+12	2011 Mar 27  2:00s
-			12:00	-	+12	2011 Sep 13  0:00s # Decree 725?
-			11:00	-	+11	2014 Oct 26  2:00s
-			10:00	-	+10
+			 8:00	-	YAKT	1930 Jun 21 # Yakutsk Time
+			 9:00	Russia	YAKT	1981 Apr  1
+			11:00	Russia	MAG%sT	1991 Mar 31  2:00s
+			10:00	Russia	MAG%sT	1992 Jan 19  2:00s
+			11:00	Russia	MAG%sT	2011 Mar 27  2:00s
+			12:00	-	MAGT	2011 Sep 13  0:00s # Decree 725?
+			11:00	-	VLAT	2014 Oct 26  2:00s
+			10:00	-	VLAT
 
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2001-08-25):
@@ -3172,12 +3155,12 @@
 # The Zone name should be Asia/Petropavlovsk-Kamchatski or perhaps
 # Asia/Petropavlovsk-Kamchatsky, but these are too long.
 Zone Asia/Kamchatka	10:34:36 -	LMT	1922 Nov 10
-			11:00	-	+11	1930 Jun 21
-			12:00	Russia	+12/+13	1991 Mar 31  2:00s
-			11:00	Russia	+11/+12	1992 Jan 19  2:00s
-			12:00	Russia	+12/+13	2010 Mar 28  2:00s
-			11:00	Russia	+11/+12	2011 Mar 27  2:00s
-			12:00	-	+12
+			11:00	-	PETT	1930 Jun 21 # P-K Time
+			12:00	Russia	PET%sT	1991 Mar 31  2:00s
+			11:00	Russia	PET%sT	1992 Jan 19  2:00s
+			12:00	Russia	PET%sT	2010 Mar 28  2:00s
+			11:00	Russia	PET%sT	2011 Mar 27  2:00s
+			12:00	-	PETT
 
 
 # From Tim Parenti (2014-07-03):
@@ -3185,13 +3168,13 @@
 # 87	RU-CHU	Chukotka Autonomous Okrug
 
 Zone Asia/Anadyr	11:49:56 -	LMT	1924 May  2
-			12:00	-	+12	1930 Jun 21
-			13:00	Russia	+13/+14	1982 Apr  1  0:00s
-			12:00	Russia	+12/+13	1991 Mar 31  2:00s
-			11:00	Russia	+11/+12	1992 Jan 19  2:00s
-			12:00	Russia	+12/+13	2010 Mar 28  2:00s
-			11:00	Russia	+11/+12	2011 Mar 27  2:00s
-			12:00	-	+12
+			12:00	-	ANAT	1930 Jun 21 # Anadyr Time
+			13:00	Russia	ANA%sT	1982 Apr  1  0:00s
+			12:00	Russia	ANA%sT	1991 Mar 31  2:00s
+			11:00	Russia	ANA%sT	1992 Jan 19  2:00s
+			12:00	Russia	ANA%sT	2010 Mar 28  2:00s
+			11:00	Russia	ANA%sT	2011 Mar 27  2:00s
+			12:00	-	ANAT
 
 
 # San Marino
@@ -3512,14 +3495,6 @@
 # Engineered Standard Time," said Twitter user @aysekarahasan.
 # http://www.bbc.com/news/world-europe-34631326
 
-# From Burak AYDIN (2016-09-08):
-# Turkey will stay in Daylight Saving Time even in winter....
-# http://www.resmigazete.gov.tr/eskiler/2016/09/20160908-2.pdf
-#
-# From Paul Eggert (2016-09-07):
-# The change is permanent, so this is the new standard time in Turkey.
-# It takes effect today, which is not much notice.
-
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Turkey	1916	only	-	May	 1	0:00	1:00	S
 Rule	Turkey	1916	only	-	Oct	 1	0:00	0	-
@@ -3583,7 +3558,7 @@
 Zone	Europe/Istanbul	1:55:52 -	LMT	1880
 			1:56:56	-	IMT	1910 Oct # Istanbul Mean Time?
 			2:00	Turkey	EE%sT	1978 Oct 15
-			3:00	Turkey	+03/+04	1985 Apr 20
+			3:00	Turkey	TR%sT	1985 Apr 20 # Turkey Time
 			2:00	Turkey	EE%sT	2007
 			2:00	EU	EE%sT	2011 Mar 27  1:00u
 			2:00	-	EET	2011 Mar 28  1:00u
@@ -3591,8 +3566,7 @@
 			2:00	-	EET	2014 Mar 31  1:00u
 			2:00	EU	EE%sT	2015 Oct 25  1:00u
 			2:00	1:00	EEST	2015 Nov  8  1:00u
-			2:00	EU	EE%sT	2016 Sep  7
-			3:00	-	+03
+			2:00	EU	EE%sT
 Link	Europe/Istanbul	Asia/Istanbul	# Istanbul is in both continents.
 
 # Ukraine
diff --git a/jdk/make/data/tzdata/factory b/jdk/make/data/tzdata/factory
index 7d79693..0a6041d 100644
--- a/jdk/make/data/tzdata/factory
+++ b/jdk/make/data/tzdata/factory
@@ -24,10 +24,9 @@
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
-# For distributors who don't want to put time zone specification in
-# their installation procedures.  Users that run 'date' will get the
-# time zone abbreviation "-00", indicating that the actual time zone
-# is unknown.
+# For companies who don't want to put time zone specification in
+# their installation procedures.  When users run date, they'll get the message.
+# Also useful for the "comp.sources" version.
 
 # Zone	NAME	GMTOFF	RULES	FORMAT
-Zone	Factory	0	-	-00
+Zone	Factory	0	- "Local time zone must be set--see zic manual page"
diff --git a/jdk/make/data/tzdata/leapseconds b/jdk/make/data/tzdata/leapseconds
index 71d774d..a08fbc7 100644
--- a/jdk/make/data/tzdata/leapseconds
+++ b/jdk/make/data/tzdata/leapseconds
@@ -79,7 +79,6 @@
 Leap	2008	Dec	31	23:59:60	+	S
 Leap	2012	Jun	30	23:59:60	+	S
 Leap	2015	Jun	30	23:59:60	+	S
-Leap	2016	Dec	31	23:59:60	+	S
 
-#	Updated through IERS Bulletin C52
-#	File expires on:  28 June 2017
+#	Updated through IERS Bulletin C51
+#	File expires on:  28 December 2016
diff --git a/jdk/make/data/tzdata/northamerica b/jdk/make/data/tzdata/northamerica
index 8ab635d..ec59510 100644
--- a/jdk/make/data/tzdata/northamerica
+++ b/jdk/make/data/tzdata/northamerica
@@ -436,42 +436,11 @@
 # north of the Salmon River, and the towns of Burgdorf and Warren),
 # Nevada (except West Wendover), Oregon (except the northern 3/4 of
 # Malheur county), and Washington
-
-# From Paul Eggert (2016-08-20):
-# In early February 1948, in response to California's electricity shortage,
-# PG&E changed power frequency from 60 to 59.5 Hz during daylight hours,
-# causing electric clocks to lose six minutes per day.  (This did not change
-# legal time, and is not part of the data here.)  See:
-# Ross SA. An energy crisis from the past: Northern California in 1948.
-# Working Paper No. 8, Institute of Governmental Studies, UC Berkeley,
-# 1973-11.  http://escholarship.org/uc/item/8x22k30c
-#
-# In another measure to save electricity, DST was instituted from 1948-03-14
-# at 02:01 to 1949-01-16 at 02:00, with the governor having the option to move
-# the fallback transition earlier.  See pages 3-4 of:
-# http://clerk.assembly.ca.gov/sites/clerk.assembly.ca.gov/files/archive/Statutes/1948/48Vol1_Chapters.pdf
-#
-# In response:
-#
-#   Governor Warren received a torrent of objecting mail, and it is not too much
-#   to speculate that the objections to Daylight Saving Time were one important
-#   factor in the defeat of the Dewey-Warren Presidential ticket in California.
-#     -- Ross, p 25
-#
-# On December 8 the governor exercised the option, setting the date to January 1
-# (LA Times 1948-12-09).  The transition time was 02:00 (LA Times 1949-01-01).
-#
-# Despite the controversy, in 1949 California voters approved Proposition 12,
-# which established DST from April's last Sunday at 01:00 until September's
-# last Sunday at 02:00. This was amended by 1962's Proposition 6, which changed
-# the fall-back date to October's last Sunday. See:
-# http://repository.uchastings.edu/cgi/viewcontent.cgi?article=1501&context=ca_ballot_props
-# http://repository.uchastings.edu/cgi/viewcontent.cgi?article=1636&context=ca_ballot_props
 #
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
-Rule	CA	1948	only	-	Mar	14	2:01	1:00	D
+Rule	CA	1948	only	-	Mar	14	2:00	1:00	D
 Rule	CA	1949	only	-	Jan	 1	2:00	0	S
-Rule	CA	1950	1966	-	Apr	lastSun	1:00	1:00	D
+Rule	CA	1950	1966	-	Apr	lastSun	2:00	1:00	D
 Rule	CA	1950	1961	-	Sep	lastSun	2:00	0	S
 Rule	CA	1962	1966	-	Oct	lastSun	2:00	0	S
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
@@ -3335,7 +3304,7 @@
 # indicating that the normal ET rules are followed.
 #
 # From Paul Eggert (2014-08-19):
-# The 2014-08-13 Cabinet meeting decided to stay on UT -04 year-round.  See:
+# The 2014-08-13 Cabinet meeting decided to stay on UTC-4 year-round.  See:
 # http://tcweeklynews.com/daylight-savings-time-to-be-maintained-p5353-127.htm
 # Model this as a switch from EST/EDT to AST ...
 # From Chris Walton (2014-11-04):
diff --git a/jdk/make/data/tzdata/southamerica b/jdk/make/data/tzdata/southamerica
index bbc0a95..08c89ca 100644
--- a/jdk/make/data/tzdata/southamerica
+++ b/jdk/make/data/tzdata/southamerica
@@ -433,9 +433,9 @@
 # stuck on Summer daylight savings time even though the summer is over.
 
 # From Paul Eggert (2013-09-05):
-# Perhaps San Luis operates on the legal fiction that it is at -04
+# Perhaps San Luis operates on the legal fiction that it is at UTC-4
 # with perpetual summer time, but ordinary usage typically seems to
-# just say it's at -03; see, for example,
+# just say it's at UTC-3; see, for example,
 # http://es.wikipedia.org/wiki/Hora_oficial_argentina
 # We've documented similar situations as being plain changes to
 # standard time, so let's do that here too.  This does not change UTC
diff --git a/jdk/make/data/tzdata/zone.tab b/jdk/make/data/tzdata/zone.tab
index db05060..5649691 100644
--- a/jdk/make/data/tzdata/zone.tab
+++ b/jdk/make/data/tzdata/zone.tab
@@ -284,7 +284,7 @@
 MH	+0905+16720	Pacific/Kwajalein	Kwajalein
 MK	+4159+02126	Europe/Skopje
 ML	+1239-00800	Africa/Bamako
-MM	+1647+09610	Asia/Yangon
+MM	+1647+09610	Asia/Rangoon
 MN	+4755+10653	Asia/Ulaanbaatar	Mongolia (most areas)
 MN	+4801+09139	Asia/Hovd	Bayan-Olgiy, Govi-Altai, Hovd, Uvs, Zavkhan
 MN	+4804+11430	Asia/Choibalsan	Dornod, Sukhbaatar
diff --git a/jdk/make/mapfiles/libnet/mapfile-vers b/jdk/make/mapfiles/libnet/mapfile-vers
index a37668a..0e432d3 100644
--- a/jdk/make/mapfiles/libnet/mapfile-vers
+++ b/jdk/make/mapfiles/libnet/mapfile-vers
@@ -112,7 +112,6 @@
 		NET_EnableFastTcpLoopback;
 		NET_ThrowNew;
                 ipv6_available;
-                initInetAddressIDs;
 
 	local:
 		*;
diff --git a/jdk/make/profile-includes.txt b/jdk/make/profile-includes.txt
index e6de98e..3014a71 100644
--- a/jdk/make/profile-includes.txt
+++ b/jdk/make/profile-includes.txt
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, 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
@@ -183,15 +183,13 @@
     net.properties \
     resources.jar \
     rt.jar \
-    security/policy/limited/US_export_policy.jar \
-    security/policy/unlimited/US_export_policy.jar \
+    security/US_export_policy.jar \
     security/blacklist \
     security/blacklisted.certs \
     security/cacerts \
     security/java.policy \
     security/java.security \
-    security/policy/limited/local_policy.jar \
-    security/policy/unlimited/local_policy.jar \
+    security/local_policy.jar \
     security/trusted.libraries \
     tzdb.dat
 
@@ -220,10 +218,8 @@
     jsse.jar \
     resources.jar \
     rt.jar \
-    security/policy/limited/US_export_policy.jar \
-    security/policy/unlimited/US_export_policy.jar \
-    security/policy/limited/local_policy.jar \
-    security/policy/unlimited/local_policy.jar
+    security/US_export_policy.jar \
+    security/local_policy.jar
 
 
 PROFILE_2_JRE_BIN_FILES := \
diff --git a/jdk/make/profile-rtjar-includes.txt b/jdk/make/profile-rtjar-includes.txt
index 84c6a0f..bda322f 100644
--- a/jdk/make/profile-rtjar-includes.txt
+++ b/jdk/make/profile-rtjar-includes.txt
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2012, 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
@@ -119,7 +119,6 @@
     com/sun/tracing \
     jdk/management \
     jdk/internal/cmm \
-    jdk/internal/instrumentation \
     java/lang/instrument \
     java/lang/management \
     java/security/acl \
@@ -208,6 +207,7 @@
     javax/xml/bind \
     javax/xml/soap \
     javax/xml/ws \
+    jdk/internal/instrumentation \
     jdk/management/resource \
     org/omg \
     sun/applet \
diff --git a/jdk/src/macosx/classes/com/apple/laf/AquaProgressBarUI.java b/jdk/src/macosx/classes/com/apple/laf/AquaProgressBarUI.java
index 80a5e36..1ac16c3 100644
--- a/jdk/src/macosx/classes/com/apple/laf/AquaProgressBarUI.java
+++ b/jdk/src/macosx/classes/com/apple/laf/AquaProgressBarUI.java
@@ -124,9 +124,7 @@
             if (!progressBar.isIndeterminate()) return;
             stopAnimationTimer();
             // start the animation thread
-            if (progressBar.isDisplayable()) {
-              startAnimationTimer();
-            }
+            startAnimationTimer();
         }
 
         if ("JProgressBar.style".equals(prop)) {
@@ -143,9 +141,7 @@
 
     public void ancestorAdded(final AncestorEvent e) {
         if (!progressBar.isIndeterminate()) return;
-        if (progressBar.isDisplayable()) {
-          startAnimationTimer();
-        }
+        startAnimationTimer();
     }
 
     public void ancestorMoved(final AncestorEvent e) { }
diff --git a/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java b/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java
index bc8c0cc..8739340 100644
--- a/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java
+++ b/jdk/src/macosx/classes/com/apple/laf/ScreenMenu.java
@@ -109,7 +109,6 @@
         final Component[] items = fInvoker.getMenuComponents();
         if (needsUpdate(items, childHashArray)) {
             removeAll();
-            fItems.clear();
             if (count <= 0) return;
 
             childHashArray = new int[count];
@@ -233,7 +232,7 @@
         synchronized (getTreeLock()) {
             super.addNotify();
             if (fModelPtr == 0) {
-                fInvoker.getPopupMenu().addContainerListener(this);
+                fInvoker.addContainerListener(this);
                 fInvoker.addComponentListener(this);
                 fPropertyListener = new ScreenMenuPropertyListener(this);
                 fInvoker.addPropertyChangeListener(fPropertyListener);
@@ -267,7 +266,7 @@
             if (fModelPtr != 0) {
                 removeMenuListeners(fModelPtr);
                 fModelPtr = 0;
-                fInvoker.getPopupMenu().removeContainerListener(this);
+                fInvoker.removeContainerListener(this);
                 fInvoker.removeComponentListener(this);
                 fInvoker.removePropertyChangeListener(fPropertyListener);
             }
@@ -288,10 +287,11 @@
     @Override
     public void componentRemoved(final ContainerEvent e) {
         final Component child = e.getChild();
-        final MenuItem sm = fItems.remove(child);
+        final MenuItem sm = fItems.get(child);
         if (sm == null) return;
 
         remove(sm);
+        fItems.remove(sm);
     }
 
     /**
diff --git a/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java b/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java
index 6488051..b1bf878 100644
--- a/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java
+++ b/jdk/src/macosx/classes/sun/lwawt/LWWindowPeer.java
@@ -183,7 +183,6 @@
 
         updateAlwaysOnTopState();
         updateMinimumSize();
-        updateFocusableWindowState();
 
         final Shape shape = getTarget().getShape();
         if (shape != null) {
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessibility.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessibility.java
index 7bc98e7..d3ab6a6 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessibility.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessibility.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 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
@@ -25,8 +25,6 @@
 
 package sun.lwawt.macosx;
 
-import sun.lwawt.LWWindowPeer;
-
 import java.awt.*;
 import java.beans.*;
 import java.lang.reflect.Field;
@@ -84,15 +82,6 @@
         return null;
     }
 
-    static <T> T invokeAndWait(final Callable<T> callable, final Component c, final T defValue) {
-        T value = null;
-        try {
-            value = LWCToolkit.invokeAndWait(callable, c);
-        } catch (final Exception e) { e.printStackTrace(); }
-
-        return value != null ? value : defValue;
-    }
-
     static void invokeLater(final Runnable runnable, final Component c) {
         try {
             LWCToolkit.invokeLater(runnable, c);
@@ -188,7 +177,7 @@
 
                 return new Boolean(as.isAccessibleChildSelected(index));
             }
-        }, c, false);
+        }, c);
     }
 
     public static AccessibleStateSet getAccessibleStateSet(final AccessibleContext ac, final Component c) {
@@ -210,7 +199,7 @@
                 if (ass == null) return null;
                 return ass.contains(as);
             }
-        }, c, false);
+        }, c);
     }
 
     static Field getAccessibleBundleKeyFieldWithReflection() {
@@ -276,7 +265,7 @@
             public Integer call() throws Exception {
                 return at.getCharCount();
             }
-        }, c, 0);
+        }, c);
     }
 
     // Accessibility Threadsafety for JavaComponentAccessibility.m
@@ -301,7 +290,7 @@
                 if (ac == null) return null;
                 return ac.getAccessibleIndexInParent();
             }
-        }, c, -1);
+        }, c);
     }
 
     public static AccessibleComponent getAccessibleComponent(final Accessible a, final Component c) {
@@ -397,7 +386,7 @@
 
                 return aComp.isFocusTraversable();
             }
-        }, c, false);
+        }, c);
     }
 
     public static Accessible accessibilityHitTest(final Container parent, final float hitPointX, final float hitPointY) {
@@ -432,8 +421,6 @@
     }
 
     public static AccessibleAction getAccessibleAction(final Accessible a, final Component c) {
-        if (a == null) return null;
-
         return invokeAndWait(new Callable<AccessibleAction>() {
             public AccessibleAction call() throws Exception {
                 final AccessibleContext ac = a.getAccessibleContext();
@@ -456,7 +443,7 @@
 
                 return aComp.isEnabled();
             }
-        }, c, false);
+        }, c);
     }
 
     // KCH - can we make this a postEvent instead?
@@ -680,28 +667,4 @@
             }
         }, c);
     }
-
-    /**
-     * @return AWTView ptr, a peer of the CPlatformView associated with the toplevel container of the Accessible, if any
-     */
-    private static long getAWTView(Accessible a) {
-        Accessible ax = CAccessible.getSwingAccessible(a);
-        if (!(ax instanceof Component)) return 0;
-
-        return invokeAndWait(new Callable<Long>() {
-            public Long call() throws Exception {
-                Component cont = (Component) ax;
-                while (cont != null && !(cont instanceof Window)) {
-                    cont = cont.getParent();
-                }
-                if (cont != null) {
-                    LWWindowPeer peer = (LWWindowPeer) cont.getPeer();
-                    if (peer != null) {
-                        return ((CPlatformWindow) peer.getPlatformWindow()).getContentView().getAWTView();
-                    }
-                }
-                return 0L;
-            }
-        }, (Component)ax);
-    }
 }
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessibleText.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessibleText.java
index 6abf06e..0237ef9 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessibleText.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CAccessibleText.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 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
@@ -264,8 +264,6 @@
                 final double localY = boundsUnion.getY();
 
                 final Point componentLocation = ac.getAccessibleComponent().getLocationOnScreen();
-                if (componentLocation == null) return ret;
-
                 final double screenX = componentLocation.getX() + localX;
                 final double screenY = componentLocation.getY() + localY;
 
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java
index 73a8875..429a395 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CDataTransferer.java
@@ -147,7 +147,8 @@
             String separator = System.getProperty("line.separator");
             StringBuilder sb = new StringBuilder();
             if(strings.length > 0) {
-                for(int i = 0; i < strings.length; i++) {
+                sb.append(strings[0]);
+                for(int i = 1; i < strings.length; i++) {
                     sb.append(strings[i]);
                     sb.append(separator);
                 }
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java
index 11f05b5..f218c90 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CEmbeddedFrame.java
@@ -91,7 +91,7 @@
         int x = (int)pluginX;
         int y = (int)pluginY;
 
-        responder.handleScrollEvent(x, y, modifierFlags, deltaX, deltaY, NSEvent.SCROLL_PHASE_UNSUPPORTED);
+        responder.handleScrollEvent(x, y, modifierFlags, deltaX, deltaY);
     }
 
     public void handleKeyEvent(int eventType, int modifierFlags, String characters,
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java
index 15c377f..591c16d 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformResponder.java
@@ -34,7 +34,6 @@
 import java.awt.event.InputEvent;
 import java.awt.event.MouseWheelEvent;
 import java.awt.event.KeyEvent;
-import java.util.Locale;
 
 /**
  * Translates NSEvents/NPCocoaEvents into AWT events.
@@ -44,8 +43,6 @@
     private final PlatformEventNotifier eventNotifier;
     private final boolean isNpapiCallback;
     private int lastKeyPressCode = KeyEvent.VK_UNDEFINED;
-    private final DeltaAccumulator deltaAccumulatorX = new DeltaAccumulator();
-    private final DeltaAccumulator deltaAccumulatorY = new DeltaAccumulator();
 
     CPlatformResponder(final PlatformEventNotifier eventNotifier,
                        final boolean isNpapiCallback) {
@@ -92,38 +89,37 @@
      * Handles scroll events.
      */
     void handleScrollEvent(final int x, final int y, final int modifierFlags,
-                           final double deltaX, final double deltaY,
-                           final int scrollPhase) {
+                           final double deltaX, final double deltaY) {
         final int buttonNumber = CocoaConstants.kCGMouseButtonCenter;
         int jmodifiers = NSEvent.nsToJavaMouseModifiers(buttonNumber,
                                                         modifierFlags);
         final boolean isShift = (jmodifiers & InputEvent.SHIFT_DOWN_MASK) != 0;
 
-        int roundDeltaX = deltaAccumulatorX.getRoundedDelta(deltaX, scrollPhase);
-        int roundDeltaY = deltaAccumulatorY.getRoundedDelta(deltaY, scrollPhase);
-
         // Vertical scroll.
-        if (!isShift && (deltaY != 0.0 || roundDeltaY != 0)) {
-            dispatchScrollEvent(x, y, jmodifiers, roundDeltaY, deltaY);
+        if (!isShift && deltaY != 0.0) {
+            dispatchScrollEvent(x, y, jmodifiers, deltaY);
         }
         // Horizontal scroll or shirt+vertical scroll.
         final double delta = isShift && deltaY != 0.0 ? deltaY : deltaX;
-        final int roundDelta = isShift && roundDeltaY != 0 ? roundDeltaY : roundDeltaX;
-        if (delta != 0.0 || roundDelta != 0) {
+        if (delta != 0.0) {
             jmodifiers |= InputEvent.SHIFT_DOWN_MASK;
-            dispatchScrollEvent(x, y, jmodifiers, roundDelta, delta);
+            dispatchScrollEvent(x, y, jmodifiers, delta);
         }
     }
 
     private void dispatchScrollEvent(final int x, final int y,
-                                     final int modifiers,
-                                     final int roundDelta, final double delta) {
+                                     final int modifiers, final double delta) {
         final long when = System.currentTimeMillis();
         final int scrollType = MouseWheelEvent.WHEEL_UNIT_SCROLL;
         final int scrollAmount = 1;
+        int wheelRotation = (int) delta;
+        int signum = (int) Math.signum(delta);
+        if (signum * delta < 1) {
+            wheelRotation = signum;
+        }
         // invert the wheelRotation for the peer
         eventNotifier.notifyMouseWheelEvent(when, x, y, modifiers, scrollType,
-                scrollAmount, -roundDelta, -delta, null);
+                scrollAmount, -wheelRotation, -delta, null);
     }
 
     /**
@@ -175,16 +171,6 @@
                 }
             }
 
-            // If Pinyin Simplified input method is selected, CAPS_LOCK key is supposed to switch
-            // input to latin letters.
-            // It is necessary to use testCharIgnoringModifiers instead of testChar for event
-            // generation in such case to avoid uppercase letters in text components.
-            LWCToolkit lwcToolkit = (LWCToolkit)Toolkit.getDefaultToolkit();
-            if (lwcToolkit.getLockingKeyState(KeyEvent.VK_CAPS_LOCK) &&
-                    Locale.SIMPLIFIED_CHINESE.equals(lwcToolkit.getDefaultKeyboardLocale())) {
-                testChar = testCharIgnoringModifiers;
-            }
-
             jkeyCode = out[0];
             jkeyLocation = out[1];
             jeventType = isNpapiCallback ? NSEvent.npToJavaEventType(eventType) :
@@ -259,46 +245,4 @@
     void handleWindowFocusEvent(boolean gained, LWWindowPeer opposite) {
         eventNotifier.notifyActivation(gained, opposite);
     }
-
-    static class DeltaAccumulator {
-
-        static final double MIN_THRESHOLD = 0.1;
-        static final double MAX_THRESHOLD = 0.5;
-        double accumulatedDelta;
-
-        int getRoundedDelta(double delta, int scrollPhase) {
-
-            int roundDelta = (int) Math.round(delta);
-
-            if (scrollPhase == NSEvent.SCROLL_PHASE_UNSUPPORTED) { // mouse wheel
-                if (roundDelta == 0 && delta != 0) {
-                    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) {
-                    accumulatedDelta = 0;
-                }
-
-                accumulatedDelta += delta;
-
-                double absAccumulatedDelta = Math.abs(accumulatedDelta);
-                if (absAccumulatedDelta > MAX_THRESHOLD) {
-                    roundDelta = (int) Math.round(accumulatedDelta);
-                    accumulatedDelta -= roundDelta;
-                }
-
-                if (end) {
-                    if (roundDelta == 0 && absAccumulatedDelta > MIN_THRESHOLD) {
-                        roundDelta = accumulatedDelta > 0 ? 1 : -1;
-                    }
-                }
-            }
-
-            return roundDelta;
-        }
-    }
 }
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java
index 9d1acaf..3c2cd23 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformView.java
@@ -192,8 +192,7 @@
 
         if (event.getType() == CocoaConstants.NSScrollWheel) {
             responder.handleScrollEvent(x, y, event.getModifierFlags(),
-                                        event.getScrollDeltaX(), event.getScrollDeltaY(),
-                                        event.getScrollPhase());
+                                        event.getScrollDeltaX(), event.getScrollDeltaY());
         } else {
             responder.handleMouseEvent(event.getType(), event.getModifierFlags(), event.getButtonNumber(),
                                        event.getClickCount(), x, y, event.getAbsX(), event.getAbsY());
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java
index a97310a..e449227 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPlatformWindow.java
@@ -61,7 +61,6 @@
     private static native void nativeSetNSWindowRepresentedFilename(long nsWindowPtr, String representedFilename);
     private static native void nativeSetEnabled(long nsWindowPtr, boolean isEnabled);
     private static native void nativeSynthesizeMouseEnteredExitedEvents();
-    private static native void nativeSynthesizeMouseEnteredExitedEvents(long nsWindowPtr, int eventType);
     private static native void nativeDispose(long nsWindowPtr);
     private static native CPlatformWindow nativeGetTopmostPlatformWindowUnderMouse();
     private static native void nativeEnterFullScreenMode(long nsWindowPtr);
@@ -428,6 +427,9 @@
 
     @Override // PlatformWindow
     public void dispose() {
+        if (owner != null) {
+            CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), getNSWindowPtr());
+        }
         contentView.dispose();
         nativeDispose(getNSWindowPtr());
         CPlatformWindow.super.dispose();
@@ -524,6 +526,25 @@
     public void setVisible(boolean visible) {
         final long nsWindowPtr = getNSWindowPtr();
 
+        // Process parent-child relationship when hiding
+        if (!visible) {
+            // Unparent my children
+            for (Window w : target.getOwnedWindows()) {
+                WindowPeer p = (WindowPeer)w.getPeer();
+                if (p instanceof LWWindowPeer) {
+                    CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
+                    if (pw != null && pw.isVisible()) {
+                        CWrapper.NSWindow.removeChildWindow(nsWindowPtr, pw.getNSWindowPtr());
+                    }
+                }
+            }
+
+            // Unparent myself
+            if (owner != null && owner.isVisible()) {
+                CWrapper.NSWindow.removeChildWindow(owner.getNSWindowPtr(), nsWindowPtr);
+            }
+        }
+
         // Configure stuff
         updateIconImages();
         updateFocusabilityForAutoRequestFocus(false);
@@ -597,19 +618,19 @@
 
         // Manage parent-child relationship when showing
         if (visible) {
-            // Order myself above my parent
+            // Add myself as a child
             if (owner != null && owner.isVisible()) {
-                CWrapper.NSWindow.orderWindow(nsWindowPtr, CWrapper.NSWindow.NSWindowAbove, owner.getNSWindowPtr());
+                CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(), nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
                 applyWindowLevel(target);
             }
 
-            // Order my own children above myself
+            // Add my own children to myself
             for (Window w : target.getOwnedWindows()) {
                 WindowPeer p = (WindowPeer)w.getPeer();
                 if (p instanceof LWWindowPeer) {
                     CPlatformWindow pw = (CPlatformWindow)((LWWindowPeer)p).getPlatformWindow();
                     if (pw != null && pw.isVisible()) {
-                        CWrapper.NSWindow.orderWindow(pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove, nsWindowPtr);
+                        CWrapper.NSWindow.addChildWindow(nsWindowPtr, pw.getNSWindowPtr(), CWrapper.NSWindow.NSWindowAbove);
                         pw.applyWindowLevel(w);
                     }
                 }
@@ -827,13 +848,6 @@
             return;
         }
 
-        if (blocked) {
-            // We are going to show a modal window. Previously displayed window will be
-            // blocked/disabled. So we have to send mouse exited event to it now, since
-            // all mouse events are discarded for blocked/disabled windows.
-            nativeSynthesizeMouseEnteredExitedEvents(getNSWindowPtr(), CocoaConstants.NSMouseExited);
-        }
-
         nativeSetEnabled(getNSWindowPtr(), !blocked);
         checkBlockingAndOrder();
     }
@@ -1045,8 +1059,8 @@
             // Order the window to front of the stack of child windows
             final long nsWindowSelfPtr = getNSWindowPtr();
             final long nsWindowOwnerPtr = owner.getNSWindowPtr();
-            CWrapper.NSWindow.orderFront(nsWindowOwnerPtr);
-            CWrapper.NSWindow.orderWindow(nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove, nsWindowOwnerPtr);
+            CWrapper.NSWindow.removeChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr);
+            CWrapper.NSWindow.addChildWindow(nsWindowOwnerPtr, nsWindowSelfPtr, CWrapper.NSWindow.NSWindowAbove);
         }
 
         applyWindowLevel(target);
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterJob.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterJob.java
index 0a6bc23..4de4d57 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterJob.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CPrinterJob.java
@@ -177,6 +177,12 @@
             return;
         }
 
+        // See if this has an NSPrintInfo in it.
+        NSPrintInfo nsPrintInfo = (NSPrintInfo)attributes.get(NSPrintInfo.class);
+        if (nsPrintInfo != null) {
+            fNSPrintInfo = nsPrintInfo.getValue();
+        }
+
         PageRanges pageRangesAttr =  (PageRanges)attributes.get(PageRanges.class);
         if (isSupportedValue(pageRangesAttr, attributes)) {
             SunPageSelection rangeSelect = (SunPageSelection)attributes.get(SunPageSelection.class);
@@ -529,11 +535,8 @@
 
     @Override
     protected void finalize() {
-        synchronized (fNSPrintInfoLock) {
-            if (fNSPrintInfo != -1) {
-                dispose(fNSPrintInfo);
-            }
-            fNSPrintInfo = -1;
+        if (fNSPrintInfo != -1) {
+            dispose(fNSPrintInfo);
         }
     }
 
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java b/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java
index 5962b7f..800d76f 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/CWarningWindow.java
@@ -221,6 +221,15 @@
         synchronized (lock) {
             final long nsWindowPtr = getNSWindowPtr();
 
+            // Process parent-child relationship when hiding
+            if (!visible) {
+                // Unparent myself
+                if (owner != null && owner.isVisible()) {
+                    CWrapper.NSWindow.removeChildWindow(
+                            owner.getNSWindowPtr(), nsWindowPtr);
+                }
+            }
+
             // Actually show or hide the window
             if (visible) {
                 CWrapper.NSWindow.orderFront(nsWindowPtr);
@@ -232,10 +241,10 @@
 
             // Manage parent-child relationship when showing
             if (visible) {
-                // Order myself above my parent
+                // Add myself as a child
                 if (owner != null && owner.isVisible()) {
-                    CWrapper.NSWindow.orderWindow(nsWindowPtr,
-                            CWrapper.NSWindow.NSWindowAbove, owner.getNSWindowPtr());
+                    CWrapper.NSWindow.addChildWindow(owner.getNSWindowPtr(),
+                            nsWindowPtr, CWrapper.NSWindow.NSWindowAbove);
 
                     // do not allow security warning to be obscured by other windows
                     applyWindowLevel(ownerWindow);
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java b/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java
index eccc257..d30a39c 100644
--- a/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/NSEvent.java
@@ -32,13 +32,6 @@
  * JDK functionality.
  */
 final class NSEvent {
-
-    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;
-
     private int type;
     private int modifierFlags;
 
@@ -49,7 +42,6 @@
     private int y;
     private double scrollDeltaY;
     private double scrollDeltaX;
-    private int scrollPhase;
     private int absX;
     private int absY;
 
@@ -70,7 +62,7 @@
     // Called from native
     NSEvent(int type, int modifierFlags, int clickCount, int buttonNumber,
                    int x, int y, int absX, int absY,
-                   double scrollDeltaY, double scrollDeltaX, int scrollPhase) {
+                   double scrollDeltaY, double scrollDeltaX) {
         this.type = type;
         this.modifierFlags = modifierFlags;
         this.clickCount = clickCount;
@@ -81,7 +73,6 @@
         this.absY = absY;
         this.scrollDeltaY = scrollDeltaY;
         this.scrollDeltaX = scrollDeltaX;
-        this.scrollPhase = scrollPhase;
     }
 
     int getType() {
@@ -116,10 +107,6 @@
         return scrollDeltaX;
     }
 
-    int getScrollPhase() {
-        return scrollPhase;
-    }
-
     int getAbsX() {
         return absX;
     }
diff --git a/jdk/src/macosx/classes/sun/lwawt/macosx/NSPrintInfo.java b/jdk/src/macosx/classes/sun/lwawt/macosx/NSPrintInfo.java
new file mode 100644
index 0000000..5698864
--- /dev/null
+++ b/jdk/src/macosx/classes/sun/lwawt/macosx/NSPrintInfo.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright (c) 2011, 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.lwawt.macosx;
+
+
+import java.io.*;
+import javax.print.attribute.*;
+
+public final class NSPrintInfo implements PrintJobAttribute, PrintRequestAttribute, Serializable, Cloneable {
+
+    private long fNSPrintInfo;
+
+    public NSPrintInfo(long nsPrintInfo) {
+        fNSPrintInfo = nsPrintInfo;
+    }
+
+    public long getValue() {
+        return fNSPrintInfo;
+    }
+
+    public boolean equals(Object object) {
+        return (object != null && object instanceof NSPrintInfo && fNSPrintInfo == ((NSPrintInfo)object).fNSPrintInfo);
+    }
+
+    public int hashCode() {
+        return (int)fNSPrintInfo;
+    }
+
+    public String toString() {
+        return "" + fNSPrintInfo;
+    }
+
+    public final Class<? extends Attribute> getCategory() {
+        return NSPrintInfo.class;
+    }
+
+    public final String getName() {
+        return "nsPrintInfo";
+    }
+}
diff --git a/jdk/src/macosx/native/sun/awt/AWTView.h b/jdk/src/macosx/native/sun/awt/AWTView.h
index 1ba06fe..592235b 100644
--- a/jdk/src/macosx/native/sun/awt/AWTView.h
+++ b/jdk/src/macosx/native/sun/awt/AWTView.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 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
@@ -63,8 +63,6 @@
 - (void) deliverJavaMouseEvent: (NSEvent *) event;
 - (jobject) awtComponent:(JNIEnv *)env;
 
-+ (AWTView *) awtView:(JNIEnv *)env ofAccessible:(jobject)jaccessible;
-
 // Input method-related events
 - (void)setInputMethod:(jobject)inputMethod;
 - (void)abandonInput;
diff --git a/jdk/src/macosx/native/sun/awt/AWTView.m b/jdk/src/macosx/native/sun/awt/AWTView.m
index 0808580..66ad514 100644
--- a/jdk/src/macosx/native/sun/awt/AWTView.m
+++ b/jdk/src/macosx/native/sun/awt/AWTView.m
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 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
@@ -35,7 +35,6 @@
 #import "LWCToolkit.h"
 #import "JavaComponentAccessibility.h"
 #import "JavaTextAccessibility.h"
-#import "JavaAccessibilityUtilities.h"
 #import "GeomUtilities.h"
 #import "OSVersion.h"
 #import "CGLLayer.h"
@@ -133,7 +132,7 @@
     self.cglLayer = nil;
 
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
-    (*env)->DeleteWeakGlobalRef(env, m_cPlatformView);
+    (*env)->DeleteGlobalRef(env, m_cPlatformView);
     m_cPlatformView = NULL;
 
     if (fInputMethodLOCKABLE != NULL)
@@ -386,7 +385,7 @@
     }
 
     static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent");
-    static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDDI)V");
+    static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDD)V");
     jobject jEvent = JNFNewObject(env, jctor_NSEvent,
                                   [event type],
                                   [event modifierFlags],
@@ -395,8 +394,7 @@
                                   (jint)localPoint.x, (jint)localPoint.y,
                                   (jint)absP.x, (jint)absP.y,
                                   [event deltaY],
-                                  [event deltaX],
-                                  [AWTToolkit scrollStateWithEvent: event]);
+                                  [event deltaX]);
     if (jEvent == nil) {
         // Unable to create event by some reason.
         return;
@@ -404,12 +402,7 @@
 
     static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView");
     static JNF_MEMBER_CACHE(jm_deliverMouseEvent, jc_PlatformView, "deliverMouseEvent", "(Lsun/lwawt/macosx/NSEvent;)V");
-
-    jobject jlocal = (*env)->NewLocalRef(env, m_cPlatformView);
-    if (!(*env)->IsSameObject(env, jlocal, NULL)) {
-        JNFCallVoidMethod(env, jlocal, jm_deliverMouseEvent, jEvent);
-        (*env)->DeleteLocalRef(env, jlocal);
-    }
+    JNFCallVoidMethod(env, m_cPlatformView, jm_deliverMouseEvent, jEvent);
 }
 
 - (void) resetTrackingArea {
@@ -470,12 +463,7 @@
     static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView");
     static JNF_MEMBER_CACHE(jm_deliverKeyEvent, jc_PlatformView,
                             "deliverKeyEvent", "(Lsun/lwawt/macosx/NSEvent;)V");
-
-    jobject jlocal = (*env)->NewLocalRef(env, m_cPlatformView);
-    if (!(*env)->IsSameObject(env, jlocal, NULL)) {
-        JNFCallVoidMethod(env, jlocal, jm_deliverKeyEvent, jevent);
-        (*env)->DeleteLocalRef(env, jlocal);
-    }
+    JNFCallVoidMethod(env, m_cPlatformView, jm_deliverKeyEvent, jevent);
 
     if (characters != NULL) {
         (*env)->DeleteLocalRef(env, characters);
@@ -490,12 +478,7 @@
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     static JNF_CLASS_CACHE(jc_PlatformView, "sun/lwawt/macosx/CPlatformView");
     static JNF_MEMBER_CACHE(jm_deliverResize, jc_PlatformView, "deliverResize", "(IIII)V");
-
-    jobject jlocal = (*env)->NewLocalRef(env, m_cPlatformView);
-    if (!(*env)->IsSameObject(env, jlocal, NULL)) {
-        JNFCallVoidMethod(env, jlocal, jm_deliverResize, x,y,w,h);
-        (*env)->DeleteLocalRef(env, jlocal);
-    }
+    JNFCallVoidMethod(env, m_cPlatformView, jm_deliverResize, x,y,w,h);
 }
 
 
@@ -524,12 +507,7 @@
 */
         static JNF_CLASS_CACHE(jc_CPlatformView, "sun/lwawt/macosx/CPlatformView");
         static JNF_MEMBER_CACHE(jm_deliverWindowDidExposeEvent, jc_CPlatformView, "deliverWindowDidExposeEvent", "()V");
-
-        jobject jlocal = (*env)->NewLocalRef(env, m_cPlatformView);
-        if (!(*env)->IsSameObject(env, jlocal, NULL)) {
-            JNFCallVoidMethod(env, jlocal, jm_deliverWindowDidExposeEvent);
-            (*env)->DeleteLocalRef(env, jlocal);
-        }
+        JNFCallVoidMethod(env, m_cPlatformView, jm_deliverWindowDidExposeEvent);
 /*
         }
 */
@@ -537,10 +515,8 @@
 }
 
 -(BOOL) isCodePointInUnicodeBlockNeedingIMEvent: (unichar) codePoint {
-    if (((codePoint >= 0x3000) && (codePoint <= 0x303F)) ||
-        ((codePoint >= 0xFF00) && (codePoint <= 0xFFEF))) {
-        // Code point is in 'CJK Symbols and Punctuation' or
-        // 'Halfwidth and Fullwidth Forms' Unicode block.
+    if ((codePoint >= 0x3000) && (codePoint <= 0x303F)) {
+        // Code point is in 'CJK Symbols and Punctuation' Unicode block.
         return YES;
     }
     return NO;
@@ -559,13 +535,7 @@
         }
         return NULL;
     }
-
-    jobject peer = NULL;
-    jobject jlocal = (*env)->NewLocalRef(env, m_cPlatformView);
-    if (!(*env)->IsSameObject(env, jlocal, NULL)) {
-        peer = JNFGetObjectField(env, jlocal, jf_Peer);
-        (*env)->DeleteLocalRef(env, jlocal);
-    }
+    jobject peer = JNFGetObjectField(env, m_cPlatformView, jf_Peer);
     static JNF_CLASS_CACHE(jc_LWWindowPeer, "sun/lwawt/LWWindowPeer");
     static JNF_MEMBER_CACHE(jf_Target, jc_LWWindowPeer, "target", "Ljava/awt/Component;");
     if (peer == NULL) {
@@ -573,27 +543,12 @@
         JNFDumpJavaStack(env);
         return NULL;
     }
-    jobject comp = JNFGetObjectField(env, peer, jf_Target);
-    (*env)->DeleteLocalRef(env, peer);
-    return comp;
-}
-
-+ (AWTView *) awtView:(JNIEnv*)env ofAccessible:(jobject)jaccessible
-{
-    static JNF_STATIC_MEMBER_CACHE(jm_getAWTView, sjc_CAccessibility, "getAWTView", "(Ljavax/accessibility/Accessible;)J");
-
-    jlong jptr = JNFCallStaticLongMethod(env, jm_getAWTView, jaccessible);
-    if (jptr == 0) return nil;
-
-    return (AWTView *)jlong_to_ptr(jptr);
+    return JNFGetObjectField(env, peer, jf_Target);
 }
 
 - (id)getAxData:(JNIEnv*)env
 {
-    jobject jcomponent = [self awtComponent:env];
-    id ax = [[[JavaComponentAccessibility alloc] initWithParent:self withEnv:env withAccessible:jcomponent withIndex:-1 withView:self withJavaRole:nil] autorelease];
-    (*env)->DeleteLocalRef(env, jcomponent);
-    return ax;
+    return [[[JavaComponentAccessibility alloc] initWithParent:self withEnv:env withAccessible:[self awtComponent:env] withIndex:-1 withView:self withJavaRole:nil] autorelease];
 }
 
 - (NSArray *)accessibilityAttributeNames
@@ -1336,7 +1291,7 @@
 JNF_COCOA_ENTER(env);
 
     NSRect rect = NSMakeRect(originX, originY, width, height);
-    jobject cPlatformView = (*env)->NewWeakGlobalRef(env, obj);
+    jobject cPlatformView = (*env)->NewGlobalRef(env, obj);
 
     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
 
diff --git a/jdk/src/macosx/native/sun/awt/AWTWindow.h b/jdk/src/macosx/native/sun/awt/AWTWindow.h
index ee01181..7f7bac7 100644
--- a/jdk/src/macosx/native/sun/awt/AWTWindow.h
+++ b/jdk/src/macosx/native/sun/awt/AWTWindow.h
@@ -46,7 +46,6 @@
     NSWindow *nsWindow;
     AWTWindow *ownerWindow;
     jint preFullScreenLevel;
-    BOOL isMinimizing;
 }
 
 // An instance of either AWTWindow_Normal or AWTWindow_Panel
@@ -60,7 +59,6 @@
 @property (nonatomic) jint styleBits;
 @property (nonatomic) BOOL isEnabled;
 @property (nonatomic) jint preFullScreenLevel;
-@property (nonatomic) BOOL isMinimizing;
 
 
 - (id) initWithPlatformWindow:(JNFWeakJObjectWrapper *)javaPlatformWindow
diff --git a/jdk/src/macosx/native/sun/awt/AWTWindow.m b/jdk/src/macosx/native/sun/awt/AWTWindow.m
index 60f465f..324f9d5 100644
--- a/jdk/src/macosx/native/sun/awt/AWTWindow.m
+++ b/jdk/src/macosx/native/sun/awt/AWTWindow.m
@@ -184,7 +184,6 @@
 @synthesize isEnabled;
 @synthesize ownerWindow;
 @synthesize preFullScreenLevel;
-@synthesize isMinimizing;
 
 - (void) updateMinMaxSize:(BOOL)resizable {
     if (resizable) {
@@ -309,7 +308,6 @@
     [self.nsWindow release]; // the property retains the object already
 
     self.isEnabled = YES;
-    self.isMinimizing = NO;
     self.javaPlatformWindow = platformWindow;
     self.styleBits = bits;
     self.ownerWindow = owner;
@@ -429,68 +427,6 @@
     [super dealloc];
 }
 
-// Tests wheather the corresponding Java paltform window is visible or not
-+ (BOOL) isJavaPlatformWindowVisible:(NSWindow *)window {
-    BOOL isVisible = NO;
-    
-    if ([AWTWindow isAWTWindow:window] && [window delegate] != nil) {
-        AWTWindow *awtWindow = (AWTWindow *)[window delegate];
-        [AWTToolkit eventCountPlusPlus];
-        
-        JNIEnv *env = [ThreadUtilities getJNIEnv];
-        jobject platformWindow = [awtWindow.javaPlatformWindow jObjectWithEnv:env];
-        if (platformWindow != NULL) {
-            static JNF_MEMBER_CACHE(jm_isVisible, jc_CPlatformWindow, "isVisible", "()Z");
-            isVisible = JNFCallBooleanMethod(env, platformWindow, jm_isVisible) == JNI_TRUE ? YES : NO;
-            (*env)->DeleteLocalRef(env, platformWindow);
-            
-        }
-    }
-    return isVisible;
-}
-
-// Orders window's childs based on the current focus state
-- (void) orderChildWindows:(BOOL)focus {
-AWT_ASSERT_APPKIT_THREAD;
-
-    if (self.isMinimizing) {
-        // Do not perform any ordering, if iconify is in progress
-        return;
-    }
-
-    NSEnumerator *windowEnumerator = [[NSApp windows]objectEnumerator];
-    NSWindow *window;
-    while ((window = [windowEnumerator nextObject]) != nil) {
-        if ([AWTWindow isJavaPlatformWindowVisible:window]) {
-            AWTWindow *awtWindow = (AWTWindow *)[window delegate];
-            AWTWindow *owner = awtWindow.ownerWindow;
-            if (IS(awtWindow.styleBits, ALWAYS_ON_TOP)) {
-                // Do not order 'always on top' windows
-                continue;
-            }
-            while (awtWindow.ownerWindow != nil) {
-                if (awtWindow.ownerWindow == self) {
-                    if (focus) {
-                        // Move the childWindow to floating level
-                        // so it will appear in front of its
-                        // parent which owns the focus
-                        [window setLevel:NSFloatingWindowLevel];
-                    } else {
-                        // Focus owner has changed, move the childWindow
-                        // back to normal window level
-                        [window setLevel:NSNormalWindowLevel];
-                    }
-                    // The childWindow should be displayed in front of
-                    // its nearest parentWindow
-                    [window orderWindow:NSWindowAbove relativeTo:[owner.nsWindow windowNumber]];
-                    break;
-                }
-                awtWindow = awtWindow.ownerWindow;
-            }
-        }
-    }
-}
-
 // NSWindow overrides
 - (BOOL) canBecomeKeyWindow {
 AWT_ASSERT_APPKIT_THREAD;
@@ -573,30 +509,6 @@
     // window exposing in _setVisible:(BOOL)
 }
 
-// Hides/shows window's childs during iconify/de-iconify operation
-- (void) iconifyChildWindows:(BOOL)iconify {
-AWT_ASSERT_APPKIT_THREAD;
-
-    NSEnumerator *windowEnumerator = [[NSApp windows]objectEnumerator];
-    NSWindow *window;
-    while ((window = [windowEnumerator nextObject]) != nil) {
-        if ([AWTWindow isJavaPlatformWindowVisible:window]) {
-            AWTWindow *awtWindow = (AWTWindow *)[window delegate];
-            while (awtWindow.ownerWindow != nil) {
-                if (awtWindow.ownerWindow == self) {
-                    if (iconify) {
-                        [window orderOut:window];
-                    } else {
-                        [window orderFront:window];
-                    }
-                    break;
-                }
-                awtWindow = awtWindow.ownerWindow;
-            }
-        }
-    }
-}
-
 - (void) _deliverIconify:(BOOL)iconify {
 AWT_ASSERT_APPKIT_THREAD;
 
@@ -610,28 +522,16 @@
     }
 }
 
-- (void)windowWillMiniaturize:(NSNotification *)notification {
-AWT_ASSERT_APPKIT_THREAD;
-
-    self.isMinimizing = YES;
-    // Excplicitly make myself a key window to avoid possible
-    // negative visual effects during iconify operation
-    [self.nsWindow makeKeyAndOrderFront:self.nsWindow];
-    [self iconifyChildWindows:YES];
-}
-
 - (void)windowDidMiniaturize:(NSNotification *)notification {
 AWT_ASSERT_APPKIT_THREAD;
 
     [self _deliverIconify:JNI_TRUE];
-    self.isMinimizing = NO;
 }
 
 - (void)windowDidDeminiaturize:(NSNotification *)notification {
 AWT_ASSERT_APPKIT_THREAD;
 
     [self _deliverIconify:JNI_FALSE];
-    [self iconifyChildWindows:NO];
 }
 
 - (void) _deliverWindowFocusEvent:(BOOL)focused oppositeWindow:(AWTWindow *)opposite {
@@ -677,7 +577,6 @@
     [AWTWindow setLastKeyWindow:nil];
 
     [self _deliverWindowFocusEvent:YES oppositeWindow: opposite];
-    [self orderChildWindows:YES];
 }
 
 - (void) windowDidResignKey: (NSNotification *) notification {
@@ -705,7 +604,6 @@
     }
 
     [self _deliverWindowFocusEvent:NO oppositeWindow: opposite];
-    [self orderChildWindows:NO];
 }
 
 - (void) windowDidBecomeMain: (NSNotification *) notification {
@@ -800,18 +698,6 @@
 
 - (void)sendEvent:(NSEvent *)event {
         if ([event type] == NSLeftMouseDown || [event type] == NSRightMouseDown || [event type] == NSOtherMouseDown) {
-            // Move parent windows to front and make sure that a child window is displayed
-            // in front of its nearest parent.
-            if (self.ownerWindow != nil) {
-                JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
-                jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
-                if (platformWindow != NULL) {
-                    static JNF_MEMBER_CACHE(jm_orderAboveSiblings, jc_CPlatformWindow, "orderAboveSiblings", "()V");
-                    JNFCallVoidMethod(env,platformWindow, jm_orderAboveSiblings);
-                    (*env)->DeleteLocalRef(env, platformWindow);
-                }
-            }
-            [self orderChildWindows:YES];
 
             NSPoint p = [NSEvent mouseLocation];
             NSRect frame = [self.nsWindow frame];
@@ -821,12 +707,9 @@
             if (p.y >= (frame.origin.y + contentRect.size.height)) {
                 JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
                 jobject platformWindow = [self.javaPlatformWindow jObjectWithEnv:env];
-                if (platformWindow != NULL) {
-                    // Currently, no need to deliver the whole NSEvent.
-                    static JNF_MEMBER_CACHE(jm_deliverNCMouseDown, jc_CPlatformWindow, "deliverNCMouseDown", "()V");
-                    JNFCallVoidMethod(env, platformWindow, jm_deliverNCMouseDown);
-                    (*env)->DeleteLocalRef(env, platformWindow);
-                }
+                // Currently, no need to deliver the whole NSEvent.
+                static JNF_MEMBER_CACHE(jm_deliverNCMouseDown, jc_CPlatformWindow, "deliverNCMouseDown", "()V");
+                JNFCallVoidMethod(env, platformWindow, jm_deliverNCMouseDown);
             }
         }
 }
@@ -1115,16 +998,6 @@
     NSWindow *nsWindow = OBJC(windowPtr);
     [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
         [nsWindow orderBack:nil];
-        // Order parent windows
-        AWTWindow *awtWindow = (AWTWindow*)[nsWindow delegate];
-        while (awtWindow.ownerWindow != nil) {
-            awtWindow = awtWindow.ownerWindow;
-            if ([AWTWindow isJavaPlatformWindowVisible:awtWindow.nsWindow]) {
-                [awtWindow.nsWindow orderBack:nil];
-            }
-        }
-        // Order child windows
-        [(AWTWindow*)[nsWindow delegate] orderChildWindows:NO];
     }];
 
 JNF_COCOA_EXIT(env);
@@ -1276,9 +1149,9 @@
 /*
  * Class:     sun_lwawt_macosx_CPlatformWindow
  * Method:    nativeSynthesizeMouseEnteredExitedEvents
- * Signature: ()V
+ * Signature: (J)V
  */
-JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMouseEnteredExitedEvents__
+JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMouseEnteredExitedEvents
 (JNIEnv *env, jclass clazz)
 {
     JNF_COCOA_ENTER(env);
@@ -1292,29 +1165,6 @@
 
 /*
  * Class:     sun_lwawt_macosx_CPlatformWindow
- * Method:    nativeSynthesizeMouseEnteredExitedEvents
- * Signature: (JI)V
- */
-JNIEXPORT void JNICALL Java_sun_lwawt_macosx_CPlatformWindow_nativeSynthesizeMouseEnteredExitedEvents__JI
-(JNIEnv *env, jclass clazz, jlong windowPtr, jint eventType)
-{
-JNF_COCOA_ENTER(env);
-
-    if (eventType == NSMouseEntered || eventType == NSMouseExited) {
-        NSWindow *nsWindow = OBJC(windowPtr);
-
-        [ThreadUtilities performOnMainThreadWaiting:NO block:^(){
-            [AWTWindow synthesizeMouseEnteredExitedEvents:nsWindow withType:eventType];
-        }];
-    } else {
-        [JNFException raise:env as:kIllegalArgumentException reason:"unknown event type"];
-    }
-    
-JNF_COCOA_EXIT(env);
-}
-
-/*
- * Class:     sun_lwawt_macosx_CPlatformWindow
  * Method:    _toggleFullScreenMode
  * Signature: (J)V
  */
diff --git a/jdk/src/macosx/native/sun/awt/CGraphicsEnv.m b/jdk/src/macosx/native/sun/awt/CGraphicsEnv.m
index 23d8eee..c8044d1 100644
--- a/jdk/src/macosx/native/sun/awt/CGraphicsEnv.m
+++ b/jdk/src/macosx/native/sun/awt/CGraphicsEnv.m
@@ -146,7 +146,6 @@
                     jc_CGraphicsEnvironment, "_displayReconfiguration","(IZ)V");
             JNFCallVoidMethod(env, graphicsEnv, jm_displayReconfiguration,
                     (jint) display, (jboolean) flags & kCGDisplayRemoveFlag);
-            (*env)->DeleteLocalRef(env, graphicsEnv);
         });
     }];
 }
diff --git a/jdk/src/macosx/native/sun/awt/CTrayIcon.m b/jdk/src/macosx/native/sun/awt/CTrayIcon.m
index b3967df..79ae024 100644
--- a/jdk/src/macosx/native/sun/awt/CTrayIcon.m
+++ b/jdk/src/macosx/native/sun/awt/CTrayIcon.m
@@ -136,7 +136,7 @@
     clickCount = [event clickCount];
 
     static JNF_CLASS_CACHE(jc_NSEvent, "sun/lwawt/macosx/NSEvent");
-    static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDDI)V");
+    static JNF_CTOR_CACHE(jctor_NSEvent, jc_NSEvent, "(IIIIIIIIDD)V");
     jobject jEvent = JNFNewObject(env, jctor_NSEvent,
                                   [event type],
                                   [event modifierFlags],
@@ -145,8 +145,7 @@
                                   (jint)localPoint.x, (jint)localPoint.y,
                                   (jint)absP.x, (jint)absP.y,
                                   [event deltaY],
-                                  [event deltaX],
-                                  [AWTToolkit scrollStateWithEvent: event]);
+                                  [event deltaX]);
     if (jEvent == nil) {
         // Unable to create event by some reason.
         return;
diff --git a/jdk/src/macosx/native/sun/awt/JavaAccessibilityAction.m b/jdk/src/macosx/native/sun/awt/JavaAccessibilityAction.m
index 2078e1d..9afd1ff 100644
--- a/jdk/src/macosx/native/sun/awt/JavaAccessibilityAction.m
+++ b/jdk/src/macosx/native/sun/awt/JavaAccessibilityAction.m
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 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
@@ -35,9 +35,9 @@
 {
     self = [super init];
     if (self) {
-        fAccessibleAction = JNFNewWeakGlobalRef(env, accessibleAction);
+        fAccessibleAction = JNFNewGlobalRef(env, accessibleAction);
         fIndex = index;
-        fComponent = JNFNewWeakGlobalRef(env, component);
+        fComponent = JNFNewGlobalRef(env, component);
     }
     return self;
 }
@@ -46,10 +46,10 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
-    JNFDeleteWeakGlobalRef(env, fAccessibleAction);
+    JNFDeleteGlobalRef(env, fAccessibleAction);
     fAccessibleAction = NULL;
 
-    JNFDeleteWeakGlobalRef(env, fComponent);
+    JNFDeleteGlobalRef(env, fComponent);
     fComponent = NULL;
 
     [super dealloc];
@@ -59,10 +59,10 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
-    JNFDeleteWeakGlobalRef(env, fAccessibleAction);
+    JNFDeleteGlobalRef(env, fAccessibleAction);
     fAccessibleAction = NULL;
 
-    JNFDeleteWeakGlobalRef(env, fComponent);
+    JNFDeleteGlobalRef(env, fComponent);
     fComponent = NULL;
 
     [super finalize];
@@ -75,18 +75,7 @@
 
     JNIEnv* env = [ThreadUtilities getJNIEnv];
 
-    jobject fCompLocal = (*env)->NewLocalRef(env, fComponent);
-    if ((*env)->IsSameObject(env, fCompLocal, NULL)) {
-        return @"unknown";
-    }
-    NSString *str = nil;
-    jobject jstr = JNFCallStaticObjectMethod(env, jm_getAccessibleActionDescription, fAccessibleAction, fIndex, fCompLocal);
-    if (jstr != NULL) {
-        NSString *str = JNFJavaToNSString(env, jstr); // AWT_THREADING Safe (AWTRunLoopMode)
-        (*env)->DeleteLocalRef(env, jstr);
-    }
-    (*env)->DeleteLocalRef(env, fCompLocal);
-    return str == nil ? @"unknown" : str;
+    return JNFJavaToNSString(env, JNFCallStaticObjectMethod(env, jm_getAccessibleActionDescription, fAccessibleAction, fIndex, fComponent)); // AWT_THREADING Safe (AWTRunLoopMode)
 }
 
 - (void)perform
@@ -107,9 +96,9 @@
 {
     self = [super init];
     if (self) {
-        fTabGroup = JNFNewWeakGlobalRef(env, tabGroup);
+        fTabGroup = JNFNewGlobalRef(env, tabGroup);
         fIndex = index;
-        fComponent = JNFNewWeakGlobalRef(env, component);
+        fComponent = JNFNewGlobalRef(env, component);
     }
     return self;
 }
@@ -118,10 +107,10 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
-    JNFDeleteWeakGlobalRef(env, fTabGroup);
+    JNFDeleteGlobalRef(env, fTabGroup);
     fTabGroup = NULL;
 
-    JNFDeleteWeakGlobalRef(env, fComponent);
+    JNFDeleteGlobalRef(env, fComponent);
     fComponent = NULL;
 
     [super dealloc];
@@ -131,10 +120,10 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
-    JNFDeleteWeakGlobalRef(env, fTabGroup);
+    JNFDeleteGlobalRef(env, fTabGroup);
     fTabGroup = NULL;
 
-    JNFDeleteWeakGlobalRef(env, fComponent);
+    JNFDeleteGlobalRef(env, fComponent);
     fComponent = NULL;
 
     [super finalize];
diff --git a/jdk/src/macosx/native/sun/awt/JavaAccessibilityUtilities.m b/jdk/src/macosx/native/sun/awt/JavaAccessibilityUtilities.m
index 2b99936..081c7f7 100644
--- a/jdk/src/macosx/native/sun/awt/JavaAccessibilityUtilities.m
+++ b/jdk/src/macosx/native/sun/awt/JavaAccessibilityUtilities.m
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 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
@@ -77,9 +77,7 @@
     jobject axRole = JNFCallStaticObjectMethod(env, sjm_getAccessibleRole, axComponent, component); // AWT_THREADING Safe (AWTRunLoopMode)
     if (axRole == NULL) return @"unknown";
 
-    NSString* str = JNFJavaToNSString(env, axRole);
-    (*env)->DeleteLocalRef(env, axRole);
-    return str;
+    return JNFJavaToNSString(env, axRole);
 }
 
 jobject getAxSelection(JNIEnv *env, jobject axContext, jobject component)
@@ -128,27 +126,21 @@
 {
     static JNF_STATIC_MEMBER_CACHE(jm_VERTICAL, sjc_AccessibleState, "VERTICAL", "Ljavax/accessibility/AccessibleState;");
     jobject axVertState = JNFGetStaticObjectField(env, jm_VERTICAL);
-    BOOL vertical = containsAxState(env, axContext, axVertState, component);
-    (*env)->DeleteLocalRef(env, axVertState);
-    return vertical;
+    return containsAxState(env, axContext, axVertState, component);
 }
 
 BOOL isHorizontal(JNIEnv *env, jobject axContext, jobject component)
 {
     static JNF_STATIC_MEMBER_CACHE(jm_HORIZONTAL, sjc_AccessibleState, "HORIZONTAL", "Ljavax/accessibility/AccessibleState;");
     jobject axHorizState = JNFGetStaticObjectField(env, jm_HORIZONTAL);
-    BOOL horizontal = containsAxState(env, axContext, axHorizState, component);
-    (*env)->DeleteLocalRef(env, axHorizState);
-    return horizontal;
+    return containsAxState(env, axContext, axHorizState, component);
 }
 
 BOOL isShowing(JNIEnv *env, jobject axContext, jobject component)
 {
     static JNF_STATIC_MEMBER_CACHE(jm_SHOWING, sjc_AccessibleState, "SHOWING", "Ljavax/accessibility/AccessibleState;");
     jobject axVisibleState = JNFGetStaticObjectField(env, jm_SHOWING);
-    BOOL showing = containsAxState(env, axContext, axVisibleState, component);
-    (*env)->DeleteLocalRef(env, axVisibleState);
-    return showing;
+    return containsAxState(env, axContext, axVisibleState, component);
 }
 
 NSPoint getAxComponentLocationOnScreen(JNIEnv *env, jobject axComponent, jobject component)
diff --git a/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.m b/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.m
index fbba6a2..ffea40f 100644
--- a/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.m
+++ b/jdk/src/macosx/native/sun/awt/JavaComponentAccessibility.m
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 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
@@ -75,6 +75,7 @@
 static NSMutableDictionary *sAttributeNamesForRoleCache = nil;
 static NSObject *sAttributeNamesLOCK = nil;
 
+
 @interface TabGroupAccessibility : JavaComponentAccessibility {
     NSInteger _numTabs;
 }
@@ -136,11 +137,8 @@
         fView = [view retain];
         fJavaRole = [javaRole retain];
 
-        fAccessible = (*env)->NewWeakGlobalRef(env, accessible);
-        
-        jobject jcomponent = [(AWTView *)fView awtComponent:env];
-        fComponent = (*env)->NewWeakGlobalRef(env, jcomponent);
-        (*env)->DeleteLocalRef(env, jcomponent);
+        fAccessible = JNFNewGlobalRef(env, accessible);
+        fComponent = JNFNewGlobalRef(env, [(AWTView *)fView awtComponent:env]);
 
         fIndex = index;
 
@@ -168,10 +166,10 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
-    (*env)->DeleteWeakGlobalRef(env, fAccessible);
+    JNFDeleteGlobalRef(env, fAccessible);
     fAccessible = NULL;
 
-    (*env)->DeleteWeakGlobalRef(env, fComponent);
+    JNFDeleteGlobalRef(env, fComponent);
     fComponent = NULL;
 
     [fParent release];
@@ -200,10 +198,10 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
-    (*env)->DeleteWeakGlobalRef(env, fAccessible);
+    JNFDeleteGlobalRef(env, fAccessible);
     fAccessible = NULL;
 
-    (*env)->DeleteWeakGlobalRef(env, fComponent);
+    JNFDeleteGlobalRef(env, fComponent);
     fComponent = NULL;
 
     [super finalize];
@@ -295,7 +293,7 @@
 
 + (NSArray *)childrenOfParent:(JavaComponentAccessibility *)parent withEnv:(JNIEnv *)env withChildrenCode:(NSInteger)whichChildren allowIgnored:(BOOL)allowIgnored
 {
-    jobjectArray jchildrenAndRoles = (jobjectArray)JNFCallStaticObjectMethod(env, jm_getChildrenAndRoles, parent->fAccessible, parent->fComponent, whichChildren, allowIgnored); // AWT_THREADING Safe (AWTRunLoop)
+    jobjectArray jchildrenAndRoles = JNFCallStaticObjectMethod(env, jm_getChildrenAndRoles, parent->fAccessible, parent->fComponent, whichChildren, allowIgnored); // AWT_THREADING Safe (AWTRunLoop)
     if (jchildrenAndRoles == NULL) return nil;
 
     jsize arrayLen = (*env)->GetArrayLength(env, jchildrenAndRoles);
@@ -310,35 +308,24 @@
 
         NSString *childJavaRole = nil;
         if (jchildJavaRole != NULL) {
-            jobject jkey = JNFGetObjectField(env, jchildJavaRole, sjf_key);
-            childJavaRole = JNFJavaToNSString(env, jkey);
-            (*env)->DeleteLocalRef(env, jkey);
+            childJavaRole = JNFJavaToNSString(env, JNFGetObjectField(env, jchildJavaRole, sjf_key));
         }
 
         JavaComponentAccessibility *child = [self createWithParent:parent accessible:jchild role:childJavaRole index:childIndex withEnv:env withView:parent->fView];
-        
-        (*env)->DeleteLocalRef(env, jchild);
-        (*env)->DeleteLocalRef(env, jchildJavaRole);
-        
         [children addObject:child];
         childIndex++;
     }
-    (*env)->DeleteLocalRef(env, jchildrenAndRoles);
-    
+
     return children;
 }
 
 + (JavaComponentAccessibility *)createWithAccessible:(jobject)jaccessible withEnv:(JNIEnv *)env withView:(NSView *)view
 {
-    JavaComponentAccessibility *ret = nil;
     jobject jcomponent = [(AWTView *)view awtComponent:env];
     jint index = JNFCallStaticIntMethod(env, sjm_getAccessibleIndexInParent, jaccessible, jcomponent);
-    if (index >= 0) {
-      NSString *javaRole = getJavaRole(env, jaccessible, jcomponent);
-      ret = [self createWithAccessible:jaccessible role:javaRole index:index withEnv:env withView:view];
-    }
-    (*env)->DeleteLocalRef(env, jcomponent);
-    return ret;
+    NSString *javaRole = getJavaRole(env, jaccessible, jcomponent);
+
+    return [self createWithAccessible:jaccessible role:javaRole index:index withEnv:env withView:view];
 }
 
 + (JavaComponentAccessibility *) createWithAccessible:(jobject)jaccessible role:(NSString *)javaRole index:(jint)index withEnv:(JNIEnv *)env withView:(NSView *)view
@@ -352,10 +339,7 @@
     jobject jCAX = [JavaComponentAccessibility getCAccessible:jaccessible withEnv:env];
     if (jCAX == NULL) return nil;
     JavaComponentAccessibility *value = (JavaComponentAccessibility *) jlong_to_ptr(JNFGetLongField(env, jCAX, jf_ptr));
-    if (value != nil) {
-        (*env)->DeleteLocalRef(env, jCAX);
-        return [[value retain] autorelease];
-    }
+    if (value != nil) return [[value retain] autorelease];
 
     // otherwise, create a new instance
     JavaComponentAccessibility *newChild = nil;
@@ -378,7 +362,6 @@
     // must hard CFRetain() pointer poked into Java object
     CFRetain(newChild);
     JNFSetLongField(env, jCAX, jf_ptr, ptr_to_jlong(newChild));
-    (*env)->DeleteLocalRef(env, jCAX);
 
     // return autoreleased instance
     return [newChild autorelease];
@@ -411,7 +394,7 @@
 
     // Get all the other accessibility attributes states we need in one swell foop.
     // javaRole isn't pulled in because we need protected access to AccessibleRole.key
-    jbooleanArray attributeStates = (jbooleanArray)JNFCallStaticObjectMethod(env, jm_getInitialAttributeStates, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
+    jbooleanArray attributeStates = JNFCallStaticObjectMethod(env, jm_getInitialAttributeStates, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
     if (attributeStates == NULL) return nil;
     jboolean *attributeStatesArray = (*env)->GetBooleanArrayElements(env, attributeStates, 0);
     if (attributeStatesArray == NULL) {
@@ -506,7 +489,6 @@
         JavaAxAction *action = [[JavaAxAction alloc] initWithEnv:env withAccessibleAction:axAction withIndex:0 withComponent:fComponent];
         [fActions setObject:action forKey:[self isMenu] ? NSAccessibilityPickAction : NSAccessibilityPressAction];
         [action release];
-        (*env)->DeleteLocalRef(env, axAction);
     }
 }
 
@@ -517,9 +499,7 @@
 
 - (id)parent
 {
-    static JNF_CLASS_CACHE(sjc_Window, "java/awt/Window");
     static JNF_STATIC_MEMBER_CACHE(sjm_getAccessibleParent, sjc_CAccessibility, "getAccessibleParent", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljavax/accessibility/Accessible;");
-    static JNF_STATIC_MEMBER_CACHE(sjm_getSwingAccessible, sjc_CAccessible, "getSwingAccessible", "(Ljavax/accessibility/Accessible;)Ljavax/accessibility/Accessible;");
 
     if(fParent == nil) {
         JNIEnv* env = [ThreadUtilities getJNIEnv];
@@ -529,21 +509,10 @@
         if (jparent == NULL) {
             fParent = fView;
         } else {
-            AWTView *view = fView;
-            jobject jax = JNFCallStaticObjectMethod(env, sjm_getSwingAccessible, fAccessible);
-
-            if (JNFIsInstanceOf(env, jax, &sjc_Window)) {
-                // In this case jparent is an owner toplevel and we should retrieve its own view
-                view = [AWTView awtView:env ofAccessible:jparent];
-            }
-            if (view != nil) {
-                fParent = [JavaComponentAccessibility createWithAccessible:jparent withEnv:env withView:view];
-            }
+            fParent = [JavaComponentAccessibility createWithAccessible:jparent withEnv:env withView:fView];
             if (fParent == nil) {
                 fParent = fView;
             }
-            (*env)->DeleteLocalRef(env, jparent);
-            (*env)->DeleteLocalRef(env, jax );
         }
         [fParent retain];
     }
@@ -591,10 +560,7 @@
         return NO;
     }
 
-    jobject axContext = [self axContextWithEnv:env];
-    BOOL showing = isShowing(env, axContext, fComponent);
-    (*env)->DeleteLocalRef(env, axContext);
-    return showing;
+    return isShowing(env, [self axContextWithEnv:env], fComponent);
 }
 
 // the array of names for each role is cached in the sAttributeNamesForRoleCache
@@ -771,12 +737,7 @@
     JNIEnv* env = [ThreadUtilities getJNIEnv];
 
     jobject val = JNFCallStaticObjectMethod(env, sjm_getAccessibleDescription, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    if (val == NULL) {
-        return @"unknown";
-    }
-    NSString* str = JNFJavaToNSString(env, val);
-    (*env)->DeleteLocalRef(env, val);
-    return str;
+    return JNFJavaToNSString(env, val);
 }
 
 - (BOOL)accessibilityIsHelpAttributeSettable
@@ -792,12 +753,7 @@
     JNIEnv* env = [ThreadUtilities getJNIEnv];
 
     jobject axValue = JNFCallStaticObjectMethod(env, jm_getMaximumAccessibleValue, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    if (axValue == NULL) {
-        return [NSNumber numberWithInt:0];
-    }
-    NSNumber* num = JNFJavaToNSNumber(env, axValue);
-    (*env)->DeleteLocalRef(env, axValue);
-    return num;
+    return JNFJavaToNSNumber(env, axValue);
 }
 
 - (BOOL)accessibilityIsMaxValueAttributeSettable
@@ -813,12 +769,7 @@
     JNIEnv* env = [ThreadUtilities getJNIEnv];
 
     jobject axValue = JNFCallStaticObjectMethod(env, jm_getMinimumAccessibleValue, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    if (axValue == NULL) {
-        return [NSNumber numberWithInt:0];
-    }
-    NSNumber* num = JNFJavaToNSNumber(env, axValue);
-    (*env)->DeleteLocalRef(env, axValue);
-    return num;
+    return JNFJavaToNSNumber(env, axValue);
 }
 
 - (BOOL)accessibilityIsMinValueAttributeSettable
@@ -833,16 +784,13 @@
 
     // cmcnote - should batch these two calls into one that returns an array of two bools, one for vertical and one for horiz
     if (isVertical(env, axContext, fComponent)) {
-        (*env)->DeleteLocalRef(env, axContext);
         return NSAccessibilityVerticalOrientationValue;
     }
 
     if (isHorizontal(env, axContext, fComponent)) {
-        (*env)->DeleteLocalRef(env, axContext);
         return NSAccessibilityHorizontalOrientationValue;
     }
 
-    (*env)->DeleteLocalRef(env, axContext);
     return nil;
 }
 
@@ -874,7 +822,6 @@
     // Get the java screen coords, and make a NSPoint of the bottom left of the AxComponent.
     NSSize size = getAxComponentSize(env, axComponent, fComponent);
     NSPoint point = getAxComponentLocationOnScreen(env, axComponent, fComponent);
-    (*env)->DeleteLocalRef(env, axComponent);
 
     point.y += size.height;
 
@@ -924,9 +871,8 @@
         JNIEnv* env = [ThreadUtilities getJNIEnv];
 
         jobject axRole = JNFCallStaticObjectMethod(env, jm_getAccessibleRoleDisplayString, fAccessible, fComponent);
-        if (axRole != NULL) {
+        if(axRole != NULL) {
             value = JNFJavaToNSString(env, axRole);
-            (*env)->DeleteLocalRef(env, axRole);
         } else {
             value = @"unknown";
         }
@@ -961,9 +907,7 @@
 - (NSValue *)accessibilitySizeAttribute {
     JNIEnv* env = [ThreadUtilities getJNIEnv];
     jobject axComponent = JNFCallStaticObjectMethod(env, sjm_getAccessibleComponent, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    NSValue* size = [NSValue valueWithSize:getAxComponentSize(env, axComponent, fComponent)];
-    (*env)->DeleteLocalRef(env, axComponent);
-    return size;
+    return [NSValue valueWithSize:getAxComponentSize(env, axComponent, fComponent)];
 }
 
 - (BOOL)accessibilityIsSizeAttributeSettable
@@ -1022,12 +966,7 @@
     JNIEnv* env = [ThreadUtilities getJNIEnv];
 
     jobject val = JNFCallStaticObjectMethod(env, sjm_getAccessibleName, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    if (val == NULL) {
-        return @"unknown";
-    }
-    NSString* str = JNFJavaToNSString(env, val);
-    (*env)->DeleteLocalRef(env, val);
-    return str;
+    return JNFJavaToNSString(env, val);
 }
 
 - (BOOL)accessibilityIsTitleAttributeSettable
@@ -1059,20 +998,8 @@
     // a text value is taken care of in JavaTextAccessibility
 
     // cmcnote should coalesce these calls into one java call
-    NSNumber *num = nil;
     jobject axValue = JNFCallStaticObjectMethod(env, sjm_getAccessibleValue, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    if (axValue != NULL) {
-        jobject str = JNFCallStaticObjectMethod(env, jm_getCurrentAccessibleValue, axValue, fComponent);
-        if (str != NULL) {
-            num = JNFJavaToNSNumber(env, str); // AWT_THREADING Safe (AWTRunLoop)
-            (*env)->DeleteLocalRef(env, str);
-        }
-        (*env)->DeleteLocalRef(env, axValue);
-    }
-    if (num == nil) {
-        num = [NSNumber numberWithInt:0];
-    }
-    return num;
+    return JNFJavaToNSNumber(env, JNFCallStaticObjectMethod(env, jm_getCurrentAccessibleValue, axValue, fComponent)); // AWT_THREADING Safe (AWTRunLoop)
 }
 
 - (BOOL)accessibilityIsValueAttributeSettable
@@ -1171,10 +1098,7 @@
     id value = nil;
     if (JNFIsInstanceOf(env, jparent, &jc_Container)) {
         jobject jaccessible = JNFCallStaticObjectMethod(env, jm_accessibilityHitTest, jparent, (jfloat)point.x, (jfloat)point.y); // AWT_THREADING Safe (AWTRunLoop)
-        if (jaccessible != NULL) {
-            value = [JavaComponentAccessibility createWithAccessible:jaccessible withEnv:env withView:fView];
-            (*env)->DeleteLocalRef(env, jaccessible);
-        }
+        value = [JavaComponentAccessibility createWithAccessible:jaccessible withEnv:env withView:fView];
     }
 
     if (value == nil) {
@@ -1206,7 +1130,6 @@
         if (JNFIsInstanceOf(env, focused, &sjc_Accessible)) {
             value = [JavaComponentAccessibility createWithAccessible:focused withEnv:env withView:fView];
         }
-        (*env)->DeleteLocalRef(env, focused);
     }
 
     if (value == nil) {
@@ -1313,46 +1236,38 @@
     for (i = 0; i < _numTabs; i++) {
         aTab = (JavaComponentAccessibility *)[tabs objectAtIndex:i];
         if ([aTab isAccessibleWithEnv:env forAccessible:selAccessible]) {
-            (*env)->DeleteLocalRef(env, selAccessible);
             return aTab;
         }
     }
-    (*env)->DeleteLocalRef(env, selAccessible);
+
     return nil;
 }
 
 - (NSArray *)tabControlsWithEnv:(JNIEnv *)env withTabGroupAxContext:(jobject)axContext withTabCode:(NSInteger)whichTabs allowIgnored:(BOOL)allowIgnored
 {
-    jobjectArray jtabsAndRoles = (jobjectArray)JNFCallStaticObjectMethod(env, jm_getChildrenAndRoles, fAccessible, fComponent, whichTabs, allowIgnored); // AWT_THREADING Safe (AWTRunLoop)
+    jobjectArray jtabsAndRoles = JNFCallStaticObjectMethod(env, jm_getChildrenAndRoles, fAccessible, fComponent, whichTabs, allowIgnored); // AWT_THREADING Safe (AWTRunLoop)
     if(jtabsAndRoles == NULL) return nil;
 
     jsize arrayLen = (*env)->GetArrayLength(env, jtabsAndRoles);
-    if (arrayLen == 0) {
-        (*env)->DeleteLocalRef(env, jtabsAndRoles);
-        return nil;
-    }
+    if (arrayLen == 0) return nil;
+
     NSMutableArray *tabs = [NSMutableArray arrayWithCapacity:(arrayLen/2)];
 
     // all of the tabs have the same role, so we can just find out what that is here and use it for all the tabs
     jobject jtabJavaRole = (*env)->GetObjectArrayElement(env, jtabsAndRoles, 1); // the array entries alternate between tab/role, starting with tab. so the first role is entry 1.
-    if (jtabJavaRole == NULL) {
-        (*env)->DeleteLocalRef(env, jtabsAndRoles);
-        return nil;
-    }
-    jobject jkey = JNFGetObjectField(env, jtabJavaRole, sjf_key);
-    NSString *tabJavaRole = JNFJavaToNSString(env, jkey);
-    (*env)->DeleteLocalRef(env, jkey);
+    if (jtabJavaRole == NULL) return nil;
+
+    NSString *tabJavaRole = JNFJavaToNSString(env, JNFGetObjectField(env, jtabJavaRole, sjf_key));
 
     NSInteger i;
     NSUInteger tabIndex = (whichTabs >= 0) ? whichTabs : 0; // if we're getting one particular child, make sure to set its index correctly
     for(i = 0; i < arrayLen; i+=2) {
         jobject jtab = (*env)->GetObjectArrayElement(env, jtabsAndRoles, i);
         JavaComponentAccessibility *tab = [[[TabGroupControlAccessibility alloc] initWithParent:self withEnv:env withAccessible:jtab withIndex:tabIndex withTabGroup:axContext withView:[self view] withJavaRole:tabJavaRole] autorelease];
-        (*env)->DeleteLocalRef(env, jtab);
         [tabs addObject:tab];
         tabIndex++;
     }
-    (*env)->DeleteLocalRef(env, jtabsAndRoles);
+
     return tabs;
 }
 
@@ -1371,9 +1286,7 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     jobject axContext = [self axContextWithEnv:env];
-    id tabs = [self tabControlsWithEnv:env withTabGroupAxContext:axContext withTabCode:JAVA_AX_ALL_CHILDREN allowIgnored:NO];
-    (*env)->DeleteLocalRef(env, axContext);
-    return tabs;
+    return [self tabControlsWithEnv:env withTabGroupAxContext:axContext withTabCode:JAVA_AX_ALL_CHILDREN allowIgnored:NO];
 }
 
 - (BOOL)accessibilityIsTabsAttributeSettable
@@ -1393,9 +1306,7 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     jobject axContext = [self axContextWithEnv:env];
-    NSArray* cont = [self contentsWithEnv:env withTabGroupAxContext:axContext withTabCode:JAVA_AX_ALL_CHILDREN allowIgnored:NO];
-    (*env)->DeleteLocalRef(env, axContext);
-    return cont;
+    return [self contentsWithEnv:env withTabGroupAxContext:axContext withTabCode:JAVA_AX_ALL_CHILDREN allowIgnored:NO];
 }
 
 - (BOOL)accessibilityIsContentsAttributeSettable
@@ -1408,9 +1319,7 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     jobject axContext = [self axContextWithEnv:env];
-    id val = [self currentTabWithEnv:env withAxContext:axContext];
-    (*env)->DeleteLocalRef(env, axContext);
-    return val;
+    return [self currentTabWithEnv:env withAxContext:axContext];
 }
 
 - (BOOL)accessibilityIsValueAttributeSettable
@@ -1427,7 +1336,6 @@
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     jobject axContext = [self axContextWithEnv:env];
     setAxContextSelection(env, axContext, fIndex, fComponent);
-    (*env)->DeleteLocalRef(env, axContext);
 }
 
 - (NSArray *)accessibilityChildrenAttribute
@@ -1463,7 +1371,6 @@
                 result = children;
             }
         }
-        (*env)->DeleteLocalRef(env, axContext);
     } else {
         result = [super accessibilityArrayAttributeValues:attribute index:index maxCount:maxCount];
     }
@@ -1482,7 +1389,7 @@
     self = [super initWithParent:parent withEnv:env withAccessible:accessible withIndex:index withView:view withJavaRole:javaRole];
     if (self) {
         if (tabGroup != NULL) {
-            fTabGroupAxContext = JNFNewWeakGlobalRef(env, tabGroup);
+            fTabGroupAxContext = JNFNewGlobalRef(env, tabGroup);
         } else {
             fTabGroupAxContext = NULL;
         }
@@ -1495,7 +1402,7 @@
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
     if (fTabGroupAxContext != NULL) {
-        JNFDeleteWeakGlobalRef(env, fTabGroupAxContext);
+        JNFDeleteGlobalRef(env, fTabGroupAxContext);
         fTabGroupAxContext = NULL;
     }
 
@@ -1507,7 +1414,7 @@
     JNIEnv *env = [ThreadUtilities getJNIEnvUncached];
 
     if (fTabGroupAxContext != NULL) {
-        JNFDeleteWeakGlobalRef(env, fTabGroupAxContext);
+        JNFDeleteGlobalRef(env, fTabGroupAxContext);
         fTabGroupAxContext = NULL;
     }
 
@@ -1518,14 +1425,9 @@
 {
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     jobject axContext = [self axContextWithEnv:env];
-    jobject selAccessible = getAxContextSelection(env, [self tabGroup], fIndex, fComponent);
 
     // Returns the current selection of the page tab list
-    id val = [NSNumber numberWithBool:ObjectEquals(env, axContext, selAccessible, fComponent)];
-
-    (*env)->DeleteLocalRef(env, selAccessible);
-    (*env)->DeleteLocalRef(env, axContext);
-    return val;
+    return [NSNumber numberWithBool:ObjectEquals(env, axContext, getAxContextSelection(env, [self tabGroup], fIndex, fComponent), fComponent)];
 }
 
 - (void)getActionsWithEnv:(JNIEnv *)env
@@ -1540,8 +1442,7 @@
     if (fTabGroupAxContext == NULL) {
         JNIEnv* env = [ThreadUtilities getJNIEnv];
         jobject tabGroupAxContext = [(JavaComponentAccessibility *)[self parent] axContextWithEnv:env];
-        fTabGroupAxContext = JNFNewWeakGlobalRef(env, tabGroupAxContext);
-        (*env)->DeleteLocalRef(env, tabGroupAxContext);
+        fTabGroupAxContext = JNFNewGlobalRef(env, tabGroupAxContext);
     }
     return fTabGroupAxContext;
 }
@@ -1576,10 +1477,8 @@
         if ([[aElement accessibilityRoleAttribute] isEqualToString:NSAccessibilityScrollBarRole]) {
             jobject elementAxContext = [aElement axContextWithEnv:env];
             if (isHorizontal(env, elementAxContext, fComponent)) {
-                (*env)->DeleteLocalRef(env, elementAxContext);
                 return aElement;
             }
-            (*env)->DeleteLocalRef(env, elementAxContext);
         }
     }
 
@@ -1605,10 +1504,8 @@
         if ([[aElement accessibilityRoleAttribute] isEqualToString:NSAccessibilityScrollBarRole]) {
             jobject elementAxContext = [aElement axContextWithEnv:env];
             if (isVertical(env, elementAxContext, fComponent)) {
-                (*env)->DeleteLocalRef(env, elementAxContext);
                 return aElement;
             }
-            (*env)->DeleteLocalRef(env, elementAxContext);
         }
     }
 
diff --git a/jdk/src/macosx/native/sun/awt/JavaTextAccessibility.m b/jdk/src/macosx/native/sun/awt/JavaTextAccessibility.m
index f7e17b0..2809d8b 100644
--- a/jdk/src/macosx/native/sun/awt/JavaTextAccessibility.m
+++ b/jdk/src/macosx/native/sun/awt/JavaTextAccessibility.m
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 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
@@ -112,9 +112,7 @@
         // if it's static text, the AppKit AXValue is the java accessibleName
         jobject axName = JNFCallStaticObjectMethod(env, sjm_getAccessibleName, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
         if (axName != NULL) {
-            NSString* str = JNFJavaToNSString(env, axName);
-            (*env)->DeleteLocalRef(env, axName);
-            return str;
+            return JNFJavaToNSString(env, axName);
         }
         // value is still nil if no accessibleName for static text. Below, try to get the accessibleText.
     }
@@ -122,18 +120,12 @@
     // cmcnote: inefficient to make three distinct JNI calls. Coalesce. radr://3951923
     jobject axText = JNFCallStaticObjectMethod(env, sjm_getAccessibleText, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
     if (axText == NULL) return nil;
-    (*env)->DeleteLocalRef(env, axText);
-    
+
     jobject axEditableText = JNFCallStaticObjectMethod(env, sjm_getAccessibleEditableText, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
     if (axEditableText == NULL) return nil;
 
     static JNF_STATIC_MEMBER_CACHE(jm_getTextRange, sjc_CAccessibleText, "getTextRange", "(Ljavax/accessibility/AccessibleEditableText;IILjava/awt/Component;)Ljava/lang/String;");
-    jobject jrange = JNFCallStaticObjectMethod(env, jm_getTextRange, axEditableText, 0, getAxTextCharCount(env, axEditableText, fComponent), fComponent);
-    NSString *string = JNFJavaToNSString(env, jrange); // AWT_THREADING Safe (AWTRunLoop)
-
-    (*env)->DeleteLocalRef(env, jrange);
-    (*env)->DeleteLocalRef(env, axEditableText);
-    
+    NSString *string = JNFJavaToNSString(env, JNFCallStaticObjectMethod(env, jm_getTextRange, axEditableText, 0, getAxTextCharCount(env, axEditableText, fComponent), fComponent)); // AWT_THREADING Safe (AWTRunLoop)
     if (string == nil) string = @"";
     return string;
 }
@@ -147,7 +139,6 @@
     JNIEnv* env = [ThreadUtilities getJNIEnv];
     jobject axEditableText = JNFCallStaticObjectMethod(env, sjm_getAccessibleEditableText, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
     if (axEditableText == NULL) return NO;
-    (*env)->DeleteLocalRef(env, axEditableText);
     return YES;
 }
 
@@ -166,9 +157,7 @@
     static JNF_STATIC_MEMBER_CACHE(jm_getSelectedText, sjc_CAccessibleText, "getSelectedText", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;)Ljava/lang/String;");
     jobject axText = JNFCallStaticObjectMethod(env, jm_getSelectedText, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
     if (axText == NULL) return @"";
-    NSString* str = JNFJavaToNSString(env, axText);
-    (*env)->DeleteLocalRef(env, axText);
-    return str;
+    return JNFJavaToNSString(env, axText);
 }
 
 - (BOOL)accessibilityIsSelectedTextAttributeSettable
@@ -231,9 +220,7 @@
     // also, static text doesn't always have accessibleText. if axText is null, should get the charcount of the accessibleName instead
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     jobject axText = JNFCallStaticObjectMethod(env, sjm_getAccessibleText, fAccessible, fComponent); // AWT_THREADING Safe (AWTRunLoop)
-    NSNumber* num = [NSNumber numberWithInt:getAxTextCharCount(env, axText, fComponent)];
-    (*env)->DeleteLocalRef(env, axText);
-    return num;
+    return [NSNumber numberWithInt:getAxTextCharCount(env, axText, fComponent)];
 }
 
 - (BOOL)accessibilityIsNumberOfCharactersAttributeSettable
@@ -298,7 +285,7 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     static JNF_STATIC_MEMBER_CACHE(jm_getBoundsForRange, sjc_CAccessibleText, "getBoundsForRange", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;II)[D");
-    jdoubleArray axBounds = (jdoubleArray)JNFCallStaticObjectMethod(env, jm_getBoundsForRange, fAccessible, fComponent, range.location, range.length); // AWT_THREADING Safe (AWTRunLoop)
+    jdoubleArray axBounds = JNFCallStaticObjectMethod(env, jm_getBoundsForRange, fAccessible, fComponent, range.location, range.length); // AWT_THREADING Safe (AWTRunLoop)
     if (axBounds == NULL) return nil;
 
     // We cheat because we know that the array is 4 elements long (x, y, width, height)
@@ -337,7 +324,7 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     static JNF_STATIC_MEMBER_CACHE(jm_getRangeForLine, sjc_CAccessibleText, "getRangeForLine", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;I)[I");
-    jintArray axTextRange = (jintArray)JNFCallStaticObjectMethod(env, jm_getRangeForLine, fAccessible, fComponent, [line intValue]); // AWT_THREADING Safe (AWTRunLoop)
+    jintArray axTextRange = JNFCallStaticObjectMethod(env, jm_getRangeForLine, fAccessible, fComponent, [line intValue]); // AWT_THREADING Safe (AWTRunLoop)
     if (axTextRange == NULL) return nil;
 
     return javaIntArrayToNSRangeValue(env,axTextRange);
@@ -363,12 +350,10 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     static JNF_STATIC_MEMBER_CACHE(jm_getStringForRange, sjc_CAccessibleText, "getStringForRange", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;II)Ljava/lang/String;");
-    jstring jstringForRange = (jstring)JNFCallStaticObjectMethod(env, jm_getStringForRange, fAccessible, fComponent, range.location, range.length); // AWT_THREADING Safe (AWTRunLoop)
+    jstring jstringForRange = JNFCallStaticObjectMethod(env, jm_getStringForRange, fAccessible, fComponent, range.location, range.length); // AWT_THREADING Safe (AWTRunLoop)
 
     if (jstringForRange == NULL) return @"";
-    NSString* str = JNFJavaToNSString(env, jstringForRange);
-    (*env)->DeleteLocalRef(env, jstringForRange);
-    return str;
+    return JNFJavaToNSString(env, jstringForRange);
 }
 
 //
@@ -421,7 +406,7 @@
 
     JNIEnv *env = [ThreadUtilities getJNIEnv];
     static JNF_STATIC_MEMBER_CACHE(jm_getRangeForIndex, sjc_CAccessibleText, "getRangeForIndex", "(Ljavax/accessibility/Accessible;Ljava/awt/Component;I)[I");
-    jintArray axTextRange = (jintArray)JNFCallStaticObjectMethod(env, jm_getRangeForIndex, fAccessible, fComponent, index); // AWT_THREADING Safe (AWTRunLoop)
+    jintArray axTextRange = JNFCallStaticObjectMethod(env, jm_getRangeForIndex, fAccessible, fComponent, index); // AWT_THREADING Safe (AWTRunLoop)
     if (axTextRange == NULL) return nil;
 
     return javaIntArrayToNSRangeValue(env, axTextRange);
diff --git a/jdk/src/macosx/native/sun/awt/LWCToolkit.h b/jdk/src/macosx/native/sun/awt/LWCToolkit.h
index 0a57501..c3e1b53 100644
--- a/jdk/src/macosx/native/sun/awt/LWCToolkit.h
+++ b/jdk/src/macosx/native/sun/awt/LWCToolkit.h
@@ -40,7 +40,6 @@
 @interface AWTToolkit : NSObject { }
 + (long) getEventCount;
 + (void) eventCountPlusPlus;
-+ (jint) scrollStateWithEvent: (NSEvent*) event;
 @end
 
 /*
diff --git a/jdk/src/macosx/native/sun/awt/LWCToolkit.m b/jdk/src/macosx/native/sun/awt/LWCToolkit.m
index 8f0a290..8b34eba 100644
--- a/jdk/src/macosx/native/sun/awt/LWCToolkit.m
+++ b/jdk/src/macosx/native/sun/awt/LWCToolkit.m
@@ -39,13 +39,6 @@
 
 #import "sizecalc.h"
 
-// SCROLL PHASE STATE
-#define SCROLL_PHASE_UNSUPPORTED 1
-#define SCROLL_PHASE_BEGAN 2
-#define SCROLL_PHASE_CONTINUED 3
-#define SCROLL_PHASE_CANCELLED 4
-#define SCROLL_PHASE_ENDED 5
-
 int gNumberOfButtons;
 jint* gButtonDownMasks;
 
@@ -61,23 +54,6 @@
     eventCount++;
 }
 
-+ (jint) scrollStateWithEvent: (NSEvent*) event {
-
-    if ([event type] != NSScrollWheel) {
-        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;
-    }
-    return SCROLL_PHASE_CONTINUED;
-}
 @end
 
 
diff --git a/jdk/src/macosx/native/sun/font/AWTFont.m b/jdk/src/macosx/native/sun/font/AWTFont.m
index 6458f17..bfb90ec 100644
--- a/jdk/src/macosx/native/sun/font/AWTFont.m
+++ b/jdk/src/macosx/native/sun/font/AWTFont.m
@@ -162,44 +162,6 @@
     return [sFontFamilyTable objectForKey:fontname];
 }
 
-static void addFont(CTFontUIFontType uiType, 
-                    NSMutableArray *allFonts,
-                    NSMutableDictionary* fontFamilyTable) {
-
-        CTFontRef font = CTFontCreateUIFontForLanguage(uiType, 0.0, NULL);
-        if (font == NULL) {
-            return;
-        }
-        CTFontDescriptorRef desc = CTFontCopyFontDescriptor(font);
-        if (desc == NULL) {
-            CFRelease(font);
-            return;
-        }
-        CFStringRef family = CTFontDescriptorCopyAttribute(desc, kCTFontFamilyNameAttribute);
-        if (family == NULL) {
-            CFRelease(desc);
-            CFRelease(font);
-            return;
-        }
-        CFStringRef name = CTFontDescriptorCopyAttribute(desc, kCTFontNameAttribute);
-        if (name == NULL) {
-            CFRelease(family);
-            CFRelease(desc);
-            CFRelease(font);
-            return;
-        }
-        [allFonts addObject:name];
-        [fontFamilyTable setObject:family forKey:name];
-#ifdef DEBUG
-        NSLog(@"name is : %@", (NSString*)name);
-        NSLog(@"family is : %@", (NSString*)family);
-#endif
-        CFRelease(family);
-        CFRelease(name);
-        CFRelease(desc);
-        CFRelease(font);
-}
- 
 static NSArray*
 GetFilteredFonts()
 {
@@ -234,16 +196,6 @@
             }
         }
 
-        /*
-         * JavaFX registers these fonts and so JDK needs to do so as well.
-         * If this isn't done we will have mis-matched rendering, since
-         * although these may include fonts that are enumerated normally
-         * they also demonstrably includes fonts that are not.
-         */
-        addFont(kCTFontUIFontSystem, allFonts, fontFamilyTable);
-        addFont(kCTFontUIFontEmphasizedSystem, allFonts, fontFamilyTable);
-        addFont(kCTFontUIFontUserFixedPitch, allFonts, fontFamilyTable);
-
         sFilteredFonts = allFonts;
         sFontFamilyTable = fontFamilyTable;
     }
diff --git a/jdk/src/macosx/native/sun/java2d/opengl/CGLLayer.h b/jdk/src/macosx/native/sun/java2d/opengl/CGLLayer.h
index 3d030e5..43724c0 100644
--- a/jdk/src/macosx/native/sun/java2d/opengl/CGLLayer.h
+++ b/jdk/src/macosx/native/sun/java2d/opengl/CGLLayer.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 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
@@ -31,7 +31,7 @@
 @interface CGLLayer : CAOpenGLLayer
 {
 @private
-    JNFWeakJObjectWrapper *javaLayer;
+    JNFJObjectWrapper *javaLayer;
 
     // intermediate buffer, used the RQ lock to synchronize
     GLuint textureID;
@@ -45,7 +45,7 @@
 #endif /* REMOTELAYER */
 }
 
-@property (nonatomic, retain) JNFWeakJObjectWrapper *javaLayer;
+@property (nonatomic, retain) JNFJObjectWrapper *javaLayer;
 @property (readwrite, assign) GLuint textureID;
 @property (readwrite, assign) GLenum target;
 @property (readwrite, assign) float textureWidth;
@@ -57,7 +57,7 @@
 @property (nonatomic, retain) NSObject<JRSRemoteLayer> *jrsRemoteLayer;
 #endif
 
-- (id) initWithJavaLayer:(JNFWeakJObjectWrapper *)javaLayer;
+- (id) initWithJavaLayer:(JNFJObjectWrapper *)javaLayer;
 - (void) blitTexture;
 @end
 
diff --git a/jdk/src/macosx/native/sun/java2d/opengl/CGLLayer.m b/jdk/src/macosx/native/sun/java2d/opengl/CGLLayer.m
index 87dcf1d..f300ea4 100644
--- a/jdk/src/macosx/native/sun/java2d/opengl/CGLLayer.m
+++ b/jdk/src/macosx/native/sun/java2d/opengl/CGLLayer.m
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 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
@@ -46,7 +46,7 @@
 @synthesize jrsRemoteLayer;
 #endif
 
-- (id) initWithJavaLayer:(JNFWeakJObjectWrapper *)layer;
+- (id) initWithJavaLayer:(JNFJObjectWrapper *)layer;
 {
 AWT_ASSERT_APPKIT_THREAD;
     // Initialize ourselves
@@ -133,15 +133,6 @@
 {
     AWT_ASSERT_APPKIT_THREAD;
 
-    JNIEnv *env = [ThreadUtilities getJNIEnv];
-    static JNF_CLASS_CACHE(jc_JavaLayer, "sun/java2d/opengl/CGLLayer");
-    static JNF_MEMBER_CACHE(jm_drawInCGLContext, jc_JavaLayer, "drawInCGLContext", "()V");
-
-    jobject javaLayerLocalRef = [self.javaLayer jObjectWithEnv:env];
-    if ((*env)->IsSameObject(env, javaLayerLocalRef, NULL)) {
-        return;
-    }
-
     // Set the current context to the one given to us.
     CGLSetCurrentContext(glContext);
 
@@ -150,7 +141,12 @@
     glClear(GL_COLOR_BUFFER_BIT);
 
     glViewport(0, 0, textureWidth, textureHeight);
+    
+    JNIEnv *env = [ThreadUtilities getJNIEnv];
+    static JNF_CLASS_CACHE(jc_JavaLayer, "sun/java2d/opengl/CGLLayer");
+    static JNF_MEMBER_CACHE(jm_drawInCGLContext, jc_JavaLayer, "drawInCGLContext", "()V");
 
+    jobject javaLayerLocalRef = [self.javaLayer jObjectWithEnv:env];
     JNFCallVoidMethod(env, javaLayerLocalRef, jm_drawInCGLContext);
     (*env)->DeleteLocalRef(env, javaLayerLocalRef);
 
@@ -175,7 +171,7 @@
 
 JNF_COCOA_ENTER(env);
 
-    JNFWeakJObjectWrapper *javaLayer = [JNFWeakJObjectWrapper wrapperWithJObject:obj withEnv:env];
+    JNFJObjectWrapper *javaLayer = [JNFJObjectWrapper wrapperWithJObject:obj withEnv:env];
 
     [ThreadUtilities performOnMainThreadWaiting:YES block:^(){
             AWT_ASSERT_APPKIT_THREAD;
diff --git a/jdk/src/macosx/native/sun/osxapp/NSApplicationAWT.m b/jdk/src/macosx/native/sun/osxapp/NSApplicationAWT.m
index d22983a..5df99a4 100644
--- a/jdk/src/macosx/native/sun/osxapp/NSApplicationAWT.m
+++ b/jdk/src/macosx/native/sun/osxapp/NSApplicationAWT.m
@@ -363,6 +363,7 @@
 {
     void (^copy)() = [block copy];
     NSInteger encode = (NSInteger) copy;
+    [copy retain];
     NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];    
     NSEvent* event = [NSEvent otherEventWithType: NSApplicationDefined
                                         location: NSMakePoint(0,0)
diff --git a/jdk/src/share/back/debugInit.c b/jdk/src/share/back/debugInit.c
index 3475397..25ffbff 100644
--- a/jdk/src/share/back/debugInit.c
+++ b/jdk/src/share/back/debugInit.c
@@ -1013,7 +1013,7 @@
 atexit_finish_logging(void)
 {
     /* Normal exit(0) (not _exit()) may only reach here */
-    finish_logging();  /* Only first call matters */
+    finish_logging(0);  /* Only first call matters */
 }
 
 static jboolean
@@ -1301,49 +1301,39 @@
 void
 debugInit_exit(jvmtiError error, const char *msg)
 {
-    enum exit_codes { EXIT_NO_ERRORS = 0, EXIT_JVMTI_ERROR = 1, EXIT_TRANSPORT_ERROR = 2 };
+    int exit_code = 0;
 
-    // Prepare to exit. Log error and finish logging
-    LOG_MISC(("Exiting with error %s(%d): %s", jvmtiErrorText(error), error,
-                                               ((msg == NULL) ? "" : msg)));
-
-    // coredump requested by command line. Keep JVMTI data dirty
-    if (error != JVMTI_ERROR_NONE && docoredump) {
-        LOG_MISC(("Dumping core as requested by command line"));
-        finish_logging();
-        abort();
-    }
-
-    finish_logging();
-
-    // Cleanup the JVMTI if we have one
-    if (gdata != NULL) {
-        gdata->vmDead = JNI_TRUE;
-        if (gdata->jvmti != NULL) {
-            // Dispose of jvmti (gdata->jvmti becomes NULL)
-            disposeEnvironment(gdata->jvmti);
+    /* Pick an error code */
+    if ( error != JVMTI_ERROR_NONE ) {
+        exit_code = 1;
+        if ( docoredump ) {
+            finish_logging(exit_code);
+            abort();
         }
     }
-
-    // We are here with no errors. Kill entire process and exit with zero exit code
-    if (error == JVMTI_ERROR_NONE) {
-        forceExit(EXIT_NO_ERRORS);
-        return;
+    if ( msg==NULL ) {
+        msg = "";
     }
 
-    // No transport initilized.
-    // As we don't have any details here exiting with separate exit code
-    if (error == AGENT_ERROR_TRANSPORT_INIT) {
-        forceExit(EXIT_TRANSPORT_ERROR);
-        return;
+    LOG_MISC(("Exiting with error %s(%d): %s", jvmtiErrorText(error), error, msg));
+
+    gdata->vmDead = JNI_TRUE;
+
+    /* Let's try and cleanup the JVMTI, if we even have one */
+    if ( gdata->jvmti != NULL ) {
+        /* Dispose of jvmti (gdata->jvmti becomes NULL) */
+        disposeEnvironment(gdata->jvmti);
     }
 
-    // We have JVMTI error. Call hotspot jni_FatalError handler
-    jniFatalError(NULL, msg, error, EXIT_JVMTI_ERROR);
+    /* Finish up logging. We reach here if JDWP is doing the exiting. */
+    finish_logging(exit_code);  /* Only first call matters */
 
-    // hotspot calls os:abort() so we should never reach code below,
-    // but guard against possible hotspot changes
+    /* Let's give the JNI a FatalError if non-exit 0, which is historic way */
+    if ( exit_code != 0 ) {
+        JNIEnv *env = NULL;
+        jniFatalError(env, msg, error, exit_code);
+    }
 
-    // Last chance to die, this kills the entire process.
-    forceExit(EXIT_JVMTI_ERROR);
+    /* Last chance to die, this kills the entire process. */
+    forceExit(exit_code);
 }
diff --git a/jdk/src/share/back/invoker.c b/jdk/src/share/back/invoker.c
index bd316dc..cd1cd2f 100644
--- a/jdk/src/share/back/invoker.c
+++ b/jdk/src/share/back/invoker.c
@@ -211,62 +211,6 @@
     return error;
 }
 
-/*
- * Delete saved global references - if any - for:
- * - a potentially thrown Exception
- * - a returned refernce/array value
- * See invoker_doInvoke() and invoke* methods where global references
- * are being saved.
- */
-static void
-deletePotentiallySavedGlobalRefs(JNIEnv *env, InvokeRequest *request)
-{
-    /* Delete potentially saved return value */
-    if ((request->invokeType == INVOKE_CONSTRUCTOR) ||
-        (returnTypeTag(request->methodSignature) == JDWP_TAG(OBJECT)) ||
-        (returnTypeTag(request->methodSignature) == JDWP_TAG(ARRAY))) {
-        if (request->returnValue.l != NULL) {
-            tossGlobalRef(env, &(request->returnValue.l));
-        }
-    }
-    /* Delete potentially saved exception */
-    if (request->exception != NULL) {
-        tossGlobalRef(env, &(request->exception));
-    }
-}
-
-/*
- * Delete global argument references from the request which got put there before a
- * invoke request was carried out. See fillInvokeRequest().
- */
-static void
-deleteGlobalArgumentRefs(JNIEnv *env, InvokeRequest *request)
-{
-    void *cursor;
-    jint argIndex = 0;
-    jvalue *argument = request->arguments;
-    jbyte argumentTag = firstArgumentTypeTag(request->methodSignature, &cursor);
-
-    if (request->clazz != NULL) {
-        tossGlobalRef(env, &(request->clazz));
-    }
-    if (request->instance != NULL) {
-        tossGlobalRef(env, &(request->instance));
-    }
-    /* Delete global argument references */
-    while (argIndex < request->argumentCount) {
-        if ((argumentTag == JDWP_TAG(OBJECT)) ||
-            (argumentTag == JDWP_TAG(ARRAY))) {
-            if (argument->l != NULL) {
-                tossGlobalRef(env, &(argument->l));
-            }
-        }
-        argument++;
-        argIndex++;
-        argumentTag = nextArgumentTypeTag(&cursor);
-    }
-}
-
 static jvmtiError
 fillInvokeRequest(JNIEnv *env, InvokeRequest *request,
                   jbyte invokeType, jbyte options, jint id,
@@ -376,8 +320,6 @@
 invokeConstructor(JNIEnv *env, InvokeRequest *request)
 {
     jobject object;
-
-    JDI_ASSERT_MSG(request->clazz, "Request clazz null");
     object = JNI_FUNC_PTR(env,NewObjectA)(env, request->clazz,
                                      request->method,
                                      request->arguments);
@@ -394,7 +336,6 @@
         case JDWP_TAG(OBJECT):
         case JDWP_TAG(ARRAY): {
             jobject object;
-            JDI_ASSERT_MSG(request->clazz, "Request clazz null");
             object = JNI_FUNC_PTR(env,CallStaticObjectMethodA)(env,
                                        request->clazz,
                                        request->method,
@@ -483,7 +424,6 @@
         case JDWP_TAG(OBJECT):
         case JDWP_TAG(ARRAY): {
             jobject object;
-            JDI_ASSERT_MSG(request->instance, "Request instance null");
             object = JNI_FUNC_PTR(env,CallObjectMethodA)(env,
                                  request->instance,
                                  request->method,
@@ -571,8 +511,6 @@
         case JDWP_TAG(OBJECT):
         case JDWP_TAG(ARRAY): {
             jobject object;
-            JDI_ASSERT_MSG(request->clazz, "Request clazz null");
-            JDI_ASSERT_MSG(request->instance, "Request instance null");
             object = JNI_FUNC_PTR(env,CallNonvirtualObjectMethodA)(env,
                                            request->instance,
                                            request->clazz,
@@ -669,8 +607,6 @@
     JNIEnv *env;
     jboolean startNow;
     InvokeRequest *request;
-    jbyte options;
-    jbyte invokeType;
 
     JDI_ASSERT(thread);
 
@@ -687,9 +623,6 @@
     if (startNow) {
         request->started = JNI_TRUE;
     }
-    options = request->options;
-    invokeType = request->invokeType;
-
     debugMonitorExit(invokerLock);
 
     if (!startNow) {
@@ -704,7 +637,7 @@
 
         JNI_FUNC_PTR(env,ExceptionClear)(env);
 
-        switch (invokeType) {
+        switch (request->invokeType) {
             case INVOKE_CONSTRUCTOR:
                 invokeConstructor(env, request);
                 break;
@@ -712,7 +645,7 @@
                 invokeStatic(env, request);
                 break;
             case INVOKE_INSTANCE:
-                if (options & JDWP_INVOKE_OPTIONS(NONVIRTUAL) ) {
+                if (request->options & JDWP_INVOKE_OPTIONS(NONVIRTUAL) ) {
                     invokeNonvirtual(env, request);
                 } else {
                     invokeVirtual(env, request);
@@ -790,23 +723,12 @@
     }
 
     /*
-     * At this time, there's no need to retain global references on
-     * arguments since the reply is processed. No one will deal with
-     * this request ID anymore, so we must call deleteGlobalArgumentRefs().
-     *
-     * We cannot delete saved exception or return value references
-     * since otherwise a deleted handle would escape when writing
-     * the response to the stream. Instead, we clean those refs up
-     * after writing the respone.
-     */
-    deleteGlobalArgumentRefs(env, request);
-
-    /*
      * Give up the lock before I/O operation
      */
     debugMonitorExit(invokerLock);
     eventHandler_unlock();
 
+
     if (!detached) {
         outStream_initReply(&out, id);
         (void)outStream_writeValue(env, &out, tag, returnValue);
@@ -814,16 +736,6 @@
         (void)outStream_writeObjectRef(env, &out, exc);
         outStream_sendReply(&out);
     }
-
-    /*
-     * Delete potentially saved global references of return value
-     * and exception
-     */
-    eventHandler_lock(); // for proper lock order
-    debugMonitorEnter(invokerLock);
-    deletePotentiallySavedGlobalRefs(env, request);
-    debugMonitorExit(invokerLock);
-    eventHandler_unlock();
 }
 
 jboolean
diff --git a/jdk/src/share/back/log_messages.c b/jdk/src/share/back/log_messages.c
index 32bea29..de8b69d 100644
--- a/jdk/src/share/back/log_messages.c
+++ b/jdk/src/share/back/log_messages.c
@@ -230,7 +230,7 @@
 
 /* Finish up logging, flush output to the logfile. */
 void
-finish_logging()
+finish_logging(int exit_code)
 {
 #ifdef JDWP_LOGGING
     MUTEX_LOCK(my_mutex);
diff --git a/jdk/src/share/back/log_messages.h b/jdk/src/share/back/log_messages.h
index 129fab6..0a442e9 100644
--- a/jdk/src/share/back/log_messages.h
+++ b/jdk/src/share/back/log_messages.h
@@ -29,7 +29,7 @@
 /* LOG: Must be called like:  LOG_category(("anything")) or LOG_category((format,args)) */
 
 void setup_logging(const char *, unsigned);
-void finish_logging();
+void finish_logging(int);
 
 #define LOG_NULL ((void)0)
 
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/AESCrypt.java b/jdk/src/share/classes/com/sun/crypto/provider/AESCrypt.java
index c85f715..12ffe89 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/AESCrypt.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/AESCrypt.java
@@ -52,7 +52,7 @@
     private boolean ROUNDS_14 = false;
 
     /** Session and Sub keys */
-    private int[][] sessionK = null;
+    private Object[] sessionK = null;
     private int[] K = null;
 
     /** Cipher encryption/decryption key */
@@ -95,7 +95,7 @@
         }
 
         // set sub key to the corresponding session Key
-        this.K = sessionK[(decrypting? 1:0)];
+        this.K = (int[]) sessionK[(decrypting? 1:0)];
     }
 
     /**
@@ -660,7 +660,7 @@
         limit = ROUNDS*4;
 
         // store the expanded sub keys into 'sessionK'
-        sessionK = new int[][] { expandedKe, expandedKd };
+        sessionK = new Object[] { expandedKe, expandedKd };
     }
 
 
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/CipherBlockChaining.java b/jdk/src/share/classes/com/sun/crypto/provider/CipherBlockChaining.java
index 5154788..51d95c1 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/CipherBlockChaining.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/CipherBlockChaining.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -26,8 +26,6 @@
 package com.sun.crypto.provider;
 
 import java.security.InvalidKeyException;
-import java.security.ProviderException;
-
 
 /**
  * This class represents ciphers in cipher block chaining (CBC) mode.
@@ -124,31 +122,31 @@
      *
      * <p>The input plain text <code>plain</code>, starting at
      * <code>plainOffset</code> and ending at
-     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
+     * <code>(plainOffset + len - 1)</code>, is encrypted.
      * The result is stored in <code>cipher</code>, starting at
      * <code>cipherOffset</code>.
      *
+     * <p>It is the application's responsibility to make sure that
+     * <code>plainLen</code> is a multiple of the embedded cipher's block size,
+     * as any excess bytes are ignored.
+     *
      * @param plain the buffer with the input data to be encrypted
      * @param plainOffset the offset in <code>plain</code>
      * @param plainLen the length of the input data
      * @param cipher the buffer for the result
      * @param cipherOffset the offset in <code>cipher</code>
-     * @exception ProviderException if <code>len</code> is not
-     * a multiple of the block size
      * @return the length of the encrypted data
      */
     int encrypt(byte[] plain, int plainOffset, int plainLen,
                 byte[] cipher, int cipherOffset)
     {
-        if ((plainLen % blockSize) != 0) {
-            throw new ProviderException("Internal error in input buffering");
-        }
+        int i;
         int endIndex = plainOffset + plainLen;
 
         for (; plainOffset < endIndex;
              plainOffset+=blockSize, cipherOffset += blockSize) {
-            for (int i = 0; i < blockSize; i++) {
-                k[i] = (byte)(plain[i + plainOffset] ^ r[i]);
+            for (i=0; i<blockSize; i++) {
+                k[i] = (byte)(plain[i+plainOffset] ^ r[i]);
             }
             embeddedCipher.encryptBlock(k, 0, cipher, cipherOffset);
             System.arraycopy(cipher, cipherOffset, r, 0, blockSize);
@@ -161,10 +159,14 @@
      *
      * <p>The input cipher text <code>cipher</code>, starting at
      * <code>cipherOffset</code> and ending at
-     * <code>(cipherOffset + cipherLen - 1)</code>, is decrypted.
+     * <code>(cipherOffset + len - 1)</code>, is decrypted.
      * The result is stored in <code>plain</code>, starting at
      * <code>plainOffset</code>.
      *
+     * <p>It is the application's responsibility to make sure that
+     * <code>cipherLen</code> is a multiple of the embedded cipher's block
+     * size, as any excess bytes are ignored.
+     *
      * <p>It is also the application's responsibility to make sure that
      * <code>init</code> has been called before this method is called.
      * (This check is omitted here, to avoid double checking.)
@@ -174,23 +176,23 @@
      * @param cipherLen the length of the input data
      * @param plain the buffer for the result
      * @param plainOffset the offset in <code>plain</code>
-     * @exception ProviderException if <code>len</code> is not
-     * a multiple of the block size
      * @return the length of the decrypted data
+     *
+     * @exception IllegalBlockSizeException if input data whose length does
+     * not correspond to the embedded cipher's block size is passed to the
+     * embedded cipher
      */
     int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
                 byte[] plain, int plainOffset)
     {
-        if ((cipherLen % blockSize) != 0) {
-            throw new ProviderException("Internal error in input buffering");
-        }
+        int i;
         int endIndex = cipherOffset + cipherLen;
 
         for (; cipherOffset < endIndex;
              cipherOffset += blockSize, plainOffset += blockSize) {
             embeddedCipher.decryptBlock(cipher, cipherOffset, k, 0);
-            for (int i = 0; i < blockSize; i++) {
-                plain[i + plainOffset] = (byte)(k[i] ^ r[i]);
+            for (i = 0; i < blockSize; i++) {
+                plain[i+plainOffset] = (byte)(k[i] ^ r[i]);
             }
             System.arraycopy(cipher, cipherOffset, r, 0, blockSize);
         }
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/CipherCore.java b/jdk/src/share/classes/com/sun/crypto/provider/CipherCore.java
index 592ec41..79f66cd 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/CipherCore.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/CipherCore.java
@@ -717,7 +717,7 @@
             len -= blockSize;
         }
         // do not count the trailing bytes which do not make up a unit
-        len = (len > 0 ? (len - (len % unitBytes)) : 0);
+        len = (len > 0 ? (len - (len%unitBytes)) : 0);
 
         // check output buffer capacity
         if ((output == null) ||
@@ -729,15 +729,6 @@
 
         int outLen = 0;
         if (len != 0) { // there is some work to do
-            if ((input == output)
-                 && (outputOffset < (inputOffset + inputLen))
-                 && (inputOffset < (outputOffset + buffer.length))) {
-                // copy 'input' out to avoid its content being
-                // overwritten prematurely.
-                input = Arrays.copyOfRange(input, inputOffset,
-                    inputOffset + inputLen);
-                inputOffset = 0;
-            }
             if (len <= buffered) {
                 // all to-be-processed data are from 'buffer'
                 if (decrypting) {
@@ -750,40 +741,37 @@
                     System.arraycopy(buffer, len, buffer, 0, buffered);
                 }
             } else { // len > buffered
-                int inputConsumed = len - buffered;
-                int temp;
-                if (buffered > 0) {
-                    int bufferCapacity = buffer.length - buffered;
-                    if (bufferCapacity != 0) {
-                        temp = Math.min(bufferCapacity, inputConsumed);
-                        if (unitBytes != blockSize) {
-                            temp -= ((buffered + temp) % unitBytes);
-                        }
-                        System.arraycopy(input, inputOffset, buffer, buffered, temp);
-                        inputOffset += temp;
-                        inputConsumed -= temp;
-                        inputLen -= temp;
-                        buffered += temp;
-                    }
-                    // process 'buffer'
+                if ((input != output) && (buffered == 0)) {
+                    // all to-be-processed data are from 'input'
+                    // however, note that if 'input' and 'output' are the same,
+                    // then they can't be passed directly to the underlying cipher
+                    // engine operations as data may be overwritten before they
+                    // are read.
                     if (decrypting) {
-                         outLen = cipher.decrypt(buffer, 0, buffered, output, outputOffset);
+                        outLen = cipher.decrypt(input, inputOffset, len, output, outputOffset);
                     } else {
-                         outLen = cipher.encrypt(buffer, 0, buffered, output, outputOffset);
+                        outLen = cipher.encrypt(input, inputOffset, len, output, outputOffset);
                     }
-                    outputOffset += outLen;
-                    buffered = 0;
-                }
-                if (inputConsumed > 0) { // still has input to process
+                    inputOffset += len;
+                    inputLen -= len;
+                } else {
+                    // assemble the data using both 'buffer' and 'input'
+                    byte[] in = new byte[len];
+                    int inConsumed = len - buffered;
+                    if (buffered != 0) {
+                        System.arraycopy(buffer, 0, in, 0, buffered);
+                        buffered = 0;
+                    }
+                    if (inConsumed != 0) {
+                        System.arraycopy(input, inputOffset, in, len - inConsumed, inConsumed);
+                        inputOffset += inConsumed;
+                        inputLen -= inConsumed;
+                    }
                     if (decrypting) {
-                        outLen += cipher.decrypt(input, inputOffset, inputConsumed,
-                            output, outputOffset);
+                        outLen = cipher.decrypt(in, 0, len, output, outputOffset);
                     } else {
-                        outLen += cipher.encrypt(input, inputOffset, inputConsumed,
-                            output, outputOffset);
+                        outLen = cipher.encrypt(in, 0, len, output, outputOffset);
                     }
-                    inputOffset += inputConsumed;
-                    inputLen -= inputConsumed;
                 }
             }
             // Let's keep track of how many bytes are needed to make
@@ -946,10 +934,8 @@
         byte[] finalBuf = input;
         int finalOffset = inputOffset;
         int finalBufLen = inputLen;
-        if ((buffered != 0) || (!decrypting && padding != null) ||
-            ((input == output)
-              && (outputOffset < (inputOffset + inputLen))
-              && (inputOffset < (outputOffset + buffer.length)))) {
+        if ((input == output) || (buffered != 0) ||
+            (!decrypting && padding != null)) {
             if (decrypting || padding == null) {
                 paddingLen = 0;
             }
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/CipherFeedback.java b/jdk/src/share/classes/com/sun/crypto/provider/CipherFeedback.java
index 84b527e..f8e6115 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/CipherFeedback.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/CipherFeedback.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -26,7 +26,6 @@
 package com.sun.crypto.provider;
 
 import java.security.InvalidKeyException;
-import java.security.ProviderException;
 
 /**
  * This class represents ciphers in cipher-feedback (CFB) mode.
@@ -134,72 +133,66 @@
      *
      * <p>The input plain text <code>plain</code>, starting at
      * <code>plainOffset</code> and ending at
-     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
+     * <code>(plainOffset + len - 1)</code>, is encrypted.
      * The result is stored in <code>cipher</code>, starting at
      * <code>cipherOffset</code>.
      *
+     * <p>It is the application's responsibility to make sure that
+     * <code>plainLen</code> is a multiple of the stream unit size
+     * <code>numBytes</code>, as any excess bytes are ignored.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
+     *
      * @param plain the buffer with the input data to be encrypted
      * @param plainOffset the offset in <code>plain</code>
      * @param plainLen the length of the input data
      * @param cipher the buffer for the result
      * @param cipherOffset the offset in <code>cipher</code>
-     * @exception ProviderException if <code>plainLen</code> is not
-     * a multiple of the <code>numBytes</code>
      * @return the length of the encrypted data
      */
     int encrypt(byte[] plain, int plainOffset, int plainLen,
-                byte[] cipher, int cipherOffset) {
-        if ((plainLen % numBytes) != 0) {
-            throw new ProviderException("Internal error in input buffering");
-        }
-
-        int nShift = blockSize - numBytes;
+                byte[] cipher, int cipherOffset)
+    {
+        int i, len;
+        len = blockSize - numBytes;
         int loopCount = plainLen / numBytes;
-
-        for (; loopCount > 0 ;
-             plainOffset += numBytes, cipherOffset += numBytes,
-             loopCount--) {
-            embeddedCipher.encryptBlock(register, 0, k, 0);
-            if (nShift != 0) {
-                System.arraycopy(register, numBytes, register, 0, nShift);
-            }
-            for (int i = 0; i < numBytes; i++) {
-                register[nShift + i] = cipher[i + cipherOffset] =
-                        (byte)(k[i] ^ plain[i + plainOffset]);
-            }
-        }
-        return plainLen;
-    }
-
-    /**
-     * Performs the last encryption operation.
-     *
-     * <p>The input plain text <code>plain</code>, starting at
-     * <code>plainOffset</code> and ending at
-     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
-     * The result is stored in <code>cipher</code>, starting at
-     * <code>cipherOffset</code>.
-     *
-     * @param plain the buffer with the input data to be encrypted
-     * @param plainOffset the offset in <code>plain</code>
-     * @param plainLen the length of the input data
-     * @param cipher the buffer for the result
-     * @param cipherOffset the offset in <code>cipher</code>
-     * @return the number of bytes placed into <code>cipher</code>
-     */
-    int encryptFinal(byte[] plain, int plainOffset, int plainLen,
-                     byte[] cipher, int cipherOffset) {
-
         int oddBytes = plainLen % numBytes;
-        int len = encrypt(plain, plainOffset, (plainLen - oddBytes),
-                          cipher, cipherOffset);
-        plainOffset += len;
-        cipherOffset += len;
-        if (oddBytes != 0) {
-            embeddedCipher.encryptBlock(register, 0, k, 0);
-            for (int i = 0; i < oddBytes; i++) {
-                 cipher[i + cipherOffset] =
-                    (byte)(k[i] ^ plain[i + plainOffset]);
+
+        if (len == 0) {
+            for (; loopCount > 0 ;
+                 plainOffset += numBytes, cipherOffset += numBytes,
+                 loopCount--) {
+                embeddedCipher.encryptBlock(register, 0, k, 0);
+                for (i = 0; i < blockSize; i++)
+                    register[i] = cipher[i+cipherOffset] =
+                        (byte)(k[i] ^ plain[i+plainOffset]);
+            }
+            if (oddBytes > 0) {
+                embeddedCipher.encryptBlock(register, 0, k, 0);
+                for (i=0; i<oddBytes; i++)
+                    register[i] = cipher[i+cipherOffset] =
+                        (byte)(k[i] ^ plain[i+plainOffset]);
+            }
+        } else {
+            for (; loopCount > 0 ;
+                 plainOffset += numBytes, cipherOffset += numBytes,
+                 loopCount--) {
+                embeddedCipher.encryptBlock(register, 0, k, 0);
+                System.arraycopy(register, numBytes, register, 0, len);
+                for (i=0; i<numBytes; i++)
+                    register[i+len] = cipher[i+cipherOffset] =
+                        (byte)(k[i] ^ plain[i+plainOffset]);
+
+            }
+            if (oddBytes != 0) {
+                embeddedCipher.encryptBlock(register, 0, k, 0);
+                System.arraycopy(register, numBytes, register, 0, len);
+                for (i=0; i<oddBytes; i++) {
+                    register[i+len] = cipher[i+cipherOffset] =
+                        (byte)(k[i] ^ plain[i+plainOffset]);
+                }
             }
         }
         return plainLen;
@@ -210,73 +203,72 @@
      *
      * <p>The input cipher text <code>cipher</code>, starting at
      * <code>cipherOffset</code> and ending at
-     * <code>(cipherOffset + cipherLen - 1)</code>, is decrypted.
+     * <code>(cipherOffset + len - 1)</code>, is decrypted.
      * The result is stored in <code>plain</code>, starting at
      * <code>plainOffset</code>.
      *
+     * <p>It is the application's responsibility to make sure that
+     * <code>cipherLen</code> is a multiple of the stream unit size
+     * <code>numBytes</code>, as any excess bytes are ignored.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
+     *
      * @param cipher the buffer with the input data to be decrypted
      * @param cipherOffset the offset in <code>cipherOffset</code>
      * @param cipherLen the length of the input data
      * @param plain the buffer for the result
      * @param plainOffset the offset in <code>plain</code>
-     * @exception ProviderException if <code>cipherLen</code> is not
-     * a multiple of the <code>numBytes</code>
      * @return the length of the decrypted data
      */
     int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
-                byte[] plain, int plainOffset) {
-        if ((cipherLen % numBytes) != 0) {
-            throw new ProviderException("Internal error in input buffering");
-        }
-
-        int nShift = blockSize - numBytes;
+                byte[] plain, int plainOffset)
+    {
+        int i, len;
+        len = blockSize - numBytes;
         int loopCount = cipherLen / numBytes;
-
-        for (; loopCount > 0;
-             plainOffset += numBytes, cipherOffset += numBytes,
-             loopCount--) {
-            embeddedCipher.encryptBlock(register, 0, k, 0);
-            if (nShift != 0) {
-                System.arraycopy(register, numBytes, register, 0, nShift);
-            }
-            for (int i = 0; i < numBytes; i++) {
-                register[i + nShift] = cipher[i + cipherOffset];
-                plain[i + plainOffset]
-                    = (byte)(cipher[i + cipherOffset] ^ k[i]);
-            }
-        }
-        return cipherLen;
-    }
-
-    /**
-     * Performs the last decryption operation.
-     *
-     * <p>The input cipher text <code>cipher</code>, starting at
-     * <code>cipherOffset</code> and ending at
-     * <code>(cipherOffset + cipherLen - 1)</code>, is decrypted.
-     * The result is stored in <code>plain</code>, starting at
-     * <code>plainOffset</code>.
-     *
-     * @param cipher the buffer with the input data to be decrypted
-     * @param cipherOffset the offset in <code>cipherOffset</code>
-     * @param cipherLen the length of the input data
-     * @param plain the buffer for the result
-     * @param plainOffset the offset in <code>plain</code>
-     * @return the length of the decrypted data
-     */
-    int decryptFinal(byte[] cipher, int cipherOffset, int cipherLen,
-                byte[] plain, int plainOffset) {
-
         int oddBytes = cipherLen % numBytes;
-        int len = decrypt(cipher, cipherOffset, (cipherLen - oddBytes),
-                          plain, plainOffset);
-        cipherOffset += len;
-        plainOffset += len;
-        if (oddBytes != 0) {
-            embeddedCipher.encryptBlock(register, 0, k, 0);
-            for (int i = 0; i < oddBytes; i++) {
-                plain[i + plainOffset]
-                    = (byte)(cipher[i + cipherOffset] ^ k[i]);
+
+        if (len == 0) {
+            for (; loopCount > 0;
+                 plainOffset += numBytes, cipherOffset += numBytes,
+                 loopCount--) {
+                embeddedCipher.encryptBlock(register, 0, k, 0);
+                for (i = 0; i < blockSize; i++) {
+                    register[i] = cipher[i+cipherOffset];
+                    plain[i+plainOffset]
+                        = (byte)(cipher[i+cipherOffset] ^ k[i]);
+                }
+            }
+            if (oddBytes > 0) {
+                embeddedCipher.encryptBlock(register, 0, k, 0);
+                for (i=0; i<oddBytes; i++) {
+                    register[i] = cipher[i+cipherOffset];
+                    plain[i+plainOffset]
+                        = (byte)(cipher[i+cipherOffset] ^ k[i]);
+                }
+            }
+        } else {
+            for (; loopCount > 0;
+                 plainOffset += numBytes, cipherOffset += numBytes,
+                 loopCount--) {
+                embeddedCipher.encryptBlock(register, 0, k, 0);
+                System.arraycopy(register, numBytes, register, 0, len);
+                for (i=0; i<numBytes; i++) {
+                    register[i+len] = cipher[i+cipherOffset];
+                    plain[i+plainOffset]
+                        = (byte)(cipher[i+cipherOffset] ^ k[i]);
+                }
+            }
+            if (oddBytes != 0) {
+                embeddedCipher.encryptBlock(register, 0, k, 0);
+                System.arraycopy(register, numBytes, register, 0, len);
+                for (i=0; i<oddBytes; i++) {
+                    register[i+len] = cipher[i+cipherOffset];
+                    plain[i+plainOffset]
+                        = (byte)(cipher[i+cipherOffset] ^ k[i]);
+                }
             }
         }
         return cipherLen;
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/CounterMode.java b/jdk/src/share/classes/com/sun/crypto/provider/CounterMode.java
index af52bd7..438998e 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/CounterMode.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/CounterMode.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 201313, Oracle and/or its affiliates. All rights reserved.
  * 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,6 @@
 
 import java.security.InvalidKeyException;
 
-
 /**
  * This class represents ciphers in counter (CTR) mode.
  *
@@ -137,6 +136,14 @@
      * The result is stored in <code>cipher</code>, starting at
      * <code>cipherOffset</code>.
      *
+     * <p>It is the application's responsibility to make sure that
+     * <code>plainLen</code> is a multiple of the embedded cipher's block size,
+     * as any excess bytes are ignored.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
+     *
      * @param in the buffer with the input data to be encrypted
      * @param inOffset the offset in <code>plain</code>
      * @param len the length of the input data
@@ -148,7 +155,30 @@
         return crypt(in, inOff, len, out, outOff);
     }
 
-    // CTR encrypt and decrypt are identical
+    /**
+     * Performs decryption operation.
+     *
+     * <p>The input cipher text <code>cipher</code>, starting at
+     * <code>cipherOffset</code> and ending at
+     * <code>(cipherOffset + len - 1)</code>, is decrypted.
+     * The result is stored in <code>plain</code>, starting at
+     * <code>plainOffset</code>.
+     *
+     * <p>It is the application's responsibility to make sure that
+     * <code>cipherLen</code> is a multiple of the embedded cipher's block
+     * size, as any excess bytes are ignored.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
+     *
+     * @param in the buffer with the input data to be decrypted
+     * @param inOff the offset in <code>cipherOffset</code>
+     * @param len the length of the input data
+     * @param out the buffer for the result
+     * @param outOff the offset in <code>plain</code>
+     * @return the length of the decrypted data
+     */
     int decrypt(byte[] in, int inOff, int len, byte[] out, int outOff) {
         return crypt(in, inOff, len, out, outOff);
     }
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java
index bd2ba6f..c71d6ab 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DHKeyPairGenerator.java
@@ -71,17 +71,6 @@
         initialize(1024, null);
     }
 
-    private static void checkKeySize(int keysize)
-            throws InvalidParameterException {
-
-        if ((keysize < 512) || (keysize > 2048) || ((keysize & 0x3F) != 0)) {
-            throw new InvalidParameterException(
-                    "DH key size must be multiple of 64, and can only range " +
-                    "from 512 to 2048 (inclusive). " +
-                    "The specific key size " + keysize + " is not supported");
-        }
-    }
-
     /**
      * Initializes this key pair generator for a certain keysize and source of
      * randomness.
@@ -91,8 +80,12 @@
      * @param random the source of randomness
      */
     public void initialize(int keysize, SecureRandom random) {
-        checkKeySize(keysize);
-
+        if ((keysize < 512) || (keysize > 2048) || (keysize % 64 != 0)) {
+            throw new InvalidParameterException("Keysize must be multiple "
+                                                + "of 64, and can only range "
+                                                + "from 512 to 2048 "
+                                                + "(inclusive)");
+        }
         this.pSize = keysize;
         this.lSize = 0;
         this.random = random;
@@ -122,10 +115,11 @@
 
         params = (DHParameterSpec)algParams;
         pSize = params.getP().bitLength();
-        try {
-            checkKeySize(pSize);
-        } catch (InvalidParameterException ipe) {
-            throw new InvalidAlgorithmParameterException(ipe.getMessage());
+        if ((pSize < 512) || (pSize > 2048) ||
+            (pSize % 64 != 0)) {
+            throw new InvalidAlgorithmParameterException
+                ("Prime size must be multiple of 64, and can only range "
+                 + "from 512 to 2048 (inclusive)");
         }
 
         // exponent size is optional, could be 0
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/DHParameterGenerator.java b/jdk/src/share/classes/com/sun/crypto/provider/DHParameterGenerator.java
index 92d4f6f..a12e945 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/DHParameterGenerator.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/DHParameterGenerator.java
@@ -59,13 +59,12 @@
     private SecureRandom random = null;
 
     private static void checkKeySize(int keysize)
-            throws InvalidParameterException {
-            if ((keysize != 2048) &&
+        throws InvalidAlgorithmParameterException {
+        if ((keysize != 2048) &&
             ((keysize < 512) || (keysize > 1024) || (keysize % 64 != 0))) {
-            throw new InvalidParameterException(
-                    "DH key size must be multiple of 64 and range " +
-                    "from 512 to 1024 (inclusive), or 2048. " +
-                    "The specific key size " + keysize + " is not supported");
+            throw new InvalidAlgorithmParameterException(
+                "Keysize must be multiple of 64 ranging from "
+                + "512 to 1024 (inclusive), or 2048");
         }
     }
 
@@ -79,7 +78,11 @@
      */
     protected void engineInit(int keysize, SecureRandom random) {
         // Re-uses DSA parameters and thus have the same range
-        checkKeySize(keysize);
+        try {
+            checkKeySize(keysize);
+        } catch (InvalidAlgorithmParameterException ex) {
+            throw new InvalidParameterException(ex.getMessage());
+        }
         this.primeSize = keysize;
         this.random = random;
     }
@@ -108,11 +111,7 @@
         primeSize = dhParamSpec.getPrimeSize();
 
         // Re-uses DSA parameters and thus have the same range
-        try {
-            checkKeySize(primeSize);
-        } catch (InvalidParameterException ipe) {
-            throw new InvalidAlgorithmParameterException(ipe.getMessage());
-        }
+        checkKeySize(primeSize);
 
         exponentSize = dhParamSpec.getExponentSize();
         if (exponentSize <= 0) {
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/ElectronicCodeBook.java b/jdk/src/share/classes/com/sun/crypto/provider/ElectronicCodeBook.java
index 334e424..a407b6a 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/ElectronicCodeBook.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/ElectronicCodeBook.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -26,7 +26,6 @@
 package com.sun.crypto.provider;
 
 import java.security.InvalidKeyException;
-import java.security.ProviderException;
 
 /**
  * This class represents ciphers in electronic codebook (ECB) mode.
@@ -97,24 +96,28 @@
     /**
      * Performs encryption operation.
      *
-     * <p>The input plain text <code>in</code>, starting at
-     * <code>inOff</code> and ending at * <code>(inOff + len - 1)</code>,
-     * is encrypted. The result is stored in <code>out</code>, starting at
-     * <code>outOff</code>.
+     * <p>The input plain text <code>plain</code>, starting at
+     * <code>plainOffset</code> and ending at
+     * <code>(plainOffset + len - 1)</code>, is encrypted.
+     * The result is stored in <code>cipher</code>, starting at
+     * <code>cipherOffset</code>.
+     *
+     * <p>It is the application's responsibility to make sure that
+     * <code>plainLen</code> is a multiple of the embedded cipher's block size,
+     * as any excess bytes are ignored.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
      *
      * @param in the buffer with the input data to be encrypted
-     * @param inOff the offset in <code>plain</code>
+     * @param inOffset the offset in <code>plain</code>
      * @param len the length of the input data
      * @param out the buffer for the result
      * @param outOff the offset in <code>cipher</code>
-     * @exception ProviderException if <code>len</code> is not
-     * a multiple of the block size
      * @return the length of the encrypted data
      */
     int encrypt(byte[] in, int inOff, int len, byte[] out, int outOff) {
-        if ((len % blockSize) != 0) {
-             throw new ProviderException("Internal error in input buffering");
-        }
         for (int i = len; i >= blockSize; i -= blockSize) {
             embeddedCipher.encryptBlock(in, inOff, out, outOff);
             inOff += blockSize;
@@ -126,24 +129,28 @@
     /**
      * Performs decryption operation.
      *
-     * <p>The input cipher text <code>in</code>, starting at
-     * <code>inOff</code> and ending at * <code>(inOff + len - 1)</code>,
-     * is decrypted.The result is stored in <code>out</code>, starting at
-     * <code>outOff</code>.
+     * <p>The input cipher text <code>cipher</code>, starting at
+     * <code>cipherOffset</code> and ending at
+     * <code>(cipherOffset + len - 1)</code>, is decrypted.
+     * The result is stored in <code>plain</code>, starting at
+     * <code>plainOffset</code>.
+     *
+     * <p>It is the application's responsibility to make sure that
+     * <code>cipherLen</code> is a multiple of the embedded cipher's block
+     * size, as any excess bytes are ignored.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
      *
      * @param in the buffer with the input data to be decrypted
      * @param inOff the offset in <code>cipherOffset</code>
      * @param len the length of the input data
      * @param out the buffer for the result
      * @param outOff the offset in <code>plain</code>
-     * @exception ProviderException if <code>len</code> is not
-     * a multiple of the block size
      * @return the length of the decrypted data
      */
     int decrypt(byte[] in, int inOff, int len, byte[] out, int outOff) {
-        if ((len % blockSize) != 0) {
-             throw new ProviderException("Internal error in input buffering");
-        }
         for (int i = len; i >= blockSize; i -= blockSize) {
             embeddedCipher.decryptBlock(in, inOff, out, outOff);
             inOff += blockSize;
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/GaloisCounterMode.java b/jdk/src/share/classes/com/sun/crypto/provider/GaloisCounterMode.java
index 4cb76ff..e4edbf0 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/GaloisCounterMode.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/GaloisCounterMode.java
@@ -403,21 +403,23 @@
      * and ending at <code>(inOff + len - 1)</code>, is encrypted. The result
      * is stored in <code>out</code>, starting at <code>outOfs</code>.
      *
+     * <p>It is the application's responsibility to make sure that
+     * <code>len</code> is a multiple of the embedded cipher's block size,
+     * otherwise, a ProviderException will be thrown.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
+     *
      * @param in the buffer with the input data to be encrypted
      * @param inOfs the offset in <code>in</code>
      * @param len the length of the input data
      * @param out the buffer for the result
      * @param outOfs the offset in <code>out</code>
-     * @exception ProviderException if <code>len</code> is not
-     * a multiple of the block size
-     * @return the number of bytes placed into the <code>out</code> buffer
      */
     int encrypt(byte[] in, int inOfs, int len, byte[] out, int outOfs) {
         checkDataLength(processed, len);
 
-        if ((len % blockSize) != 0) {
-             throw new ProviderException("Internal error in input buffering");
-        }
         processAAD();
         if (len > 0) {
             gctrPAndC.update(in, inOfs, len, out, outOfs);
@@ -430,6 +432,9 @@
     /**
      * Performs encryption operation for the last time.
      *
+     * <p>NOTE: <code>len</code> may not be multiple of the embedded
+     * cipher's block size for this call.
+     *
      * @param in the input buffer with the data to be encrypted
      * @param inOfs the offset in <code>in</code>
      * @param len the length of the input data
@@ -474,21 +479,23 @@
      * is decrypted. The result is stored in <code>out</code>, starting at
      * <code>outOfs</code>.
      *
+     * <p>It is the application's responsibility to make sure that
+     * <code>len</code> is a multiple of the embedded cipher's block
+     * size, as any excess bytes are ignored.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
+     *
      * @param in the buffer with the input data to be decrypted
      * @param inOfs the offset in <code>in</code>
      * @param len the length of the input data
      * @param out the buffer for the result
      * @param outOfs the offset in <code>out</code>
-     * @exception ProviderException if <code>len</code> is not
-     * a multiple of the block size
-     * @return the number of bytes placed into the <code>out</code> buffer
      */
     int decrypt(byte[] in, int inOfs, int len, byte[] out, int outOfs) {
         checkDataLength(ibuffer.size(), len);
 
-        if ((len % blockSize) != 0) {
-             throw new ProviderException("Internal error in input buffering");
-        }
         processAAD();
 
         if (len > 0) {
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/JceKeyStore.java b/jdk/src/share/classes/com/sun/crypto/provider/JceKeyStore.java
index 5ec36fd..cbbc54e 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/JceKeyStore.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/JceKeyStore.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 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
@@ -864,9 +864,7 @@
                         if (computed[i] != actual[i]) {
                             throw new IOException(
                                 "Keystore was tampered with, or "
-                                + "password was incorrect",
-                                    new UnrecoverableKeyException(
-                                            "Password verification failed"));
+                                + "password was incorrect");
                         }
                     }
                 }
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/OutputFeedback.java b/jdk/src/share/classes/com/sun/crypto/provider/OutputFeedback.java
index 250e60e..ea5890d 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/OutputFeedback.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/OutputFeedback.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -26,7 +26,6 @@
 package com.sun.crypto.provider;
 
 import java.security.InvalidKeyException;
-import java.security.ProviderException;
 
 /**
  * This class represents ciphers in output-feedback (OFB) mode.
@@ -133,88 +132,101 @@
      *
      * <p>The input plain text <code>plain</code>, starting at
      * <code>plainOffset</code> and ending at
-     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
+     * <code>(plainOffset + len - 1)</code>, is encrypted.
      * The result is stored in <code>cipher</code>, starting at
      * <code>cipherOffset</code>.
      *
+     * <p>It is the application's responsibility to make sure that
+     * <code>plainLen</code> is a multiple of the stream unit size
+     * <code>numBytes</code>, as any excess bytes are ignored.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
+     *
      * @param plain the buffer with the input data to be encrypted
      * @param plainOffset the offset in <code>plain</code>
      * @param plainLen the length of the input data
      * @param cipher the buffer for the result
      * @param cipherOffset the offset in <code>cipher</code>
-     * @exception ProviderException if <code>plainLen</code> is not
-     * a multiple of the <code>numBytes</code>
      * @return the length of the encrypted data
      */
     int encrypt(byte[] plain, int plainOffset, int plainLen,
-                byte[] cipher, int cipherOffset) {
-
-        if ((plainLen % numBytes) != 0) {
-            throw new ProviderException("Internal error in input buffering");
-        }
-        int nShift = blockSize - numBytes;
+                byte[] cipher, int cipherOffset)
+    {
+        int i;
+        int len = blockSize - numBytes;
         int loopCount = plainLen / numBytes;
+        int oddBytes = plainLen % numBytes;
 
-        for (; loopCount > 0;
-             plainOffset += numBytes, cipherOffset += numBytes,
-             loopCount--) {
-            embeddedCipher.encryptBlock(register, 0, k, 0);
-            for (int i = 0; i < numBytes; i++) {
-                cipher[i + cipherOffset] =
-                    (byte)(k[i] ^ plain[i + plainOffset]);
-                if (nShift != 0) {
-                    System.arraycopy(register, numBytes, register, 0, nShift);
-                }
-                System.arraycopy(k, 0, register, nShift, numBytes);
+        if (len == 0) {
+            for (; loopCount > 0;
+                 plainOffset += numBytes, cipherOffset += numBytes,
+                 loopCount--) {
+                embeddedCipher.encryptBlock(register, 0, k, 0);
+                for (i=0; i<numBytes; i++)
+                    cipher[i+cipherOffset] =
+                        (byte)(k[i] ^ plain[i+plainOffset]);
+                System.arraycopy(k, 0, register, 0, numBytes);
+            }
+            if (oddBytes > 0) {
+                embeddedCipher.encryptBlock(register, 0, k, 0);
+                for (i=0; i<oddBytes; i++)
+                    cipher[i+cipherOffset] =
+                        (byte)(k[i] ^ plain[i+plainOffset]);
+                System.arraycopy(k, 0, register, 0, numBytes);
+            }
+        } else {
+            for (; loopCount > 0;
+                 plainOffset += numBytes, cipherOffset += numBytes,
+                 loopCount--) {
+                embeddedCipher.encryptBlock(register, 0, k, 0);
+                for (i=0; i<numBytes; i++)
+                    cipher[i+cipherOffset] =
+                        (byte)(k[i] ^ plain[i+plainOffset]);
+                System.arraycopy(register, numBytes, register, 0, len);
+                System.arraycopy(k, 0, register, len, numBytes);
+            }
+            if (oddBytes > 0) {
+                embeddedCipher.encryptBlock(register, 0, k, 0);
+                for (i=0; i<oddBytes; i++)
+                    cipher[i+cipherOffset] =
+                        (byte)(k[i] ^ plain[i+plainOffset]);
+                System.arraycopy(register, numBytes, register, 0, len);
+                System.arraycopy(k, 0, register, len, numBytes);
             }
         }
         return plainLen;
     }
 
     /**
-     * Performs last encryption operation.
+     * Performs decryption operation.
      *
-     * <p>The input plain text <code>plain</code>, starting at
-     * <code>plainOffset</code> and ending at
-     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
-     * The result is stored in <code>cipher</code>, starting at
-     * <code>cipherOffset</code>.
+     * <p>The input cipher text <code>cipher</code>, starting at
+     * <code>cipherOffset</code> and ending at
+     * <code>(cipherOffset + len - 1)</code>, is decrypted.
+     * The result is stored in <code>plain</code>, starting at
+     * <code>plainOffset</code>.
      *
-     * @param plain the buffer with the input data to be encrypted
+     * <p>It is the application's responsibility to make sure that
+     * <code>cipherLen</code> is a multiple of the stream unit size
+     * <code>numBytes</code>, as any excess bytes are ignored.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
+     *
+     * @param cipher the buffer with the input data to be decrypted
+     * @param cipherOffset the offset in <code>cipherOffset</code>
+     * @param cipherLen the length of the input data
+     * @param plain the buffer for the result
      * @param plainOffset the offset in <code>plain</code>
-     * @param plainLen the length of the input data
-     * @param cipher the buffer for the result
-     * @param cipherOffset the offset in <code>cipher</code>
-     * @return the length of the encrypted data
+     * @return the length of the decrypted data
      */
-    int encryptFinal(byte[] plain, int plainOffset, int plainLen,
-                     byte[] cipher, int cipherOffset) {
-        int oddBytes = plainLen % numBytes;
-        int len = encrypt(plain, plainOffset, (plainLen - oddBytes),
-                          cipher, cipherOffset);
-        plainOffset += len;
-        cipherOffset += len;
-
-        if (oddBytes != 0) {
-            embeddedCipher.encryptBlock(register, 0, k, 0);
-            for (int i = 0; i < oddBytes; i++) {
-                cipher[i + cipherOffset] =
-                    (byte)(k[i] ^ plain[ i + plainOffset]);
-            }
-        }
-        return plainLen;
-    }
-
-    // OFB encrypt and decrypt are identical
     int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
-                byte[] plain, int plainOffset) {
-        return encrypt(cipher, cipherOffset, cipherLen, plain, plainOffset);
-    }
-
-    // OFB encrypt and decrypt are identical
-    int decryptFinal(byte[] cipher, int cipherOffset, int cipherLen,
-                     byte[] plain, int plainOffset) {
+                        byte[] plain, int plainOffset)
+    {
         // OFB encrypt and decrypt are identical
-        return encryptFinal(cipher, cipherOffset, cipherLen, plain, plainOffset);
+        return encrypt(cipher, cipherOffset, cipherLen, plain, plainOffset);
     }
 }
diff --git a/jdk/src/share/classes/com/sun/crypto/provider/PCBC.java b/jdk/src/share/classes/com/sun/crypto/provider/PCBC.java
index fd99bb0..aefc45e 100644
--- a/jdk/src/share/classes/com/sun/crypto/provider/PCBC.java
+++ b/jdk/src/share/classes/com/sun/crypto/provider/PCBC.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -26,8 +26,6 @@
 package com.sun.crypto.provider;
 
 import java.security.InvalidKeyException;
-import java.security.ProviderException;
-
 
 /**
  * This class represents ciphers in Plaintext Cipher Block Chaining (PCBC)
@@ -120,36 +118,38 @@
      *
      * <p>The input plain text <code>plain</code>, starting at
      * <code>plainOffset</code> and ending at
-     * <code>(plainOffset + plainLen - 1)</code>, is encrypted.
+     * <code>(plainOffset + len - 1)</code>, is encrypted.
      * The result is stored in <code>cipher</code>, starting at
      * <code>cipherOffset</code>.
      *
+     * <p>It is the application's responsibility to make sure that
+     * <code>plainLen</code> is a multiple of the embedded cipher's block size,
+     * as any excess bytes are ignored.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
+     *
      * @param plain the buffer with the input data to be encrypted
      * @param plainOffset the offset in <code>plain</code>
      * @param plainLen the length of the input data
      * @param cipher the buffer for the result
      * @param cipherOffset the offset in <code>cipher</code>
-     * @exception ProviderException if <code>plainLen</code> is not
-     * a multiple of the block size
-     * @return the length of the encrypted data
      */
     int encrypt(byte[] plain, int plainOffset, int plainLen,
                 byte[] cipher, int cipherOffset)
     {
-        if ((plainLen % blockSize) != 0) {
-            throw new ProviderException("Internal error in input buffering");
-        }
         int i;
         int endIndex = plainOffset + plainLen;
 
         for (; plainOffset < endIndex;
              plainOffset += blockSize, cipherOffset += blockSize) {
-            for (i = 0; i < blockSize; i++) {
-                k[i] ^= plain[i + plainOffset];
+            for (i=0; i<blockSize; i++) {
+                k[i] ^= plain[i+plainOffset];
             }
             embeddedCipher.encryptBlock(k, 0, cipher, cipherOffset);
             for (i = 0; i < blockSize; i++) {
-                k[i] = (byte)(plain[i + plainOffset] ^ cipher[i + cipherOffset]);
+                k[i] = (byte)(plain[i+plainOffset] ^ cipher[i+cipherOffset]);
             }
         }
         return plainLen;
@@ -160,25 +160,27 @@
      *
      * <p>The input cipher text <code>cipher</code>, starting at
      * <code>cipherOffset</code> and ending at
-     * <code>(cipherOffset + cipherLen - 1)</code>, is decrypted.
+     * <code>(cipherOffset + len - 1)</code>, is decrypted.
      * The result is stored in <code>plain</code>, starting at
      * <code>plainOffset</code>.
      *
+     * <p>It is the application's responsibility to make sure that
+     * <code>cipherLen</code> is a multiple of the embedded cipher's block
+     * size, as any excess bytes are ignored.
+     *
+     * <p>It is also the application's responsibility to make sure that
+     * <code>init</code> has been called before this method is called.
+     * (This check is omitted here, to avoid double checking.)
+     *
      * @param cipher the buffer with the input data to be decrypted
      * @param cipherOffset the offset in <code>cipherOffset</code>
      * @param cipherLen the length of the input data
      * @param plain the buffer for the result
      * @param plainOffset the offset in <code>plain</code>
-     * @exception ProviderException if <code>cipherLen</code> is not
-     * a multiple of the block size
-     * @return the length of the decrypted data
      */
     int decrypt(byte[] cipher, int cipherOffset, int cipherLen,
                 byte[] plain, int plainOffset)
     {
-        if ((cipherLen % blockSize) != 0) {
-             throw new ProviderException("Internal error in input buffering");
-        }
         int i;
         int endIndex = cipherOffset + cipherLen;
 
@@ -187,10 +189,10 @@
             embeddedCipher.decryptBlock(cipher, cipherOffset,
                                    plain, plainOffset);
             for (i = 0; i < blockSize; i++) {
-                plain[i + plainOffset] ^= k[i];
+                plain[i+plainOffset] ^= k[i];
             }
             for (i = 0; i < blockSize; i++) {
-                k[i] = (byte)(plain[i + plainOffset] ^ cipher[i + cipherOffset]);
+                k[i] = (byte)(plain[i+plainOffset] ^ cipher[i+cipherOffset]);
             }
         }
         return cipherLen;
diff --git a/jdk/src/share/classes/com/sun/java/accessibility/util/package-info.java b/jdk/src/share/classes/com/sun/java/accessibility/util/package-info.java
index 7d81ed6..2ae79d1 100644
--- a/jdk/src/share/classes/com/sun/java/accessibility/util/package-info.java
+++ b/jdk/src/share/classes/com/sun/java/accessibility/util/package-info.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, 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
diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/AbstractLdapNamingEnumeration.java b/jdk/src/share/classes/com/sun/jndi/ldap/AbstractLdapNamingEnumeration.java
index 4b97591..241105b 100644
--- a/jdk/src/share/classes/com/sun/jndi/ldap/AbstractLdapNamingEnumeration.java
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/AbstractLdapNamingEnumeration.java
@@ -300,7 +300,7 @@
         errEx = e;
     }
 
-    protected abstract AbstractLdapNamingEnumeration<? extends NameClassPair> getReferredResults(
+    protected abstract AbstractLdapNamingEnumeration<T> getReferredResults(
             LdapReferralContext refCtx) throws NamingException;
 
     /*
@@ -360,7 +360,7 @@
      * Merge the entries and/or referrals from the supplied enumeration
      * with those of the current enumeration.
      */
-    protected void update(AbstractLdapNamingEnumeration<? extends NameClassPair> ne) {
+    protected void update(AbstractLdapNamingEnumeration<T> ne) {
         // Cleanup previous context first
         homeCtx.decEnumCount();
 
diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/DigestClientId.java b/jdk/src/share/classes/com/sun/jndi/ldap/DigestClientId.java
index 6eac44a..b4f19d0 100644
--- a/jdk/src/share/classes/com/sun/jndi/ldap/DigestClientId.java
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/DigestClientId.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,6 +60,7 @@
 
     final private String[] propvals;
     final private int myHash;
+    private int pHash = 0;
 
     DigestClientId(int version, String hostname, int port,
         String protocol, Control[] bindCtls, OutputStream trace,
@@ -77,9 +78,12 @@
             propvals = new String[SASL_PROPS.length];
             for (int i = 0; i < SASL_PROPS.length; i++) {
                 propvals[i] = (String) env.get(SASL_PROPS[i]);
+                if (propvals[i] != null) {
+                    pHash = pHash * 31 + propvals[i].hashCode();
+                }
             }
         }
-        myHash = super.hashCode() ^ Arrays.hashCode(propvals);
+        myHash = super.hashCode() + pHash;
     }
 
     public boolean equals(Object obj) {
@@ -88,6 +92,7 @@
         }
         DigestClientId other = (DigestClientId)obj;
         return myHash == other.myHash
+            && pHash == other.pHash
             && super.equals(obj)
             && Arrays.equals(propvals, other.propvals);
     }
diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/LdapBindingEnumeration.java b/jdk/src/share/classes/com/sun/jndi/ldap/LdapBindingEnumeration.java
index 8d385d3..65c8051 100644
--- a/jdk/src/share/classes/com/sun/jndi/ldap/LdapBindingEnumeration.java
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/LdapBindingEnumeration.java
@@ -104,9 +104,9 @@
     }
 
     @Override
-    protected AbstractLdapNamingEnumeration<? extends NameClassPair> getReferredResults(
+    protected LdapBindingEnumeration getReferredResults(
             LdapReferralContext refCtx) throws NamingException{
         // repeat the original operation at the new context
-        return (AbstractLdapNamingEnumeration<? extends NameClassPair>)refCtx.listBindings(listArg);
+        return (LdapBindingEnumeration)refCtx.listBindings(listArg);
     }
 }
diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/LdapNamingEnumeration.java b/jdk/src/share/classes/com/sun/jndi/ldap/LdapNamingEnumeration.java
index c923fda..422ce79 100644
--- a/jdk/src/share/classes/com/sun/jndi/ldap/LdapNamingEnumeration.java
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/LdapNamingEnumeration.java
@@ -72,9 +72,9 @@
     }
 
     @Override
-    protected AbstractLdapNamingEnumeration<? extends NameClassPair> getReferredResults(
+    protected LdapNamingEnumeration getReferredResults(
             LdapReferralContext refCtx) throws NamingException {
         // repeat the original operation at the new context
-        return (AbstractLdapNamingEnumeration<? extends NameClassPair>)refCtx.list(listArg);
+        return (LdapNamingEnumeration)refCtx.list(listArg);
     }
 }
diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/LdapSearchEnumeration.java b/jdk/src/share/classes/com/sun/jndi/ldap/LdapSearchEnumeration.java
index 24c421e..329b1d2 100644
--- a/jdk/src/share/classes/com/sun/jndi/ldap/LdapSearchEnumeration.java
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/LdapSearchEnumeration.java
@@ -199,15 +199,15 @@
     }
 
     @Override
-    protected AbstractLdapNamingEnumeration<? extends NameClassPair> getReferredResults(
+    protected LdapSearchEnumeration getReferredResults(
             LdapReferralContext refCtx) throws NamingException {
         // repeat the original operation at the new context
-        return (AbstractLdapNamingEnumeration<? extends NameClassPair>)refCtx.search(
+        return (LdapSearchEnumeration)refCtx.search(
                 searchArgs.name, searchArgs.filter, searchArgs.cons);
     }
 
     @Override
-    protected void update(AbstractLdapNamingEnumeration<? extends NameClassPair> ne) {
+    protected void update(AbstractLdapNamingEnumeration<SearchResult> ne) {
         super.update(ne);
 
         // Update search-specific variables
diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/SimpleClientId.java b/jdk/src/share/classes/com/sun/jndi/ldap/SimpleClientId.java
index 2915110..6fa5471 100644
--- a/jdk/src/share/classes/com/sun/jndi/ldap/SimpleClientId.java
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/SimpleClientId.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -49,23 +49,21 @@
                 socketFactory);
 
         this.username = username;
-        int pwdHashCode = 0;
         if (passwd == null) {
             this.passwd = null;
+        } else if (passwd instanceof String) {
+            this.passwd = passwd;
         } else if (passwd instanceof byte[]) {
             this.passwd = ((byte[])passwd).clone();
-            pwdHashCode = Arrays.hashCode((byte[])passwd);
         } else if (passwd instanceof char[]) {
             this.passwd = ((char[])passwd).clone();
-            pwdHashCode = Arrays.hashCode((char[])passwd);
         } else {
             this.passwd = passwd;
-            pwdHashCode = passwd.hashCode();
         }
 
         myHash = super.hashCode()
-            ^ (username != null ? username.hashCode() : 0)
-            ^ pwdHashCode;
+            + (username != null ? username.hashCode() : 0)
+            + (passwd != null ? passwd.hashCode() : 0);
     }
 
     public boolean equals(Object obj) {
diff --git a/jdk/src/share/classes/com/sun/jndi/ldap/pool/Pool.java b/jdk/src/share/classes/com/sun/jndi/ldap/pool/Pool.java
index 29c4d32..f9786ca 100644
--- a/jdk/src/share/classes/com/sun/jndi/ldap/pool/Pool.java
+++ b/jdk/src/share/classes/com/sun/jndi/ldap/pool/Pool.java
@@ -118,11 +118,7 @@
         PooledConnectionFactory factory) throws NamingException {
 
         d("get(): ", id);
-        if (debug) {
-            synchronized (map) {
-                d("size: ", map.size());
-            }
-        }
+        d("size: ", map.size());
 
         expungeStaleConnections();
 
@@ -145,9 +141,10 @@
                 // Keep the weak reference through the element of a linked list
                 weakRefs.add(weakRef);
             }
-            d("get(): size after: ", map.size());
         }
 
+        d("get(): size after: ", map.size());
+
         return conns.get(timeout, factory); // get one connection from list
     }
 
@@ -212,24 +209,19 @@
         out.println("maximum pool size: " + maxSize);
         out.println("preferred pool size: " + prefSize);
         out.println("initial pool size: " + initSize);
+        out.println("current pool size: " + map.size());
 
-        synchronized (map) {
-            out.println("current pool size: " + map.size());
-
-            for (Map.Entry<Object, ConnectionsRef> entry : map.entrySet()) {
-                id = entry.getKey();
-                conns = entry.getValue().getConnections();
-                out.println("   " + id + ":" + conns.getStats());
-            }
+        for (Map.Entry<Object, ConnectionsRef> entry : map.entrySet()) {
+            id = entry.getKey();
+            conns = entry.getValue().getConnections();
+            out.println("   " + id + ":" + conns.getStats());
         }
 
         out.println("====== Pool end =====================");
     }
 
     public String toString() {
-        synchronized (map) {
-            return super.toString() + " " + map.toString();
-        }
+        return super.toString() + " " + map.toString();
     }
 
     private void d(String msg, int i) {
diff --git a/jdk/src/share/classes/com/sun/tools/example/debug/tty/EventHandler.java b/jdk/src/share/classes/com/sun/tools/example/debug/tty/EventHandler.java
index cd416cc..fe6dd07 100644
--- a/jdk/src/share/classes/com/sun/tools/example/debug/tty/EventHandler.java
+++ b/jdk/src/share/classes/com/sun/tools/example/debug/tty/EventHandler.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -133,10 +133,6 @@
             if (!vmDied) {
                 vmDisconnectEvent(event);
             }
-            /*
-             * Inform jdb command line processor that jdb is being shutdown. JDK-8154144.
-             */
-            ((TTY)notifier).setShuttingDown(true);
             Env.shutdown(shutdownMessageKey);
             return false;
         } else {
diff --git a/jdk/src/share/classes/com/sun/tools/example/debug/tty/TTY.java b/jdk/src/share/classes/com/sun/tools/example/debug/tty/TTY.java
index 5338665..1958b9a 100644
--- a/jdk/src/share/classes/com/sun/tools/example/debug/tty/TTY.java
+++ b/jdk/src/share/classes/com/sun/tools/example/debug/tty/TTY.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -56,16 +56,6 @@
      */
     private static final String progname = "jdb";
 
-    private volatile boolean shuttingDown = false;
-
-    public void setShuttingDown(boolean s) {
-       shuttingDown = s;
-    }
-
-    public boolean isShuttingDown() {
-        return shuttingDown;
-    }
-
     @Override
     public void vmStartEvent(VMStartEvent se)  {
         Thread.yield();  // fetch output
@@ -760,13 +750,7 @@
             while (true) {
                 String ln = in.readLine();
                 if (ln == null) {
-                    /*
-                     *  Jdb is being shutdown because debuggee exited, ignore any 'null'
-                     *  returned by readLine() during shutdown. JDK-8154144.
-                     */
-                    if (!isShuttingDown()) {
-                        MessageOutput.println("Input stream closed.");
-                    }
+                    MessageOutput.println("Input stream closed.");
                     ln = "quit";
                 }
 
diff --git a/jdk/src/share/classes/java/awt/Container.java b/jdk/src/share/classes/java/awt/Container.java
index b9e4f91..47e580b 100644
--- a/jdk/src/share/classes/java/awt/Container.java
+++ b/jdk/src/share/classes/java/awt/Container.java
@@ -1089,18 +1089,17 @@
             }
             checkAddToSelf(comp);
             checkNotAWindow(comp);
-            /* Reparent the component and tidy up the tree's state. */
-            if (comp.parent != null) {
-                comp.parent.remove(comp);
-                if (index > component.size()) {
-                    throw new IllegalArgumentException("illegal component position");
-                }
-            }
             if (thisGC != null) {
                 comp.checkGD(thisGC.getDevice().getIDstring());
             }
 
-
+            /* Reparent the component and tidy up the tree's state. */
+            if (comp.parent != null) {
+                comp.parent.remove(comp);
+                    if (index > component.size()) {
+                        throw new IllegalArgumentException("illegal component position");
+                    }
+            }
 
             //index == -1 means add to the end.
             if (index == -1) {
diff --git a/jdk/src/share/classes/java/awt/SplashScreen.java b/jdk/src/share/classes/java/awt/SplashScreen.java
index c51aa6f..05a38e7 100644
--- a/jdk/src/share/classes/java/awt/SplashScreen.java
+++ b/jdk/src/share/classes/java/awt/SplashScreen.java
@@ -250,7 +250,7 @@
             assert scale > 0;
             if (scale > 0 && scale != 1) {
                 bounds.setSize((int) (bounds.getWidth() / scale),
-                        (int) (bounds.getHeight() / scale));
+                        (int) (bounds.getWidth() / scale));
             }
             return bounds;
         }
diff --git a/jdk/src/share/classes/java/awt/TextArea.java b/jdk/src/share/classes/java/awt/TextArea.java
index 7c2acf0..34b2137 100644
--- a/jdk/src/share/classes/java/awt/TextArea.java
+++ b/jdk/src/share/classes/java/awt/TextArea.java
@@ -322,8 +322,9 @@
         TextAreaPeer peer = (TextAreaPeer)this.peer;
         if (peer != null) {
             peer.insert(str, pos);
+        } else {
+            text = text.substring(0, pos) + str + text.substring(pos);
         }
-        text = text.substring(0, pos) + str + text.substring(pos);
     }
 
     /**
@@ -346,7 +347,11 @@
      */
     @Deprecated
     public synchronized void appendText(String str) {
+        if (peer != null) {
             insertText(str, getText().length());
+        } else {
+            text = text + str;
+        }
     }
 
     /**
@@ -381,8 +386,9 @@
         TextAreaPeer peer = (TextAreaPeer)this.peer;
         if (peer != null) {
             peer.replaceRange(str, start, end);
+        } else {
+            text = text.substring(0, start) + str + text.substring(end);
         }
-        text = text.substring(0, start) + str + text.substring(end);
     }
 
     /**
diff --git a/jdk/src/share/classes/java/beans/MethodRef.java b/jdk/src/share/classes/java/beans/MethodRef.java
index 6be617f..59b2690 100644
--- a/jdk/src/share/classes/java/beans/MethodRef.java
+++ b/jdk/src/share/classes/java/beans/MethodRef.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -64,9 +64,10 @@
                 this.signature = null;
                 this.methodRef = null;
                 this.typeRef = null;
-                return null;
             }
-            this.methodRef = new SoftReference<>(method);
+            else {
+                this.methodRef = new SoftReference<>(method);
+            }
         }
         return isPackageAccessible(method.getDeclaringClass()) ? method : null;
     }
diff --git a/jdk/src/share/classes/java/io/CharArrayReader.java b/jdk/src/share/classes/java/io/CharArrayReader.java
index 2190be3..08d447a 100644
--- a/jdk/src/share/classes/java/io/CharArrayReader.java
+++ b/jdk/src/share/classes/java/io/CharArrayReader.java
@@ -130,10 +130,8 @@
             if (pos >= count) {
                 return -1;
             }
-
-            int avail = count - pos;
-            if (len > avail) {
-                len = avail;
+            if (pos + len > count) {
+                len = count - pos;
             }
             if (len <= 0) {
                 return 0;
@@ -159,10 +157,8 @@
     public long skip(long n) throws IOException {
         synchronized (lock) {
             ensureOpen();
-
-            long avail = count - pos;
-            if (n > avail) {
-                n = avail;
+            if (pos + n > count) {
+                n = count - pos;
             }
             if (n < 0) {
                 return 0;
diff --git a/jdk/src/share/classes/java/io/StringBufferInputStream.java b/jdk/src/share/classes/java/io/StringBufferInputStream.java
index f47eebc..509a96c 100644
--- a/jdk/src/share/classes/java/io/StringBufferInputStream.java
+++ b/jdk/src/share/classes/java/io/StringBufferInputStream.java
@@ -118,10 +118,8 @@
         if (pos >= count) {
             return -1;
         }
-
-        int avail = count - pos;
-        if (len > avail) {
-            len = avail;
+        if (pos + len > count) {
+            len = count - pos;
         }
         if (len <= 0) {
             return 0;
diff --git a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java
index acac29b..dfd8628 100644
--- a/jdk/src/share/classes/java/lang/invoke/MethodHandles.java
+++ b/jdk/src/share/classes/java/lang/invoke/MethodHandles.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 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
@@ -915,9 +915,6 @@
          * @throws NullPointerException if any argument is null
          */
         public MethodHandle findConstructor(Class<?> refc, MethodType type) throws NoSuchMethodException, IllegalAccessException {
-            if (refc.isArray()) {
-                throw new NoSuchMethodException("no constructor for array class: " + refc.getName());
-            }
             String name = "<init>";
             MemberName ctor = resolveOrFail(REF_newInvokeSpecial, refc, name, type);
             return getDirectConstructor(refc, ctor);
diff --git a/jdk/src/share/classes/java/nio/Bits.java b/jdk/src/share/classes/java/nio/Bits.java
index 7711b5a..c7f2b78 100644
--- a/jdk/src/share/classes/java/nio/Bits.java
+++ b/jdk/src/share/classes/java/nio/Bits.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 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
@@ -614,8 +614,7 @@
         String arch = AccessController.doPrivileged(
             new sun.security.action.GetPropertyAction("os.arch"));
         unaligned = arch.equals("i386") || arch.equals("x86")
-            || arch.equals("amd64") || arch.equals("x86_64")
-            || arch.equals("ppc64") || arch.equals("ppc64le");
+            || arch.equals("amd64") || arch.equals("x86_64");
         unalignedKnown = true;
         return unaligned;
     }
diff --git a/jdk/src/share/classes/java/security/ProtectionDomain.java b/jdk/src/share/classes/java/security/ProtectionDomain.java
index 9e597bc..ffd2def 100644
--- a/jdk/src/share/classes/java/security/ProtectionDomain.java
+++ b/jdk/src/share/classes/java/security/ProtectionDomain.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -25,16 +25,12 @@
 
 package java.security;
 
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
-import java.lang.ref.SoftReference;
-import java.lang.ref.WeakReference;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Enumeration;
 import java.util.List;
 import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
+import java.util.WeakHashMap;
 import sun.misc.JavaSecurityProtectionDomainAccess;
 import static sun.misc.JavaSecurityProtectionDomainAccess.ProtectionDomainCache;
 import sun.security.util.Debug;
@@ -460,14 +456,24 @@
     /**
      * Used for storing ProtectionDomains as keys in a Map.
      */
-    static final class Key {}
+    final class Key {}
 
     static {
         SharedSecrets.setJavaSecurityProtectionDomainAccess(
             new JavaSecurityProtectionDomainAccess() {
-                @Override
                 public ProtectionDomainCache getProtectionDomainCache() {
-                    return new PDCache();
+                    return new ProtectionDomainCache() {
+                        private final Map<Key, PermissionCollection> map =
+                            Collections.synchronizedMap
+                                (new WeakHashMap<Key, PermissionCollection>());
+                        public void put(ProtectionDomain pd,
+                            PermissionCollection pc) {
+                            map.put((pd == null ? null : pd.key), pc);
+                        }
+                        public PermissionCollection get(ProtectionDomain pd) {
+                            return pd == null ? map.get(null) : map.get(pd.key);
+                        }
+                    };
                 }
 
                 @Override
@@ -476,119 +482,4 @@
                 }
             });
     }
-
-    /**
-     * A cache of ProtectionDomains and their Permissions.
-     *
-     * This class stores ProtectionDomains as weak keys in a ConcurrentHashMap
-     * with additional support for checking and removing weak keys that are no
-     * longer in use. There can be cases where the permission collection may
-     * have a chain of strong references back to the ProtectionDomain, which
-     * ordinarily would prevent the entry from being removed from the map. To
-     * address that, we wrap the permission collection in a SoftReference so
-     * that it can be reclaimed by the garbage collector due to memory demand.
-     */
-    private static class PDCache implements ProtectionDomainCache {
-        private final ConcurrentHashMap<WeakProtectionDomainKey,
-                                        SoftReference<PermissionCollection>>
-                                        pdMap = new ConcurrentHashMap<>();
-        private final ReferenceQueue<Key> queue = new ReferenceQueue<>();
-
-        @Override
-        public void put(ProtectionDomain pd, PermissionCollection pc) {
-            processQueue(queue, pdMap);
-            WeakProtectionDomainKey weakPd =
-                new WeakProtectionDomainKey(pd, queue);
-            pdMap.put(weakPd, new SoftReference<>(pc));
-        }
-
-        @Override
-        public PermissionCollection get(ProtectionDomain pd) {
-            processQueue(queue, pdMap);
-            WeakProtectionDomainKey weakPd = new WeakProtectionDomainKey(pd);
-            SoftReference<PermissionCollection> sr = pdMap.get(weakPd);
-            return (sr == null) ? null : sr.get();
-        }
-
-        /**
-         * Removes weak keys from the map that have been enqueued
-         * on the reference queue and are no longer in use.
-         */
-        private static void processQueue(ReferenceQueue<Key> queue,
-                                         ConcurrentHashMap<? extends
-                                         WeakReference<Key>, ?> pdMap) {
-            Reference<? extends Key> ref;
-            while ((ref = queue.poll()) != null) {
-                pdMap.remove(ref);
-            }
-        }
-    }
-
-    /**
-     * A weak key for a ProtectionDomain.
-     */
-    private static class WeakProtectionDomainKey extends WeakReference<Key> {
-        /**
-         * Saved value of the referent's identity hash code, to maintain
-         * a consistent hash code after the referent has been cleared
-         */
-        private final int hash;
-
-        /**
-         * A key representing a null ProtectionDomain.
-         */
-        private static final Key NULL_KEY = new Key();
-
-        /**
-         * Create a new WeakProtectionDomain with the specified domain and
-         * registered with a queue.
-         */
-        WeakProtectionDomainKey(ProtectionDomain pd, ReferenceQueue<Key> rq) {
-            this((pd == null ? NULL_KEY : pd.key), rq);
-        }
-
-        WeakProtectionDomainKey(ProtectionDomain pd) {
-            this(pd == null ? NULL_KEY : pd.key);
-        }
-
-        private WeakProtectionDomainKey(Key key, ReferenceQueue<Key> rq) {
-            super(key, rq);
-            hash = key.hashCode();
-        }
-
-        private WeakProtectionDomainKey(Key key) {
-            super(key);
-            hash = key.hashCode();
-        }
-
-        /**
-         * Returns the identity hash code of the original referent.
-         */
-        @Override
-        public int hashCode() {
-            return hash;
-        }
-
-        /**
-         * Returns true if the given object is an identical
-         * WeakProtectionDomainKey instance, or, if this object's referent
-         * has not been cleared and the given object is another
-         * WeakProtectionDomainKey instance with an identical non-null
-         * referent as this one.
-         */
-        @Override
-        public boolean equals(Object obj) {
-            if (obj == this) {
-                return true;
-            }
-
-            if (obj instanceof WeakProtectionDomainKey) {
-                Object referent = get();
-                return (referent != null) &&
-                       (referent == ((WeakProtectionDomainKey)obj).get());
-            } else {
-                return false;
-            }
-        }
-    }
 }
diff --git a/jdk/src/share/classes/java/security/SecureRandom.java b/jdk/src/share/classes/java/security/SecureRandom.java
index 6848be5..3481e21 100644
--- a/jdk/src/share/classes/java/security/SecureRandom.java
+++ b/jdk/src/share/classes/java/security/SecureRandom.java
@@ -464,7 +464,7 @@
      * @param bytes the array to be filled in with random bytes.
      */
     @Override
-    public void nextBytes(byte[] bytes) {
+    synchronized public void nextBytes(byte[] bytes) {
         secureRandomSpi.engineNextBytes(bytes);
     }
 
diff --git a/jdk/src/share/classes/java/time/ZoneOffset.java b/jdk/src/share/classes/java/time/ZoneOffset.java
index 97b7f13..dc2562a 100644
--- a/jdk/src/share/classes/java/time/ZoneOffset.java
+++ b/jdk/src/share/classes/java/time/ZoneOffset.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 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
@@ -375,15 +375,15 @@
         } else if ((minutes > 0 && seconds < 0) || (minutes < 0 && seconds > 0)) {
             throw new DateTimeException("Zone offset minutes and seconds must have the same sign");
         }
-        if (minutes < -59 || minutes > 59) {
-            throw new DateTimeException("Zone offset minutes not in valid range: value " +
-                    minutes + " is not in the range -59 to 59");
+        if (Math.abs(minutes) > 59) {
+            throw new DateTimeException("Zone offset minutes not in valid range: abs(value) " +
+                    Math.abs(minutes) + " is not in the range 0 to 59");
         }
-        if (seconds < -59 || seconds > 59) {
-            throw new DateTimeException("Zone offset seconds not in valid range: value " +
-                    seconds + " is not in the range -59 to 59");
+        if (Math.abs(seconds) > 59) {
+            throw new DateTimeException("Zone offset seconds not in valid range: abs(value) " +
+                    Math.abs(seconds) + " is not in the range 0 to 59");
         }
-        if (Math.abs(hours) == 18 && (minutes | seconds) != 0) {
+        if (Math.abs(hours) == 18 && (Math.abs(minutes) > 0 || Math.abs(seconds) > 0)) {
             throw new DateTimeException("Zone offset not in valid range: -18:00 to +18:00");
         }
     }
@@ -411,7 +411,7 @@
      * @throws DateTimeException if the offset is not in the required range
      */
     public static ZoneOffset ofTotalSeconds(int totalSeconds) {
-        if (totalSeconds < -MAX_SECONDS || totalSeconds > MAX_SECONDS) {
+        if (Math.abs(totalSeconds) > MAX_SECONDS) {
             throw new DateTimeException("Zone offset not in valid range: -18:00 to +18:00");
         }
         if (totalSeconds % (15 * SECONDS_PER_MINUTE) == 0) {
@@ -696,12 +696,11 @@
      * The comparison is "consistent with equals", as defined by {@link Comparable}.
      *
      * @param other  the other date to compare to, not null
-     * @return the comparator value, negative if less, positive if greater
+     * @return the comparator value, negative if less, postive if greater
      * @throws NullPointerException if {@code other} is null
      */
     @Override
     public int compareTo(ZoneOffset other) {
-        // abs(totalSeconds) <= MAX_SECONDS, so no overflow can happen here
         return other.totalSeconds - totalSeconds;
     }
 
diff --git a/jdk/src/share/classes/java/time/format/ZoneName.java b/jdk/src/share/classes/java/time/format/ZoneName.java
index 6452413..f1f6170 100644
--- a/jdk/src/share/classes/java/time/format/ZoneName.java
+++ b/jdk/src/share/classes/java/time/format/ZoneName.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -25,8 +25,11 @@
 package java.time.format;
 
 import java.util.HashMap;
+import java.util.HashSet;
 import java.util.Locale;
 import java.util.Map;
+import java.util.Map.Entry;
+import java.util.Set;
 
 /**
  * A helper class to map a zone name to metazone and back to the
@@ -332,7 +335,6 @@
         "America/Eirunepe", "Amazon", "America/Manaus",
         "Africa/Nairobi", "Africa_Eastern", "Africa/Nairobi",
         "Asia/Yakutsk", "Yakutsk", "Asia/Yakutsk",
-        "Asia/Yangon", "Myanmar", "Asia/Rangoon",
         "America/Goose_Bay", "Atlantic", "America/Halifax",
         "Africa/Maseru", "Africa_Southern", "Africa/Johannesburg",
         "America/Swift_Current", "America_Central", "America/Chicago",
@@ -768,7 +770,6 @@
         "America/Indianapolis", "America/Indiana/Indianapolis",
         "Europe/Belfast", "Europe/London",
         "America/Kralendijk", "America/Curacao",
-        "Asia/Rangoon", "Asia/Yangon",
     };
 
     private static final Map<String, String> zidToMzone = new HashMap<>();
diff --git a/jdk/src/share/classes/java/util/ArrayList.java b/jdk/src/share/classes/java/util/ArrayList.java
index 0af3388..925cc18 100644
--- a/jdk/src/share/classes/java/util/ArrayList.java
+++ b/jdk/src/share/classes/java/util/ArrayList.java
@@ -842,8 +842,6 @@
         int lastRet = -1; // index of last element returned; -1 if no such
         int expectedModCount = modCount;
 
-        Itr() {}
-
         public boolean hasNext() {
             return cursor != size;
         }
diff --git a/jdk/src/share/classes/java/util/Base64.java b/jdk/src/share/classes/java/util/Base64.java
index 61f68d3..172acbe 100644
--- a/jdk/src/share/classes/java/util/Base64.java
+++ b/jdk/src/share/classes/java/util/Base64.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -788,7 +788,7 @@
         public void write(byte[] b, int off, int len) throws IOException {
             if (closed)
                 throw new IOException("Stream is closed");
-            if (off < 0 || len < 0 || len > b.length - off)
+            if (off < 0 || len < 0 || off + len > b.length)
                 throw new ArrayIndexOutOfBoundsException();
             if (len == 0)
                 return;
diff --git a/jdk/src/share/classes/java/util/CurrencyData.properties b/jdk/src/share/classes/java/util/CurrencyData.properties
index b3ff517..5f2656e 100644
--- a/jdk/src/share/classes/java/util/CurrencyData.properties
+++ b/jdk/src/share/classes/java/util/CurrencyData.properties
@@ -1,5 +1,5 @@
 #
-# Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
+# Copyright (c) 2000, 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
@@ -31,7 +31,7 @@
 # Version of the currency code information in this class.
 # It is a serial number that accompanies with each amendment.
 
-dataVersion=160
+dataVersion=159
 
 # List of all valid ISO 4217 currency codes.
 # To ensure compatibility, do not remove codes.
@@ -109,7 +109,7 @@
 AT=EUR
 # AZERBAIJAN
 AZ=AZN
-# BAHAMAS (THE)
+# BAHAMAS
 BS=BSD
 # BAHRAIN
 BH=BHD
@@ -131,7 +131,7 @@
 BQ=USD
 # BHUTAN
 BT=BTN
-# BOLIVIA (PLURINATIONAL STATE OF)
+# BOLIVIA
 BO=BOB
 # BOSNIA AND HERZEGOVINA
 BA=BAM
@@ -141,7 +141,7 @@
 BV=NOK
 # BRAZIL
 BR=BRL
-# BRITISH INDIAN OCEAN TERRITORY (THE)
+# BRITISH INDIAN OCEAN TERRITORY
 IO=USD
 # BRUNEI DARUSSALAM
 BN=BND
@@ -159,9 +159,9 @@
 CA=CAD
 # CAPE VERDE
 CV=CVE
-# CAYMAN ISLANDS (THE)
+# CAYMAN ISLANDS
 KY=KYD
-# CENTRAL AFRICAN REPUBLIC (THE)
+# CENTRAL AFRICAN REPUBLIC
 CF=XAF
 # CHAD
 TD=XAF
@@ -171,17 +171,17 @@
 CN=CNY
 # CHRISTMAS ISLAND
 CX=AUD
-# COCOS (KEELING) ISLANDS (THE)
+# COCOS (KEELING) ISLANDS
 CC=AUD
 # COLOMBIA
 CO=COP
-# COMOROS (THE)
+# COMOROS
 KM=KMF
-# CONGO (THE)
+# CONGO
 CG=XAF
-# CONGO (THE DEMOCRATIC REPUBLIC OF THE)
+# CONGO, THE DEMOCRATIC REPUBLIC OF THE
 CD=CDF
-# COOK ISLANDS (THE)
+# COOK ISLANDS
 CK=NZD
 # COSTA RICA
 CR=CRC
@@ -195,7 +195,7 @@
 CW=ANG
 # CYPRUS
 CY=EUR
-# CZECH REPUBLIC (THE)
+# CZECH REPUBLIC
 CZ=CZK
 # DENMARK
 DK=DKK
@@ -203,7 +203,7 @@
 DJ=DJF
 # DOMINICA
 DM=XCD
-# DOMINICAN REPUBLIC (THE)
+# DOMINICAN REPUBLIC
 DO=DOP
 # ECUADOR
 EC=USD
@@ -220,9 +220,9 @@
 EE=EUR
 # ETHIOPIA
 ET=ETB
-# FALKLAND ISLANDS (THE) [MALVINAS]
+# FALKLAND ISLANDS (MALVINAS)
 FK=FKP
-# FAROE ISLANDS (THE)
+# FAROE ISLANDS
 FO=DKK
 # FIJI
 FJ=FJD
@@ -234,11 +234,11 @@
 GF=EUR
 # FRENCH POLYNESIA
 PF=XPF
-# FRENCH SOUTHERN TERRITORIES (THE)
+# FRENCH SOUTHERN TERRITORIES
 TF=EUR
 # GABON
 GA=XAF
-# GAMBIA (THE)
+# GAMBIA
 GM=GMD
 # GEORGIA
 GE=GEL
@@ -272,7 +272,7 @@
 HT=HTG
 # HEARD ISLAND AND MCDONALD ISLANDS
 HM=AUD
-# HOLY SEE (THE)
+# HOLY SEE (VATICAN CITY STATE)
 VA=EUR
 # HONDURAS
 HN=HNL
@@ -286,7 +286,7 @@
 IN=INR
 # INDONESIA
 ID=IDR
-# IRAN (ISLAMIC REPUBLIC OF)
+# IRAN, ISLAMIC REPUBLIC OF
 IR=IRR
 # IRAQ
 IQ=IQD
@@ -312,15 +312,15 @@
 KE=KES
 # KIRIBATI
 KI=AUD
-# KOREA (THE DEMOCRATIC PEOPLE'S REPUBLIC OF)
+# KOREA, DEMOCRATIC PEOPLE'S REPUBLIC OF
 KP=KPW
-# KOREA (THE REPUBLIC OF)
+# KOREA, REPUBLIC OF
 KR=KRW
 # KUWAIT
 KW=KWD
 # KYRGYZSTAN
 KG=KGS
-# LAO PEOPLE'S DEMOCRATIC REPUBLIC (THE)
+# LAO PEOPLE'S DEMOCRATIC REPUBLIC
 LA=LAK
 # LATVIA
 LV=LVL;2013-12-31-22-00-00;EUR
@@ -340,7 +340,7 @@
 LU=EUR
 # MACAU
 MO=MOP
-# MACEDONIA (THE FORMER YUGOSLAV REPUBLIC OF)
+# MACEDONIA, THE FORMER YUGOSLAV REPUBLIC OF
 MK=MKD
 # MADAGASCAR
 MG=MGA
@@ -354,7 +354,7 @@
 ML=XOF
 # MALTA
 MT=EUR
-# MARSHALL ISLANDS (THE)
+# MARSHALL ISLANDS
 MH=USD
 # MARTINIQUE
 MQ=EUR
@@ -366,9 +366,9 @@
 YT=EUR
 # MEXICO
 MX=MXN
-# MICRONESIA (FEDERATED STATES OF)
+# MICRONESIA, FEDERATED STATES OF
 FM=USD
-# MOLDOVA (THE REPUBLIC OF)
+# MOLDOVA, REPUBLIC OF
 MD=MDL
 # MONACO
 MC=EUR
@@ -390,7 +390,7 @@
 NR=AUD
 # NEPAL
 NP=NPR
-# NETHERLANDS (THE)
+# NETHERLANDS
 NL=EUR
 # NETHERLANDS ANTILLES
 AN=ANG
@@ -400,7 +400,7 @@
 NZ=NZD
 # NICARAGUA
 NI=NIO
-# NIGER (THE)
+# NIGER
 NE=XOF
 # NIGERIA
 NG=NGN
@@ -408,7 +408,7 @@
 NU=NZD
 # NORFOLK ISLAND
 NF=AUD
-# NORTHERN MARIANA ISLANDS (THE)
+# NORTHERN MARIANA ISLANDS
 MP=USD
 # NORWAY
 NO=NOK
@@ -428,7 +428,7 @@
 PY=PYG
 # PERU
 PE=PEN
-# PHILIPPINES (THE)
+# PHILIPPINES
 PH=PHP
 # PITCAIRN
 PN=NZD
@@ -444,7 +444,7 @@
 RE=EUR
 # ROMANIA
 RO=RON
-# RUSSIAN FEDERATION (THE)
+# RUSSIAN FEDERATION
 RU=RUB
 # RWANDA
 RW=RWF
@@ -500,7 +500,7 @@
 ES=EUR
 # SRI LANKA
 LK=LKR
-# SUDAN (THE)
+# SUDAN
 SD=SDG
 # SURINAME
 SR=SRD
@@ -516,7 +516,7 @@
 CH=CHF
 # SYRIAN ARAB REPUBLIC
 SY=SYP
-# TAIWAN (PROVINCE OF CHINA)
+# TAIWAN
 TW=TWD
 # TAJIKISTAN
 TJ=TJS
@@ -540,7 +540,7 @@
 TR=TRY
 # TURKMENISTAN
 TM=TMT
-# TURKS AND CAICOS ISLANDS (THE)
+# TURKS AND CAICOS ISLANDS
 TC=USD
 # TUVALU
 TV=AUD
@@ -548,13 +548,13 @@
 UG=UGX
 # UKRAINE
 UA=UAH
-# UNITED ARAB EMIRATES (THE)
+# UNITED ARAB EMIRATES
 AE=AED
-# UNITED KINGDOM OF GREAT BRITAIN AND NORTHERN IRELAND (THE)
+# UNITED KINGDOM
 GB=GBP
-# UNITED STATES OF AMERICA (THE)
+# UNITED STATES
 US=USD
-# UNITED STATES MINOR OUTLYING ISLANDS (THE)
+# UNITED STATES MINOR OUTLYING ISLANDS
 UM=USD
 # URUGUAY
 UY=UYU
@@ -562,7 +562,7 @@
 UZ=UZS
 # VANUATU
 VU=VUV
-# VENEZUELA (BOLIVARIAN REPUBLIC OF)
+# VENEZUELA
 VE=VEF
 # VIET NAM
 VN=VND
diff --git a/jdk/src/share/classes/javax/crypto/JceSecurity.java b/jdk/src/share/classes/javax/crypto/JceSecurity.java
index 5def277..29823e7 100644
--- a/jdk/src/share/classes/javax/crypto/JceSecurity.java
+++ b/jdk/src/share/classes/javax/crypto/JceSecurity.java
@@ -29,14 +29,12 @@
 import java.util.jar.*;
 import java.io.*;
 import java.net.URL;
-import java.nio.file.*;
 import java.security.*;
 
 import java.security.Provider.Service;
 
 import sun.security.jca.*;
 import sun.security.jca.GetInstance.Instance;
-import sun.security.util.Debug;
 
 /**
  * This class instantiates implementations of JCE engine classes from
@@ -68,9 +66,6 @@
 
     private static final boolean isRestricted;
 
-    private static final Debug debug =
-                        Debug.getInstance("jca", "Cipher");
-
     /*
      * Don't let anyone instantiate this.
      */
@@ -209,7 +204,7 @@
 
     static {
         try {
-            NULL_URL = new URL("http://null.oracle.com/");
+            NULL_URL = new URL("http://null.sun.com/");
         } catch (Exception e) {
             throw new RuntimeException(e);
         }
@@ -244,70 +239,14 @@
         }
     }
 
-    /*
-     * This is called from within an doPrivileged block.
-     *
-     * Following logic is used to decide what policy files are selected.
-     *
-     * If the new Security property (crypto.policy) is set in the
-     * java.security file, or has been set dynamically using the
-     * Security.setProperty() call before the JCE framework has
-     * been initialized, that setting will be used.
-     * Remember - this property is not defined by default. A conscious
-     * user edit or an application call is required.
-     *
-     * Otherwise, if user has policy jar files installed in the legacy
-     * jre/lib/security/ directory, the JDK will honor whatever
-     * setting is set by those policy files. (legacy/current behavior)
-     *
-     * If none of the above 2 conditions are met, the JDK will default
-     * to using the limited crypto policy files found in the
-     * jre/lib/security/policy/limited/ directory
-     */
     private static void setupJurisdictionPolicies() throws Exception {
-        // Sanity check the crypto.policy Security property.  Single
-        // directory entry, no pseudo-directories (".", "..", leading/trailing
-        // path separators). normalize()/getParent() will help later.
-        String javaHomeProperty = System.getProperty("java.home");
-        String cryptoPolicyProperty = Security.getProperty("crypto.policy");
-        Path cpPath = (cryptoPolicyProperty == null) ? null :
-                Paths.get(cryptoPolicyProperty);
+        String javaHomeDir = System.getProperty("java.home");
+        String sep = File.separator;
+        String pathToPolicyJar = javaHomeDir + sep + "lib" + sep +
+            "security" + sep;
 
-        if ((cpPath != null) && ((cpPath.getNameCount() != 1) ||
-                (cpPath.compareTo(cpPath.getFileName())) != 0)) {
-            throw new SecurityException(
-                    "Invalid policy directory name format: " +
-                            cryptoPolicyProperty);
-        }
-
-        if (cpPath == null) {
-            // Security property is not set, use default path
-            cpPath = Paths.get(javaHomeProperty, "lib", "security");
-        } else {
-            // populate with java.home
-            cpPath = Paths.get(javaHomeProperty, "lib", "security",
-                    "policy", cryptoPolicyProperty);
-        }
-
-        if (debug != null) {
-            debug.println("crypto policy directory: " + cpPath);
-        }
-
-        File exportJar = new File(cpPath.toFile(),"US_export_policy.jar");
-        File importJar = new File(cpPath.toFile(),"local_policy.jar");
-
-        if (cryptoPolicyProperty == null && (!exportJar.exists() ||
-                !importJar.exists())) {
-            // Compatibility set up. If crypto.policy is not defined.
-            // check to see if legacy jars exist in lib directory. If
-            // they don't exist, we default to limited policy mode.
-            cpPath = Paths.get(
-                    javaHomeProperty, "lib", "security", "policy", "limited");
-            // point to the new jar files in limited directory
-            exportJar = new File(cpPath.toFile(),"US_export_policy.jar");
-            importJar = new File(cpPath.toFile(),"local_policy.jar");
-        }
-
+        File exportJar = new File(pathToPolicyJar, "US_export_policy.jar");
+        File importJar = new File(pathToPolicyJar, "local_policy.jar");
         URL jceCipherURL = ClassLoader.getSystemResource
                 ("javax/crypto/Cipher.class");
 
diff --git a/jdk/src/share/classes/javax/security/auth/kerberos/KerberosTicket.java b/jdk/src/share/classes/javax/security/auth/kerberos/KerberosTicket.java
index 9a208a5..c9e2b28 100644
--- a/jdk/src/share/classes/javax/security/auth/kerberos/KerberosTicket.java
+++ b/jdk/src/share/classes/javax/security/auth/kerberos/KerberosTicket.java
@@ -377,7 +377,7 @@
      * @return true if this ticket is forwardable, false if not.
      */
     public final boolean isForwardable() {
-        return flags == null? false: flags[FORWARDABLE_TICKET_FLAG];
+        return flags[FORWARDABLE_TICKET_FLAG];
     }
 
     /**
@@ -389,7 +389,7 @@
      * false otherwise.
      */
     public final boolean isForwarded() {
-        return flags == null? false: flags[FORWARDED_TICKET_FLAG];
+        return flags[FORWARDED_TICKET_FLAG];
     }
 
     /**
@@ -398,7 +398,7 @@
      * @return true if this ticket is proxiable, false if not.
      */
     public final boolean isProxiable() {
-        return flags == null? false: flags[PROXIABLE_TICKET_FLAG];
+        return flags[PROXIABLE_TICKET_FLAG];
     }
 
     /**
@@ -407,7 +407,7 @@
      * @return true if this ticket is a proxy-ticket, false if not.
      */
     public final boolean isProxy() {
-        return flags == null? false: flags[PROXY_TICKET_FLAG];
+        return flags[PROXY_TICKET_FLAG];
     }
 
 
@@ -417,7 +417,7 @@
      * @return true if this ticket is post-dated, false if not.
      */
     public final boolean isPostdated() {
-        return flags == null? false: flags[POSTDATED_TICKET_FLAG];
+        return flags[POSTDATED_TICKET_FLAG];
     }
 
     /**
@@ -428,7 +428,7 @@
      * @return true if this ticket is renewable, false if not.
      */
     public final boolean isRenewable() {
-        return flags == null? false: flags[RENEWABLE_TICKET_FLAG];
+        return flags[RENEWABLE_TICKET_FLAG];
     }
 
     /**
@@ -439,7 +439,7 @@
      * protocol, false if not.
      */
     public final boolean isInitial() {
-        return flags == null? false: flags[INITIAL_TICKET_FLAG];
+        return flags[INITIAL_TICKET_FLAG];
     }
 
     /**
@@ -479,7 +479,7 @@
      * @return the expiration time for this ticket's validity period.
      */
     public final java.util.Date getEndTime() {
-        return (endTime == null) ? null : (Date) endTime.clone();
+        return (Date) endTime.clone();
     }
 
     /**
@@ -515,7 +515,7 @@
 
     /** Determines if this ticket is still current.  */
     public boolean isCurrent() {
-        return endTime == null? false: (System.currentTimeMillis() <= endTime.getTime());
+        return (System.currentTimeMillis() <= getEndTime().getTime());
     }
 
     /**
diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java
index bc8a2ba..95ea7f7 100644
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboBoxUI.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -125,6 +125,8 @@
     protected MouseMotionListener popupMouseMotionListener;
     protected KeyListener popupKeyListener;
 
+    private MouseWheelListener mouseWheelListener;
+
     // This is used for knowing when to cache the minimum preferred size.
     // If the data in the list changes, the cached value get marked for recalc.
     // Added to the current JComboBox model
@@ -375,6 +377,10 @@
                 comboBox.getModel().addListDataListener( listDataListener );
             }
         }
+
+        if ((mouseWheelListener = createMouseWheelListener()) != null) {
+            comboBox.addMouseWheelListener(mouseWheelListener);
+        }
     }
 
     /**
@@ -421,6 +427,9 @@
                 comboBox.getModel().removeListDataListener( listDataListener );
             }
         }
+        if (mouseWheelListener != null) {
+            comboBox.removeMouseWheelListener(mouseWheelListener);
+        }
     }
 
     /**
@@ -534,6 +543,10 @@
         return handler;
     }
 
+    private MouseWheelListener createMouseWheelListener() {
+        return getHandler();
+    }
+
     //
     // end UI Initialization
     //======================
@@ -1669,7 +1682,8 @@
     //
     private class Handler implements ActionListener, FocusListener,
                                      KeyListener, LayoutManager,
-                                     ListDataListener, PropertyChangeListener {
+                                     ListDataListener, PropertyChangeListener,
+                                     MouseWheelListener {
         //
         // PropertyChangeListener
         //
@@ -1953,6 +1967,10 @@
                 }
             }
         }
+
+        public void mouseWheelMoved(MouseWheelEvent e) {
+            e.consume();
+        }
    }
 
     class DefaultKeySelectionManager implements JComboBox.KeySelectionManager, UIResource {
diff --git a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java
index ae39867..682e6c6 100644
--- a/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java
+++ b/jdk/src/share/classes/javax/swing/plaf/basic/BasicComboPopup.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 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
@@ -345,26 +345,17 @@
     // PopupMenuListeners.
 
     protected void firePopupMenuWillBecomeVisible() {
-        if (scrollerMouseWheelListener != null) {
-            comboBox.addMouseWheelListener(scrollerMouseWheelListener);
-        }
         super.firePopupMenuWillBecomeVisible();
         // comboBox.firePopupMenuWillBecomeVisible() is called from BasicComboPopup.show() method
         // to let the user change the popup menu from the PopupMenuListener.popupMenuWillBecomeVisible()
     }
 
     protected void firePopupMenuWillBecomeInvisible() {
-        if (scrollerMouseWheelListener != null) {
-            comboBox.removeMouseWheelListener(scrollerMouseWheelListener);
-        }
         super.firePopupMenuWillBecomeInvisible();
         comboBox.firePopupMenuWillBecomeInvisible();
     }
 
     protected void firePopupMenuCanceled() {
-        if (scrollerMouseWheelListener != null) {
-            comboBox.removeMouseWheelListener(scrollerMouseWheelListener);
-        }
         super.firePopupMenuCanceled();
         comboBox.firePopupMenuCanceled();
     }
@@ -1006,8 +997,6 @@
             if (e.getStateChange() == ItemEvent.SELECTED) {
                 JComboBox comboBox = (JComboBox)e.getSource();
                 setListSelection(comboBox.getSelectedIndex());
-            } else {
-                setListSelection(-1);
             }
         }
 
diff --git a/jdk/src/share/classes/javax/swing/plaf/nimbus/skin.laf b/jdk/src/share/classes/javax/swing/plaf/nimbus/skin.laf
index da41a8b..208a3b0 100644
--- a/jdk/src/share/classes/javax/swing/plaf/nimbus/skin.laf
+++ b/jdk/src/share/classes/javax/swing/plaf/nimbus/skin.laf
@@ -13407,7 +13407,7 @@
             <cacheSettingsInherited>false</cacheSettingsInherited>
             <cacheMode>NO_CACHING</cacheMode>
             <uiproperties>
-               <uiProperty name="rendererUseListColors" type="BOOLEAN" value="false"/>
+               <uiProperty name="rendererUseListColors" type="BOOLEAN" value="true"/>
                <uiProperty name="rendererUseUIBorder" type="BOOLEAN" value="true"/>
                <uiProperty name="cellNoFocusBorder" type="BORDER">
                    <border type="empty" top="2" left="5" bottom="2" right="5"/>
@@ -13513,67 +13513,17 @@
                   <uiproperties/>
                </style>
                <backgroundStates>
-                  <state stateKeys="Selected">
-                     <style>
-                        <textForeground>
-                           <matte red="255" green="255" blue="255" alpha="255" uiDefaultParentName="nimbusLightBackground" hueOffset="0.0" saturationOffset="0.0" brightnessOffset="0.0" alphaOffset="0"/>
-                        </textForeground>
-                        <textBackground/>
-                        <background>
-                           <matte red="57" green="105" blue="138" alpha="255" uiDefaultParentName="nimbusSelectionBackground" hueOffset="0.0" saturationOffset="0.0" brightnessOffset="0.0" alphaOffset="0"/>
-                        </background>
-                        <inherit-textForeground>false</inherit-textForeground>
-                        <inherit-background>false</inherit-background>
-                        <uiproperties/>
-                     </style>
-                     <canvas>
-                        <size width="100" height="30"/>
-                        <nextLayerNameIndex>2</nextLayerNameIndex>
-                        <stretchingInsets top="0" bottom="0" left="0" right="0"/>
-                        <layer name="Layer 1">
-                           <opacity>1.0</opacity>
-                           <fillOpacity>1.0</fillOpacity>
-                           <blendingMode>NORMAL</blendingMode>
-                           <locked>false</locked>
-                           <visible>true</visible>
-                           <shapes/>
-                           <effects/>
-                        </layer>
-                     </canvas>
-                  </state>
-                  <state stateKeys="Disabled+Selected">
-                     <style>
-                        <textForeground/>
-                        <textBackground/>
-                        <background>
-                           <matte red="57" green="105" blue="138" alpha="255" uiDefaultParentName="nimbusSelectionBackground" hueOffset="0.0" saturationOffset="0.0" brightnessOffset="0.0" alphaOffset="0"/>
-                        </background>
-                        <inherit-background>false</inherit-background>
-                        <uiproperties/>
-                     </style>
-                     <canvas>
-                        <size width="100" height="30"/>
-                        <nextLayerNameIndex>2</nextLayerNameIndex>
-                        <stretchingInsets top="0" bottom="0" left="0" right="0"/>
-                        <layer name="Layer 1">
-                           <opacity>1.0</opacity>
-                           <fillOpacity>1.0</fillOpacity>
-                           <blendingMode>NORMAL</blendingMode>
-                           <locked>false</locked>
-                           <visible>true</visible>
-                           <shapes/>
-                           <effects/>
-                        </layer>
-                     </canvas>
-                  </state>
                   <state stateKeys="Disabled">
                      <style>
                         <textForeground>
                            <matte red="142" green="143" blue="145" alpha="255" uiDefaultParentName="nimbusDisabledText" hueOffset="0.0" saturationOffset="0.0" brightnessOffset="0.0" alphaOffset="0"/>
                         </textForeground>
                         <textBackground/>
-                        <background/>
+                        <background>
+                           <matte red="57" green="105" blue="138" alpha="255" uiDefaultParentName="nimbusSelectionBackground" hueOffset="0.0" saturationOffset="0.0" brightnessOffset="0.0" alphaOffset="0"/>
+                        </background>
                         <inherit-textForeground>false</inherit-textForeground>
+                        <inherit-background>false</inherit-background>
                         <uiproperties/>
                      </style>
                      <canvas>
diff --git a/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java b/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java
index 21f5703..7912446 100644
--- a/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java
+++ b/jdk/src/share/classes/javax/swing/text/html/parser/Parser.java
@@ -1986,69 +1986,57 @@
         while (true) {
             int i = 0;
             while (!insideComment && i < SCRIPT_END_TAG.length
-                    && (SCRIPT_END_TAG[i] == ch
-                    || SCRIPT_END_TAG_UPPER_CASE[i] == ch)) {
+                       && (SCRIPT_END_TAG[i] == ch
+                           || SCRIPT_END_TAG_UPPER_CASE[i] == ch)) {
                 charsToAdd[i] = (char) ch;
                 ch = readCh();
                 i++;
             }
             if (i == SCRIPT_END_TAG.length) {
-                return;
-            }
 
-            if (!insideComment && i == 1 && charsToAdd[0] == START_COMMENT.charAt(0)) {
-                // it isn't end script tag, but may be it's start comment tag?
-                while (i < START_COMMENT.length()
-                        && START_COMMENT.charAt(i) == ch) {
-                    charsToAdd[i] = (char) ch;
-                    ch = readCh();
-                    i++;
-                }
-                if (i == START_COMMENT.length()) {
-                    insideComment = true;
-                }
-            }
-            if (insideComment) {
-                while (i < END_COMMENT.length()
-                        && END_COMMENT.charAt(i) == ch) {
-                    charsToAdd[i] = (char) ch;
-                    ch = readCh();
-                    i++;
-                }
-                if (i == END_COMMENT.length()) {
-                    insideComment = false;
-                }
-            }
-
-            /* To account for extra read()'s that happened */
-            for (int j = 0; j < i; j++) {
-                addString(charsToAdd[j]);
-            }
-            switch (ch) {
-            case -1:
-                error("eof.script");
+                /*  '</script>' tag detected */
+                /* Here, ch == the first character after </script> */
                 return;
-            case '\n':
-                ln++;
-                ch = readCh();
-                lfCount++;
-                addString('\n');
-                break;
-            case '\r':
-                ln++;
-                if ((ch = readCh()) == '\n') {
-                    ch = readCh();
-                    crlfCount++;
-                } else {
-                    crCount++;
+            } else {
+
+                /* To account for extra read()'s that happened */
+                for (int j = 0; j < i; j++) {
+                    addString(charsToAdd[j]);
                 }
-                addString('\n');
-                break;
-            default:
-                addString(ch);
-                ch = readCh();
-                break;
-            } // switch
+
+                switch (ch) {
+                case -1:
+                    error("eof.script");
+                    return;
+                case '\n':
+                    ln++;
+                    ch = readCh();
+                    lfCount++;
+                    addString('\n');
+                    break;
+                case '\r':
+                    ln++;
+                    if ((ch = readCh()) == '\n') {
+                        ch = readCh();
+                        crlfCount++;
+                    } else {
+                        crCount++;
+                    }
+                    addString('\n');
+                    break;
+                default:
+                    addString(ch);
+                    String str = new String(getChars(0, strpos));
+                    if (!insideComment && str.endsWith(START_COMMENT)) {
+                        insideComment = true;
+                    }
+                    if (insideComment && str.endsWith(END_COMMENT)) {
+                        insideComment = false;
+                    }
+                    ch = readCh();
+                    break;
+                } // switch
+            }
         } // while
     }
 
diff --git a/jdk/src/share/classes/sun/font/CompositeFont.java b/jdk/src/share/classes/sun/font/CompositeFont.java
index a7df046..45480ca 100644
--- a/jdk/src/share/classes/sun/font/CompositeFont.java
+++ b/jdk/src/share/classes/sun/font/CompositeFont.java
@@ -270,21 +270,10 @@
                 if (componentNames[slot] == null) {
                     componentNames[slot] = name;
                 } else if (!componentNames[slot].equalsIgnoreCase(name)) {
-                    /* If a component specifies the file with a bad font,
-                     * the corresponding slot will be initialized by
-                     * default physical font. In such case findFont2D may
-                     * return composite font which cannot be casted to
-                     * physical font.
-                     */
-                    try {
-                        components[slot] =
-                            (PhysicalFont) fm.findFont2D(componentNames[slot],
-                                                         style,
+                    components[slot] =
+                        (PhysicalFont) fm.findFont2D(componentNames[slot],
+                                                     style,
                                                 FontManager.PHYSICAL_FALLBACK);
-                    } catch (ClassCastException cce) {
-                        /* Assign default physical font to the slot */
-                        components[slot] = fm.getDefaultPhysicalFont();
-                    }
                 }
             }
             deferredInitialisation[slot] = false;
diff --git a/jdk/src/share/classes/sun/font/FontFamily.java b/jdk/src/share/classes/sun/font/FontFamily.java
index e319886..31f1425 100644
--- a/jdk/src/share/classes/sun/font/FontFamily.java
+++ b/jdk/src/share/classes/sun/font/FontFamily.java
@@ -335,10 +335,10 @@
         case Font.BOLD|Font.ITALIC:
             if (bolditalic != null) {
                 return bolditalic;
-            } else if (bold != null && bold.canDoStyle(style)) {
-                return bold;
             } else if (italic != null && italic.canDoStyle(style)) {
                     return italic;
+            } else if (bold != null && bold.canDoStyle(style)) {
+                    return italic;
             } else if (plain != null && plain.canDoStyle(style)) {
                     return plain;
             } else {
diff --git a/jdk/src/share/classes/sun/font/ScriptRunData.java b/jdk/src/share/classes/sun/font/ScriptRunData.java
index e72c856..d894014 100644
--- a/jdk/src/share/classes/sun/font/ScriptRunData.java
+++ b/jdk/src/share/classes/sun/font/ScriptRunData.java
@@ -44,7 +44,7 @@
         if (cp >= data[cache] && cp < data[cache+2]) {
             return data[cache+1];
         }
-        if ((cp >= CHAR_START) && (cp < CHAR_LIMIT)) {
+        if (cp >= CHAR_START & cp < CHAR_LIMIT) {
             int probe = dataPower;
             int index = 0;
 
diff --git a/jdk/src/share/classes/sun/java2d/opengl/OGLMaskFill.java b/jdk/src/share/classes/sun/java2d/opengl/OGLMaskFill.java
index ab053f1..b75d5a4 100644
--- a/jdk/src/share/classes/sun/java2d/opengl/OGLMaskFill.java
+++ b/jdk/src/share/classes/sun/java2d/opengl/OGLMaskFill.java
@@ -26,7 +26,6 @@
 package sun.java2d.opengl;
 
 import java.awt.Composite;
-import sun.java2d.InvalidPipeException;
 import sun.java2d.SunGraphics2D;
 import sun.java2d.loops.GraphicsPrimitive;
 import sun.java2d.loops.GraphicsPrimitiveMgr;
@@ -68,14 +67,7 @@
     protected void validateContext(SunGraphics2D sg2d,
                                    Composite comp, int ctxflags)
     {
-        OGLSurfaceData dstData;
-        try {
-            dstData = (OGLSurfaceData) sg2d.surfaceData;
-        } catch (ClassCastException e) {
-            throw new InvalidPipeException("wrong surface data type: " +
-                                           sg2d.surfaceData);
-        }
-
+        OGLSurfaceData dstData = (OGLSurfaceData)sg2d.surfaceData;
         OGLContext.validateContext(dstData, dstData,
                                    sg2d.getCompClip(), comp,
                                    null, sg2d.paint, sg2d, ctxflags);
diff --git a/jdk/src/share/classes/sun/java2d/pipe/BufferedContext.java b/jdk/src/share/classes/sun/java2d/pipe/BufferedContext.java
index 3475c43..4513c67 100644
--- a/jdk/src/share/classes/sun/java2d/pipe/BufferedContext.java
+++ b/jdk/src/share/classes/sun/java2d/pipe/BufferedContext.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 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
@@ -38,8 +38,6 @@
 import static sun.java2d.pipe.BufferedRenderPipe.BYTES_PER_SPAN;
 
 import java.lang.annotation.Native;
-import java.lang.ref.Reference;
-import java.lang.ref.WeakReference;
 
 /**
  * Base context class for managing state in a single-threaded rendering
@@ -89,11 +87,11 @@
      */
     protected static BufferedContext currentContext;
 
-    private Reference<AccelSurface> validSrcDataRef = new WeakReference<>(null);
-    private Reference<AccelSurface> validDstDataRef = new WeakReference<>(null);
-    private Reference<Region> validClipRef = new WeakReference<>(null);
-    private Reference<Composite> validCompRef = new WeakReference<>(null);
-    private Reference<Paint> validPaintRef = new WeakReference<>(null);
+    private AccelSurface    validatedSrcData;
+    private AccelSurface    validatedDstData;
+    private Region          validatedClip;
+    private Composite       validatedComp;
+    private Paint           validatedPaint;
     // renamed from isValidatedPaintAColor as part of a work around for 6764257
     private boolean         isValidatedPaintJustAColor;
     private int             validatedRGB;
@@ -129,9 +127,9 @@
                                        int flags)
     {
         // assert rq.lock.isHeldByCurrentThread();
-        BufferedContext context = dstData.getContext();
-        context.validate(srcData, dstData,
-                         clip, comp, xform, paint, sg2d, flags);
+        BufferedContext d3dc = dstData.getContext();
+        d3dc.validate(srcData, dstData,
+                      clip, comp, xform, paint, sg2d, flags);
     }
 
     /**
@@ -202,15 +200,13 @@
                 updatePaint = true;
                 isValidatedPaintJustAColor = true;
             }
-        } else if (validPaintRef.get() != paint) {
+        } else if (validatedPaint != paint) {
             updatePaint = true;
             // this should be set when we are switching from paint to color
             // in which case this condition will be true
             isValidatedPaintJustAColor = false;
         }
 
-        final AccelSurface validatedSrcData = validSrcDataRef.get();
-        final AccelSurface validatedDstData = validDstDataRef.get();
         if ((currentContext != this) ||
             (srcData != validatedSrcData) ||
             (dstData != validatedDstData))
@@ -232,12 +228,11 @@
             setSurfaces(srcData, dstData);
 
             currentContext = this;
-            validSrcDataRef = new WeakReference<>(srcData);
-            validDstDataRef = new WeakReference<>(dstData);
+            validatedSrcData = srcData;
+            validatedDstData = dstData;
         }
 
         // validate clip
-        final Region validatedClip = validClipRef.get();
         if ((clip != validatedClip) || updateClip) {
             if (clip != null) {
                 if (updateClip ||
@@ -253,13 +248,13 @@
             } else {
                 resetClip();
             }
-            validClipRef = new WeakReference<>(clip);
+            validatedClip = clip;
         }
 
         // validate composite (note that a change in the context flags
         // may require us to update the composite state, even if the
         // composite has not changed)
-        if ((comp != validCompRef.get()) || (flags != validatedFlags)) {
+        if ((comp != validatedComp) || (flags != validatedFlags)) {
             if (comp != null) {
                 setComposite(comp, flags);
             } else {
@@ -268,7 +263,7 @@
             // the paint state is dependent on the composite state, so make
             // sure we update the color below
             updatePaint = true;
-            validCompRef = new WeakReference<>(comp);
+            validatedComp = comp;
             validatedFlags = flags;
         }
 
@@ -302,7 +297,7 @@
             } else {
                 BufferedPaints.resetPaint(rq);
             }
-            validPaintRef = new WeakReference<>(paint);
+            validatedPaint = paint;
         }
 
         // mark dstData dirty
@@ -320,9 +315,9 @@
      * @see RenderQueue#lock
      * @see RenderQueue#unlock
      */
-    private void invalidateSurfaces() {
-        validSrcDataRef.clear();
-        validDstDataRef.clear();
+    public void invalidateSurfaces() {
+        validatedSrcData = null;
+        validatedDstData = null;
     }
 
     private void setSurfaces(AccelSurface srcData,
@@ -439,9 +434,9 @@
         resetClip();
         BufferedPaints.resetPaint(rq);
         invalidateSurfaces();
-        validCompRef.clear();
-        validClipRef.clear();
-        validPaintRef.clear();
+        validatedComp = null;
+        validatedClip = null;
+        validatedPaint = null;
         isValidatedPaintJustAColor = false;
         xformInUse = false;
     }
diff --git a/jdk/src/share/classes/sun/management/LazyCompositeData.java b/jdk/src/share/classes/sun/management/LazyCompositeData.java
index 1204da3..935f09a 100644
--- a/jdk/src/share/classes/sun/management/LazyCompositeData.java
+++ b/jdk/src/share/classes/sun/management/LazyCompositeData.java
@@ -27,7 +27,6 @@
 
 import java.io.Serializable;
 import java.util.*;
-import javax.management.openmbean.ArrayType;
 import javax.management.openmbean.CompositeData;
 import javax.management.openmbean.CompositeType;
 import javax.management.openmbean.OpenType;
@@ -49,48 +48,39 @@
     private CompositeData compositeData;
 
     // Implementation of the CompositeData interface
-    @Override
     public boolean containsKey(String key) {
         return compositeData().containsKey(key);
     }
 
-    @Override
     public boolean containsValue(Object value) {
         return compositeData().containsValue(value);
     }
 
-    @Override
     public boolean equals(Object obj) {
         return compositeData().equals(obj);
     }
 
-    @Override
     public Object get(String key) {
         return compositeData().get(key);
     }
 
-    @Override
     public Object[] getAll(String[] keys) {
         return compositeData().getAll(keys);
     }
 
-    @Override
     public CompositeType getCompositeType() {
         return compositeData().getCompositeType();
     }
 
-    @Override
     public int hashCode() {
         return compositeData().hashCode();
     }
 
-    @Override
     public String toString() {
         /** FIXME: What should this be?? */
         return compositeData().toString();
     }
 
-    @Override
     public Collection<?> values() {
         return compositeData().values();
     }
@@ -136,31 +126,27 @@
         if (cd == null)
             throw new IllegalArgumentException("Null CompositeData");
 
-        return ((Boolean) cd.get(itemName));
+        return ((Boolean) cd.get(itemName)).booleanValue();
     }
 
     static long getLong(CompositeData cd, String itemName) {
         if (cd == null)
             throw new IllegalArgumentException("Null CompositeData");
 
-        return ((Long) cd.get(itemName));
+        return ((Long) cd.get(itemName)).longValue();
     }
 
     static int getInt(CompositeData cd, String itemName) {
         if (cd == null)
             throw new IllegalArgumentException("Null CompositeData");
 
-        return ((Integer) cd.get(itemName));
+        return ((Integer) cd.get(itemName)).intValue();
     }
 
     /**
      * Compares two CompositeTypes and returns true if
      * all items in type1 exist in type2 and their item types
      * are the same.
-     * @param type1 the base composite type
-     * @param type2 the checked composite type
-     * @return {@code true} if all items in type1 exist in type2 and their item
-     *         types are the same.
      */
     protected static boolean isTypeMatched(CompositeType type1, CompositeType type2) {
         if (type1 == type2) return true;
@@ -173,9 +159,24 @@
         if (!type2.keySet().containsAll(allItems))
             return false;
 
-        return allItems.stream().allMatch(
-            item -> isTypeMatched(type1.getType(item), type2.getType(item))
-        );
+        for (String item: allItems) {
+            OpenType<?> ot1 = type1.getType(item);
+            OpenType<?> ot2 = type2.getType(item);
+            if (ot1 instanceof CompositeType) {
+                if (! (ot2 instanceof CompositeType))
+                    return false;
+                if (!isTypeMatched((CompositeType) ot1, (CompositeType) ot2))
+                    return false;
+            } else if (ot1 instanceof TabularType) {
+                if (! (ot2 instanceof TabularType))
+                    return false;
+                if (!isTypeMatched((TabularType) ot1, (TabularType) ot2))
+                    return false;
+            } else if (!ot1.equals(ot2)) {
+                return false;
+            }
+        }
+        return true;
     }
 
     protected static boolean isTypeMatched(TabularType type1, TabularType type2) {
@@ -191,41 +192,5 @@
         return isTypeMatched(type1.getRowType(), type2.getRowType());
     }
 
-    protected static boolean isTypeMatched(ArrayType<?> type1, ArrayType<?> type2) {
-        if (type1 == type2) return true;
-
-        int dim1 = type1.getDimension();
-        int dim2 = type2.getDimension();
-
-        // check if the array dimensions are the same
-        if (dim1 != dim2)
-            return false;
-
-        return isTypeMatched(type1.getElementOpenType(), type2.getElementOpenType());
-    }
-
-    private static boolean isTypeMatched(OpenType<?> ot1, OpenType<?> ot2) {
-        if (ot1 instanceof CompositeType) {
-            if (! (ot2 instanceof CompositeType))
-                return false;
-            if (!isTypeMatched((CompositeType) ot1, (CompositeType) ot2))
-                return false;
-        } else if (ot1 instanceof TabularType) {
-            if (! (ot2 instanceof TabularType))
-                return false;
-            if (!isTypeMatched((TabularType) ot1, (TabularType) ot2))
-                return false;
-        } else if (ot1 instanceof ArrayType) {
-            if (! (ot2 instanceof ArrayType))
-                return false;
-            if (!isTypeMatched((ArrayType<?>) ot1, (ArrayType<?>) ot2)) {
-                return false;
-            }
-        } else if (!ot1.equals(ot2)) {
-            return false;
-        }
-        return true;
-    }
-
     private static final long serialVersionUID = -2190411934472666714L;
 }
diff --git a/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java b/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java
index 4822c10..0f4bf3f 100644
--- a/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java
+++ b/jdk/src/share/classes/sun/net/ftp/impl/FtpClient.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2009, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2009, 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
@@ -1708,7 +1708,7 @@
      */
     public InputStream nameList(String path) throws sun.net.ftp.FtpProtocolException, IOException {
         Socket s;
-        s = openDataConnection(path == null ? "NLST" : "NLST " + path);
+        s = openDataConnection("NLST " + path);
         if (s != null) {
             return createInputStream(s.getInputStream());
         }
diff --git a/jdk/src/share/classes/sun/net/spi/DefaultProxySelector.java b/jdk/src/share/classes/sun/net/spi/DefaultProxySelector.java
index 36db753..f7018ed 100644
--- a/jdk/src/share/classes/sun/net/spi/DefaultProxySelector.java
+++ b/jdk/src/share/classes/sun/net/spi/DefaultProxySelector.java
@@ -32,14 +32,13 @@
 import java.net.URI;
 import java.util.ArrayList;
 import java.util.List;
+import java.util.StringTokenizer;
 import java.io.IOException;
+import sun.misc.RegexpPool;
 import java.security.AccessController;
 import java.security.PrivilegedAction;
-import java.util.StringJoiner;
-import java.util.regex.Pattern;
 import sun.net.NetProperties;
 import sun.net.SocksProxy;
-import static java.util.regex.Pattern.quote;
 
 /**
  * Supports proxy settings using system properties This proxy selector
@@ -108,7 +107,7 @@
 
     /**
      * How to deal with "non proxy hosts":
-     * since we do have to generate a pattern we don't want to do that if
+     * since we do have to generate a RegexpPool we don't want to do that if
      * it's not necessary. Therefore we do cache the result, on a per-protocol
      * basis, and change it only when the "source", i.e. the system property,
      * did change.
@@ -120,17 +119,17 @@
         static final String defStringVal = "localhost|127.*|[::1]|0.0.0.0|[::0]";
 
         String hostsSource;
-        Pattern pattern;
+        RegexpPool hostsPool;
         final String property;
         final String defaultVal;
         static NonProxyInfo ftpNonProxyInfo = new NonProxyInfo("ftp.nonProxyHosts", null, null, defStringVal);
         static NonProxyInfo httpNonProxyInfo = new NonProxyInfo("http.nonProxyHosts", null, null, defStringVal);
         static NonProxyInfo socksNonProxyInfo = new NonProxyInfo("socksNonProxyHosts", null, null, defStringVal);
 
-        NonProxyInfo(String p, String s, Pattern pattern, String d) {
+        NonProxyInfo(String p, String s, RegexpPool pool, String d) {
             property = p;
             hostsSource = s;
-            this.pattern = pattern;
+            hostsPool = pool;
             defaultVal = d;
         }
     }
@@ -256,7 +255,7 @@
                                             nphosts = nprop.defaultVal;
                                         } else {
                                             nprop.hostsSource = null;
-                                            nprop.pattern = null;
+                                            nprop.hostsPool = null;
                                         }
                                     } else if (nphosts.length() != 0) {
                                         // add the required default patterns
@@ -267,11 +266,20 @@
                                     }
                                     if (nphosts != null) {
                                         if (!nphosts.equals(nprop.hostsSource)) {
-                                            nprop.pattern = toPattern(nphosts);
+                                            RegexpPool pool = new RegexpPool();
+                                            StringTokenizer st = new StringTokenizer(nphosts, "|", false);
+                                            try {
+                                                while (st.hasMoreTokens()) {
+                                                    pool.add(st.nextToken().toLowerCase(), Boolean.TRUE);
+                                                }
+                                            } catch (sun.misc.REException ex) {
+                                            }
+                                            nprop.hostsPool = pool;
                                             nprop.hostsSource = nphosts;
                                         }
                                     }
-                                    if (shouldNotUseProxyFor(nprop.pattern, urlhost)) {
+                                    if (nprop.hostsPool != null &&
+                                        nprop.hostsPool.match(urlhost) != null) {
                                         return Proxy.NO_PROXY;
                                     }
                                 }
@@ -347,49 +355,4 @@
 
     private native static boolean init();
     private synchronized native Proxy getSystemProxy(String protocol, String host);
-
-    /**
-     * @return {@code true} if given this pattern for non-proxy hosts and this
-     *         urlhost the proxy should NOT be used to access this urlhost
-     */
-    static boolean shouldNotUseProxyFor(Pattern pattern, String urlhost) {
-        if (pattern == null || urlhost.isEmpty())
-            return false;
-        boolean matches = pattern.matcher(urlhost).matches();
-        return matches;
-    }
-
-    /**
-     * @param mask non-null mask
-     * @return {@link java.util.regex.Pattern} corresponding to this mask
-     *         or {@code null} in case mask should not match anything
-     */
-    static Pattern toPattern(String mask) {
-        boolean disjunctionEmpty = true;
-        StringJoiner joiner = new StringJoiner("|");
-        for (String disjunct : mask.split("\\|")) {
-            if (disjunct.isEmpty())
-                continue;
-            disjunctionEmpty = false;
-            String regex = disjunctToRegex(disjunct.toLowerCase());
-            joiner.add(regex);
-        }
-        return disjunctionEmpty ? null : Pattern.compile(joiner.toString());
-    }
-
-    /**
-     * @param disjunct non-null mask disjunct
-     * @return java regex string corresponding to this mask
-     */
-    static String disjunctToRegex(String disjunct) {
-        String regex;
-        if (disjunct.startsWith("*")) {
-            regex = ".*" + quote(disjunct.substring(1));
-        } else if (disjunct.endsWith("*")) {
-            regex = quote(disjunct.substring(0, disjunct.length() - 1)) + ".*";
-        } else {
-            regex = quote(disjunct);
-        }
-        return regex;
-    }
 }
diff --git a/jdk/src/share/classes/sun/net/www/protocol/jar/JarURLConnection.java b/jdk/src/share/classes/sun/net/www/protocol/jar/JarURLConnection.java
index d7c4424..509b712 100644
--- a/jdk/src/share/classes/sun/net/www/protocol/jar/JarURLConnection.java
+++ b/jdk/src/share/classes/sun/net/www/protocol/jar/JarURLConnection.java
@@ -125,9 +125,7 @@
              * to get the jarFile, and set it as our permission.
              */
             if (getUseCaches()) {
-                boolean oldUseCaches = jarFileURLConnection.getUseCaches();
                 jarFileURLConnection = factory.getConnection(jarFile);
-                jarFileURLConnection.setUseCaches(oldUseCaches);
             }
 
             if ((entryName != null)) {
diff --git a/jdk/src/share/classes/sun/reflect/annotation/AnnotationType.java b/jdk/src/share/classes/sun/reflect/annotation/AnnotationType.java
index 92f600d..aa0cbe9 100644
--- a/jdk/src/share/classes/sun/reflect/annotation/AnnotationType.java
+++ b/jdk/src/share/classes/sun/reflect/annotation/AnnotationType.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -118,22 +118,16 @@
         members = new HashMap<String, Method>(methods.length+1, 1.0f);
 
         for (Method method :  methods) {
-            if (Modifier.isPublic(method.getModifiers()) &&
-                Modifier.isAbstract(method.getModifiers()) &&
-                !method.isSynthetic()) {
-                if (method.getParameterTypes().length != 0) {
-                    throw new IllegalArgumentException(method + " has params");
-                }
-                String name = method.getName();
-                Class<?> type = method.getReturnType();
-                memberTypes.put(name, invocationHandlerReturnType(type));
-                members.put(name, method);
+            if (method.getParameterTypes().length != 0)
+                throw new IllegalArgumentException(method + " has params");
+            String name = method.getName();
+            Class<?> type = method.getReturnType();
+            memberTypes.put(name, invocationHandlerReturnType(type));
+            members.put(name, method);
 
-                Object defaultValue = method.getDefaultValue();
-                if (defaultValue != null) {
-                    memberDefaults.put(name, defaultValue);
-                }
-            }
+            Object defaultValue = method.getDefaultValue();
+            if (defaultValue != null)
+                memberDefaults.put(name, defaultValue);
         }
 
         // Initialize retention, & inherited fields.  Special treatment
diff --git a/jdk/src/share/classes/sun/security/jca/ProviderConfig.java b/jdk/src/share/classes/sun/security/jca/ProviderConfig.java
index 7294269..62f8bdd 100644
--- a/jdk/src/share/classes/sun/security/jca/ProviderConfig.java
+++ b/jdk/src/share/classes/sun/security/jca/ProviderConfig.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 2009, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -255,15 +255,6 @@
                         disableLoad();
                     }
                     return null;
-                } catch (ExceptionInInitializerError err) {
-                    // unexpected exception thrown from static initialization block in provider
-                    // (ex: insufficient permission to initialize provider class)
-                    if (debug != null) {
-                        debug.println("Error loading provider " + ProviderConfig.this);
-                        err.printStackTrace();
-                    }
-                    disableLoad();
-                    return null;
                 }
             }
         });
diff --git a/jdk/src/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java b/jdk/src/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java
index 02ce5e0..536f927 100644
--- a/jdk/src/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java
+++ b/jdk/src/share/classes/sun/security/jgss/krb5/Krb5InitCredential.java
@@ -235,11 +235,8 @@
      */
     public int getInitLifetime() throws GSSException {
         int retVal = 0;
-        Date d = getEndTime();
-        if (d == null) {
-            return 0;
-        }
-        retVal = (int)(d.getTime() - (new Date().getTime()));
+        retVal = (int)(getEndTime().getTime()
+                       - (new Date().getTime()));
 
         return retVal/1000;
     }
diff --git a/jdk/src/share/classes/sun/security/krb5/Config.java b/jdk/src/share/classes/sun/security/krb5/Config.java
index 7ee9231..129f774 100644
--- a/jdk/src/share/classes/sun/security/krb5/Config.java
+++ b/jdk/src/share/classes/sun/security/krb5/Config.java
@@ -525,9 +525,9 @@
                 String previous = null;
                 while ((line = br.readLine()) != null) {
                     line = line.trim();
-                    if (line.isEmpty() || line.startsWith("#") || line.startsWith(";")) {
+                    if (line.startsWith("#") || line.isEmpty()) {
                         // ignore comments and blank line
-                        // Comments start with '#' or ';'
+                        // Comments start with #.
                         continue;
                     }
                     // In practice, a subsection might look like:
diff --git a/jdk/src/share/classes/sun/security/krb5/KrbKdcRep.java b/jdk/src/share/classes/sun/security/krb5/KrbKdcRep.java
index 66ce73a..dd0e951 100644
--- a/jdk/src/share/classes/sun/security/krb5/KrbKdcRep.java
+++ b/jdk/src/share/classes/sun/security/krb5/KrbKdcRep.java
@@ -62,8 +62,7 @@
             throw new KrbApErrException(Krb5.KRB_AP_ERR_MODIFIED);
         }
 
-        // We allow KDC to return a non-forwardable ticket if request has -f
-        for (int i = 2; i < 6; i++) {
+        for (int i = 1; i < 6; i++) {
             if (req.reqBody.kdcOptions.get(i) !=
                    rep.encKDCRepPart.flags.get(i)) {
                 if (Krb5.DEBUG) {
diff --git a/jdk/src/share/classes/sun/security/krb5/KrbTgsReq.java b/jdk/src/share/classes/sun/security/krb5/KrbTgsReq.java
index 85b7cb2..798b78d 100644
--- a/jdk/src/share/classes/sun/security/krb5/KrbTgsReq.java
+++ b/jdk/src/share/classes/sun/security/krb5/KrbTgsReq.java
@@ -150,11 +150,19 @@
         ctime = KerberosTime.now();
 
         // check if they are valid arguments. The optional fields
-        // should be consistent with settings in KDCOptions.
+        // should be  consistent with settings in KDCOptions.
+
+        // TODO: Is this necessary? If the TGT is not FORWARDABLE,
+        // you can still request for a FORWARDABLE ticket, just the
+        // KDC will give you a non-FORWARDABLE one. Even if you
+        // cannot use the ticket expected, it still contains info.
+        // This means there will be problem later. We already have
+        // flags check in KrbTgsRep. Of course, sometimes the KDC
+        // will not issue the ticket at all.
 
         if (options.get(KDCOptions.FORWARDABLE) &&
                 (!(asCreds.flags.get(Krb5.TKT_OPTS_FORWARDABLE)))) {
-            options.set(KDCOptions.FORWARDABLE, false);
+            throw new KrbException(Krb5.KRB_AP_ERR_REQ_OPTIONS);
         }
         if (options.get(KDCOptions.FORWARDED)) {
             if (!(asCreds.flags.get(KDCOptions.FORWARDABLE)))
diff --git a/jdk/src/share/classes/sun/security/krb5/PrincipalName.java b/jdk/src/share/classes/sun/security/krb5/PrincipalName.java
index 6d5ed3d..885e13c 100644
--- a/jdk/src/share/classes/sun/security/krb5/PrincipalName.java
+++ b/jdk/src/share/classes/sun/security/krb5/PrincipalName.java
@@ -424,9 +424,6 @@
                 } catch (UnknownHostException | SecurityException e) {
                     // not canonicalized or no permission to do so, use old
                 }
-                if (hostName.endsWith(".")) {
-                    hostName = hostName.substring(0, hostName.length() - 1);
-                }
                 nameParts[1] = hostName.toLowerCase(Locale.ENGLISH);
             }
             nameStrings = nameParts;
diff --git a/jdk/src/share/classes/sun/security/krb5/internal/CredentialsUtil.java b/jdk/src/share/classes/sun/security/krb5/internal/CredentialsUtil.java
index 14620e9..b6a3677 100644
--- a/jdk/src/share/classes/sun/security/krb5/internal/CredentialsUtil.java
+++ b/jdk/src/share/classes/sun/security/krb5/internal/CredentialsUtil.java
@@ -58,9 +58,6 @@
             // TODO: we do not support kerberos referral now
             throw new KrbException("Cross realm impersonation not supported");
         }
-        if (!ccreds.isForwardable()) {
-            throw new KrbException("S4U2self needs a FORWARDABLE ticket");
-        }
         KrbTgsReq req = new KrbTgsReq(
                 ccreds,
                 ccreds.getClient(),
@@ -71,9 +68,6 @@
         if (!creds.getClient().equals(client)) {
             throw new KrbException("S4U2self request not honored by KDC");
         }
-        if (!creds.isForwardable()) {
-            throw new KrbException("S4U2self ticket must be FORWARDABLE");
-        }
         return creds;
     }
 
diff --git a/jdk/src/share/classes/sun/security/pkcs/SignerInfo.java b/jdk/src/share/classes/sun/security/pkcs/SignerInfo.java
index 78d3f63..d93a09f 100644
--- a/jdk/src/share/classes/sun/security/pkcs/SignerInfo.java
+++ b/jdk/src/share/classes/sun/security/pkcs/SignerInfo.java
@@ -498,23 +498,6 @@
         return unauthenticatedAttributes;
     }
 
-    /**
-     * Returns the timestamp PKCS7 data unverified.
-     * @return a PKCS7 object
-     */
-    public PKCS7 getTsToken() throws IOException {
-        if (unauthenticatedAttributes == null) {
-            return null;
-        }
-        PKCS9Attribute tsTokenAttr =
-                unauthenticatedAttributes.getAttribute(
-                        PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
-        if (tsTokenAttr == null) {
-            return null;
-        }
-        return new PKCS7((byte[])tsTokenAttr.getValue());
-    }
-
     /*
      * Extracts a timestamp from a PKCS7 SignerInfo.
      *
@@ -542,12 +525,19 @@
         if (timestamp != null || !hasTimestamp)
             return timestamp;
 
-        PKCS7 tsToken = getTsToken();
-        if (tsToken == null) {
+        if (unauthenticatedAttributes == null) {
+            hasTimestamp = false;
+            return null;
+        }
+        PKCS9Attribute tsTokenAttr =
+            unauthenticatedAttributes.getAttribute(
+                PKCS9Attribute.SIGNATURE_TIMESTAMP_TOKEN_OID);
+        if (tsTokenAttr == null) {
             hasTimestamp = false;
             return null;
         }
 
+        PKCS7 tsToken = new PKCS7((byte[])tsTokenAttr.getValue());
         // Extract the content (an encoded timestamp token info)
         byte[] encTsTokenInfo = tsToken.getContentInfo().getData();
         // Extract the signer (the Timestamping Authority)
diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java b/jdk/src/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java
index 068f00a..4adac8c 100644
--- a/jdk/src/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11KeyPairGenerator.java
@@ -228,34 +228,29 @@
         // check native range first
         if ((minKeySize != -1) && (keySize < minKeySize)) {
             throw new InvalidAlgorithmParameterException(algorithm +
-                " key must be at least " + minKeySize + " bits. " +
-                "The specific key size " + keySize + " is not supported");
+                " key must be at least " + minKeySize + " bits");
         }
         if ((maxKeySize != -1) && (keySize > maxKeySize)) {
             throw new InvalidAlgorithmParameterException(algorithm +
-                " key must be at most " + maxKeySize + " bits. " +
-                "The specific key size " + keySize + " is not supported");
+                " key must be at most " + maxKeySize + " bits");
         }
 
         // check our own algorithm-specific limits also
         if (algorithm.equals("EC")) {
             if (keySize < 112) {
-                    throw new InvalidAlgorithmParameterException(
-                    "EC key size must be at least 112 bit. " +
-                    "The specific key size " + keySize + " is not supported");
+                throw new InvalidAlgorithmParameterException
+                    ("Key size must be at least 112 bit");
             }
             if (keySize > 2048) {
                 // sanity check, nobody really wants keys this large
-                throw new InvalidAlgorithmParameterException(
-                    "EC key size must be at most 2048 bit. " +
-                    "The specific key size " + keySize + " is not supported");
+                throw new InvalidAlgorithmParameterException
+                    ("Key size must be at most 2048 bit");
             }
         } else {
             // RSA, DH, DSA
             if (keySize < 512) {
-                throw new InvalidAlgorithmParameterException(algorithm +
-                    " key size must be at least 512 bit. " +
-                    "The specific key size " + keySize + " is not supported");
+                throw new InvalidAlgorithmParameterException
+                    ("Key size must be at least 512 bit");
             }
             if (algorithm.equals("RSA")) {
                 BigInteger tmpExponent = rsaPublicExponent;
@@ -276,10 +271,8 @@
                 if (algorithm.equals("DH") && (params != null)) {
                     // sanity check, nobody really wants keys this large
                     if (keySize > 64 * 1024) {
-                        throw new InvalidAlgorithmParameterException(
-                            "DH key size must be at most 65536 bit. " +
-                            "The specific key size " +
-                            keySize + " is not supported");
+                        throw new InvalidAlgorithmParameterException
+                            ("Key size must be at most 65536 bit");
                     }
                 } else {
                     // this restriction is in the spec for DSA
@@ -289,9 +282,7 @@
                         ((keySize > 1024) || ((keySize & 0x3f) != 0))) {
                         throw new InvalidAlgorithmParameterException(algorithm +
                             " key must be multiples of 64 if less than 1024 bits" +
-                            ", or 2048 bits. " +
-                            "The specific key size " +
-                            keySize + " is not supported");
+                            ", or 2048 bits");
                     }
                 }
             }
diff --git a/jdk/src/share/classes/sun/security/pkcs11/P11KeyStore.java b/jdk/src/share/classes/sun/security/pkcs11/P11KeyStore.java
index e5b8fa8..32002c2 100644
--- a/jdk/src/share/classes/sun/security/pkcs11/P11KeyStore.java
+++ b/jdk/src/share/classes/sun/security/pkcs11/P11KeyStore.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -752,21 +752,6 @@
             } else {
                 login(new PasswordCallbackHandler(password));
             }
-        } catch(LoginException e) {
-            Throwable cause = e.getCause();
-            if (cause instanceof PKCS11Exception) {
-                PKCS11Exception pe = (PKCS11Exception) cause;
-                if (pe.getErrorCode() == CKR_PIN_INCORRECT) {
-                    // if password is wrong, the cause of the IOException
-                    // should be an UnrecoverableKeyException
-                    throw new IOException("load failed",
-                            new UnrecoverableKeyException().initCause(e));
-                }
-            }
-            throw new IOException("load failed", e);
-        }
-
-        try {
             if (mapLabels() == true) {
                 // CKA_LABELs are shared by multiple certs
                 writeDisabled = true;
@@ -774,7 +759,7 @@
             if (debug != null) {
                 dumpTokenMap();
             }
-        } catch (KeyStoreException | PKCS11Exception e) {
+        } catch (LoginException | KeyStoreException | PKCS11Exception e) {
             throw new IOException("load failed", e);
         }
     }
diff --git a/jdk/src/share/classes/sun/security/pkcs12/PKCS12KeyStore.java b/jdk/src/share/classes/sun/security/pkcs12/PKCS12KeyStore.java
index dd3e060..25fc78c 100644
--- a/jdk/src/share/classes/sun/security/pkcs12/PKCS12KeyStore.java
+++ b/jdk/src/share/classes/sun/security/pkcs12/PKCS12KeyStore.java
@@ -2051,7 +2051,7 @@
                 }
 
                 if (!MessageDigest.isEqual(macData.getDigest(), macResult)) {
-                   throw new UnrecoverableKeyException("Failed PKCS12" +
+                   throw new SecurityException("Failed PKCS12" +
                                         " integrity checking");
                 }
            } catch (Exception e) {
diff --git a/jdk/src/share/classes/sun/security/provider/ByteArrayAccess.java b/jdk/src/share/classes/sun/security/provider/ByteArrayAccess.java
index e57ba14..e06832b 100644
--- a/jdk/src/share/classes/sun/security/provider/ByteArrayAccess.java
+++ b/jdk/src/share/classes/sun/security/provider/ByteArrayAccess.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 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
@@ -94,7 +94,7 @@
         String arch = java.security.AccessController.doPrivileged
             (new sun.security.action.GetPropertyAction("os.arch", ""));
         return arch.equals("i386") || arch.equals("x86") || arch.equals("amd64")
-            || arch.equals("x86_64") || arch.equals("ppc64") || arch.equals("ppc64le");
+            || arch.equals("x86_64");
     }
 
     /**
diff --git a/jdk/src/share/classes/sun/security/smartcardio/TerminalImpl.java b/jdk/src/share/classes/sun/security/smartcardio/TerminalImpl.java
index 604fac3..de1410f 100644
--- a/jdk/src/share/classes/sun/security/smartcardio/TerminalImpl.java
+++ b/jdk/src/share/classes/sun/security/smartcardio/TerminalImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 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
@@ -75,10 +75,10 @@
             }
         }
         try {
-            card = new CardImpl(this, protocol);
+            card =  new CardImpl(this, protocol);
             return card;
         } catch (PCSCException e) {
-            if (e.code == SCARD_W_REMOVED_CARD || e.code == SCARD_E_NO_SMARTCARD) {
+            if (e.code == SCARD_W_REMOVED_CARD) {
                 throw new CardNotPresentException("No card present", e);
             } else {
                 throw new CardException("connect() failed", e);
diff --git a/jdk/src/share/classes/sun/security/ssl/CipherBox.java b/jdk/src/share/classes/sun/security/ssl/CipherBox.java
index ec5880b..fa11bce 100644
--- a/jdk/src/share/classes/sun/security/ssl/CipherBox.java
+++ b/jdk/src/share/classes/sun/security/ssl/CipherBox.java
@@ -1044,6 +1044,40 @@
         return nonce;
     }
 
+    /*
+     * Is this cipher available?
+     *
+     * This method can only be called by CipherSuite.BulkCipher.isAvailable()
+     * to test the availability of a cipher suites.  Please DON'T use it in
+     * other places, otherwise, the behavior may be unexpected because we may
+     * initialize AEAD cipher improperly in the method.
+     */
+    Boolean isAvailable() {
+        // We won't know whether a cipher for a particular key size is
+        // available until the cipher is successfully initialized.
+        //
+        // We do not initialize AEAD cipher in the constructor.  Need to
+        // initialize the cipher to ensure that the AEAD mode for a
+        // particular key size is supported.
+        if (cipherType == AEAD_CIPHER) {
+            try {
+                Authenticator authenticator =
+                    new Authenticator(protocolVersion);
+                byte[] nonce = authenticator.sequenceNumber();
+                byte[] iv = Arrays.copyOf(fixedIv,
+                                            fixedIv.length + nonce.length);
+                System.arraycopy(nonce, 0, iv, fixedIv.length, nonce.length);
+                GCMParameterSpec spec = new GCMParameterSpec(tagSize * 8, iv);
+
+                cipher.init(mode, key, spec, random);
+            } catch (Exception e) {
+                return Boolean.FALSE;
+            }
+        }   // Otherwise, we have initialized the cipher in the constructor.
+
+        return Boolean.TRUE;
+    }
+
     /**
      * Sanity check the length of a fragment before decryption.
      *
diff --git a/jdk/src/share/classes/sun/security/ssl/CipherSuite.java b/jdk/src/share/classes/sun/security/ssl/CipherSuite.java
index 677a7e1..740cdd6 100644
--- a/jdk/src/share/classes/sun/security/ssl/CipherSuite.java
+++ b/jdk/src/share/classes/sun/security/ssl/CipherSuite.java
@@ -75,6 +75,12 @@
     // minimum priority for default enabled CipherSuites
     final static int DEFAULT_SUITES_PRIORITY = 300;
 
+    // Flag indicating if CipherSuite availability can change dynamically.
+    // This is the case when we rely on a JCE cipher implementation that
+    // may not be available in the installed JCE providers.
+    // It is true because we might not have an ECC implementation.
+    final static boolean DYNAMIC_AVAILABILITY = true;
+
     private final static boolean ALLOW_ECC = Debug.getBooleanProperty
         ("com.sun.net.ssl.enableECC", true);
 
@@ -180,6 +186,9 @@
      * Return whether this CipherSuite is available for use. A
      * CipherSuite may be unavailable even if it is supported
      * (i.e. allowed == true) if the required JCE cipher is not installed.
+     * In some configuration, this situation may change over time, call
+     * CipherSuiteList.clearAvailableCache() before this method to obtain
+     * the most current status.
      */
     boolean isAvailable() {
         return allowed && keyExchange.isAvailable() && cipher.isAvailable();
@@ -395,6 +404,10 @@
      */
     final static class BulkCipher {
 
+        // Map BulkCipher -> Boolean(available)
+        private final static Map<BulkCipher,Boolean> availableCache =
+                                            new HashMap<>(8);
+
         // descriptive name including key size, e.g. AES/128
         final String description;
 
@@ -438,9 +451,6 @@
         // The secure random used to detect the cipher availability.
         private final static SecureRandom secureRandom;
 
-        // runtime availability
-        private final boolean isAvailable;
-
         static {
             try {
                 secureRandom = JsseJce.getSecureRandom();
@@ -465,17 +475,6 @@
 
             this.expandedKeySize = expandedKeySize;
             this.exportable = true;
-
-            // availability of this bulk cipher
-            //
-            // Currently all supported ciphers except AES are always available
-            // via the JSSE internal implementations. We also assume AES/128 of
-            // CBC mode is always available since it is shipped with the SunJCE
-            // provider.  However, AES/256 is unavailable when the default JCE
-            // policy jurisdiction files are installed because of key length
-            // restrictions.
-            this.isAvailable =
-                    allowed ? isUnlimited(keySize, transformation) : false;
         }
 
         BulkCipher(String transformation, CipherType cipherType, int keySize,
@@ -492,17 +491,6 @@
 
             this.expandedKeySize = keySize;
             this.exportable = false;
-
-            // availability of this bulk cipher
-            //
-            // Currently all supported ciphers except AES are always available
-            // via the JSSE internal implementations. We also assume AES/128 of
-            // CBC mode is always available since it is shipped with the SunJCE
-            // provider.  However, AES/256 is unavailable when the default JCE
-            // policy jurisdiction files are installed because of key length
-            // restrictions.
-            this.isAvailable =
-                    allowed ? isUnlimited(keySize, transformation) : false;
         }
 
         /**
@@ -520,29 +508,86 @@
 
         /**
          * Test if this bulk cipher is available. For use by CipherSuite.
+         *
+         * Currently all supported ciphers except AES are always available
+         * via the JSSE internal implementations. We also assume AES/128 of
+         * CBC mode is always available since it is shipped with the SunJCE
+         * provider.  However, AES/256 is unavailable when the default JCE
+         * policy jurisdiction files are installed because of key length
+         * restrictions, and AEAD is unavailable when the underlying providers
+         * do not support AEAD/GCM mode.
          */
         boolean isAvailable() {
-            return this.isAvailable;
-        }
-
-        private static boolean isUnlimited(int keySize, String transformation) {
-            int keySizeInBits = keySize * 8;
-            if (keySizeInBits > 128) {    // need the JCE unlimited
-                                          // strength jurisdiction policy
-                try {
-                    if (Cipher.getMaxAllowedKeyLength(
-                            transformation) < keySizeInBits) {
-
-                        return false;
-                    }
-                } catch (Exception e) {
-                    return false;
-                }
+            if (allowed == false) {
+                return false;
             }
 
+            if ((this == B_AES_256) ||
+                    (this.cipherType == CipherType.AEAD_CIPHER)) {
+                return isAvailable(this);
+            }
+
+            // always available
             return true;
         }
 
+        // for use by CipherSuiteList.clearAvailableCache();
+        static synchronized void clearAvailableCache() {
+            if (DYNAMIC_AVAILABILITY) {
+                availableCache.clear();
+            }
+        }
+
+        private static synchronized boolean isAvailable(BulkCipher cipher) {
+            Boolean b = availableCache.get(cipher);
+            if (b == null) {
+                int keySizeInBits = cipher.keySize * 8;
+                if (keySizeInBits > 128) {    // need the JCE unlimited
+                                               // strength jurisdiction policy
+                    try {
+                        if (Cipher.getMaxAllowedKeyLength(
+                                cipher.transformation) < keySizeInBits) {
+                            b = Boolean.FALSE;
+                        }
+                    } catch (Exception e) {
+                        b = Boolean.FALSE;
+                    }
+                }
+
+                if (b == null) {
+                    b = Boolean.FALSE;          // may be reset to TRUE if
+                                                // the cipher is available
+                    CipherBox temporary = null;
+                    try {
+                        SecretKey key = new SecretKeySpec(
+                                            new byte[cipher.expandedKeySize],
+                                            cipher.algorithm);
+                        IvParameterSpec iv;
+                        if (cipher.cipherType == CipherType.AEAD_CIPHER) {
+                            iv = new IvParameterSpec(
+                                            new byte[cipher.fixedIvSize]);
+                        } else {
+                            iv = new IvParameterSpec(new byte[cipher.ivSize]);
+                        }
+                        temporary = cipher.newCipher(
+                                            ProtocolVersion.DEFAULT,
+                                            key, iv, secureRandom, true);
+                        b = temporary.isAvailable();
+                    } catch (NoSuchAlgorithmException e) {
+                        // not available
+                    } finally {
+                        if (temporary != null) {
+                            temporary.dispose();
+                        }
+                    }
+                }
+
+                availableCache.put(cipher, b);
+            }
+
+            return b.booleanValue();
+        }
+
         @Override
         public String toString() {
             return description;
diff --git a/jdk/src/share/classes/sun/security/ssl/CipherSuiteList.java b/jdk/src/share/classes/sun/security/ssl/CipherSuiteList.java
index 491bffa..19dc90f 100644
--- a/jdk/src/share/classes/sun/security/ssl/CipherSuiteList.java
+++ b/jdk/src/share/classes/sun/security/ssl/CipherSuiteList.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, 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
@@ -74,12 +74,24 @@
             throw new IllegalArgumentException("CipherSuites may not be null");
         }
         cipherSuites = new ArrayList<CipherSuite>(names.length);
+        // refresh available cache once if a CipherSuite is not available
+        // (maybe new JCE providers have been installed)
+        boolean refreshed = false;
         for (int i = 0; i < names.length; i++) {
             String suiteName = names[i];
             CipherSuite suite = CipherSuite.valueOf(suiteName);
             if (suite.isAvailable() == false) {
-                throw new IllegalArgumentException("Cannot support "
-                    + suiteName + " with currently installed providers");
+                if (refreshed == false) {
+                    // clear the cache so that the isAvailable() call below
+                    // does a full check
+                    clearAvailableCache();
+                    refreshed = true;
+                }
+                // still missing?
+                if (suite.isAvailable() == false) {
+                    throw new IllegalArgumentException("Cannot support "
+                        + suiteName + " with currently installed providers");
+                }
             }
             cipherSuites.add(suite);
         }
@@ -183,4 +195,16 @@
         }
         s.putBytes16(suiteBytes);
     }
+
+    /**
+     * Clear cache of available ciphersuites. If we support all ciphers
+     * internally, there is no need to clear the cache and calling this
+     * method has no effect.
+     */
+    static synchronized void clearAvailableCache() {
+        if (CipherSuite.DYNAMIC_AVAILABILITY) {
+            CipherSuite.BulkCipher.clearAvailableCache();
+            JsseJce.clearEcAvailable();
+        }
+    }
 }
diff --git a/jdk/src/share/classes/sun/security/ssl/JsseJce.java b/jdk/src/share/classes/sun/security/ssl/JsseJce.java
index 923ae8e..4c98772 100644
--- a/jdk/src/share/classes/sun/security/ssl/JsseJce.java
+++ b/jdk/src/share/classes/sun/security/ssl/JsseJce.java
@@ -55,6 +55,11 @@
 
     private final static ProviderList fipsProviderList;
 
+    // Flag indicating whether EC crypto is available.
+    // If null, then we have not checked yet.
+    // If yes, then all the EC based crypto we need is available.
+    private static Boolean ecAvailable;
+
     // Flag indicating whether Kerberos crypto is available.
     // If true, then all the Kerberos-based crypto we need is available.
     private final static boolean kerberosAvailable;
@@ -190,8 +195,24 @@
         // no instantiation of this class
     }
 
-    static boolean isEcAvailable() {
-        return EcAvailability.isAvailable;
+    synchronized static boolean isEcAvailable() {
+        if (ecAvailable == null) {
+            try {
+                JsseJce.getSignature(SIGNATURE_ECDSA);
+                JsseJce.getSignature(SIGNATURE_RAWECDSA);
+                JsseJce.getKeyAgreement("ECDH");
+                JsseJce.getKeyFactory("EC");
+                JsseJce.getKeyPairGenerator("EC");
+                ecAvailable = true;
+            } catch (Exception e) {
+                ecAvailable = false;
+            }
+        }
+        return ecAvailable;
+    }
+
+    synchronized static void clearEcAvailable() {
+        ecAvailable = null;
     }
 
     static boolean isKerberosAvailable() {
@@ -393,27 +414,4 @@
         }
     }
 
-
-    // lazy initialization holder class idiom for static default parameters
-    //
-    // See Effective Java Second Edition: Item 71.
-    private static class EcAvailability {
-        // Is EC crypto available?
-        private final static boolean isAvailable;
-
-        static {
-            boolean mediator = true;
-            try {
-                JsseJce.getSignature(SIGNATURE_ECDSA);
-                JsseJce.getSignature(SIGNATURE_RAWECDSA);
-                JsseJce.getKeyAgreement("ECDH");
-                JsseJce.getKeyFactory("EC");
-                JsseJce.getKeyPairGenerator("EC");
-            } catch (Exception e) {
-                mediator = false;
-            }
-
-            isAvailable = mediator;
-        }
-    }
 }
diff --git a/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java b/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java
index 09dd4cb..783146c 100644
--- a/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java
+++ b/jdk/src/share/classes/sun/security/ssl/RSAClientKeyExchange.java
@@ -90,30 +90,6 @@
     }
 
     /*
-     * Retrieving the cipher's provider name for the debug purposes
-     * can throw an exception by itself.
-     */
-    private static String safeProviderName(Cipher cipher) {
-        try {
-            return cipher.getProvider().toString();
-        } catch (Exception e) {
-            if (debug != null && Debug.isOn("handshake")) {
-                System.out.println("Retrieving The Cipher provider name" +
-                        " caused exception " + e.getMessage());
-            }
-        }
-        try {
-            return cipher.toString() + " (provider name not available)";
-        } catch (Exception e) {
-            if (debug != null && Debug.isOn("handshake")) {
-                System.out.println("Retrieving The Cipher name" +
-                        " caused exception " + e.getMessage());
-            }
-        }
-        return "(cipher/provider names not available)";
-    }
-
-    /*
      * Server gets the PKCS #1 (block format 02) data, decrypts
      * it with its private key.
      */
@@ -154,19 +130,15 @@
                         cipher.getProvider().getName());
             } catch (InvalidKeyException | UnsupportedOperationException iue) {
                 if (debug != null && Debug.isOn("handshake")) {
-                    System.out.println("The Cipher provider "
-                            + safeProviderName(cipher)
-                            + " caused exception: " + iue.getMessage());
+                    System.out.println("The Cipher provider " +
+                        cipher.getProvider().getName() +
+                        " caused exception: " + iue.getMessage());
                 }
 
                 needFailover = true;
             }
 
             if (needFailover) {
-                // The cipher might be spoiled by unsuccessful call to init(),
-                // so request a fresh instance
-                cipher = JsseJce.getCipher(JsseJce.CIPHER_RSA_PKCS1);
-
                 // Use DECRYPT_MODE and dispose the previous initialization.
                 cipher.init(Cipher.DECRYPT_MODE, privateKey);
                 boolean failed = false;
@@ -255,13 +227,7 @@
 
     @Override
     void print(PrintStream s) throws IOException {
-        String version = "version not available/extractable";
-
-        byte[] ba = preMaster.getEncoded();
-        if (ba != null && ba.length >= 2) {
-            version = ProtocolVersion.valueOf(ba[0], ba[1]).name;
-        }
-
-        s.println("*** ClientKeyExchange, RSA PreMasterSecret, " + version);
+        s.println("*** ClientKeyExchange, RSA PreMasterSecret, " +
+                                                        protocolVersion);
     }
 }
diff --git a/jdk/src/share/classes/sun/security/ssl/SSLContextImpl.java b/jdk/src/share/classes/sun/security/ssl/SSLContextImpl.java
index f8a1cf0..b00a26d 100644
--- a/jdk/src/share/classes/sun/security/ssl/SSLContextImpl.java
+++ b/jdk/src/share/classes/sun/security/ssl/SSLContextImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1999, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1999, 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
@@ -52,6 +52,16 @@
     private X509TrustManager trustManager;
     private SecureRandom secureRandom;
 
+    // supported and default protocols
+    private ProtocolList defaultServerProtocolList;
+    private ProtocolList defaultClientProtocolList;
+    private ProtocolList supportedProtocolList;
+
+    // supported and default cipher suites
+    private CipherSuiteList defaultServerCipherSuiteList;
+    private CipherSuiteList defaultClientCipherSuiteList;
+    private CipherSuiteList supportedCipherSuiteList;
+
     SSLContextImpl() {
         ephemeralKeyManager = new EphemeralKeyManager();
         clientCache = new SSLSessionContextImpl();
@@ -181,8 +191,6 @@
         }
         return new SSLServerSocketFactoryImpl(this);
     }
-    abstract SSLEngine createSSLEngineImpl();
-    abstract SSLEngine createSSLEngineImpl(String host, int port);
 
     @Override
     protected SSLEngine engineCreateSSLEngine() {
@@ -190,7 +198,7 @@
             throw new IllegalStateException(
                 "SSLContextImpl is not initialized");
         }
-        return createSSLEngineImpl();
+        return new SSLEngineImpl(this);
     }
 
     @Override
@@ -199,7 +207,7 @@
             throw new IllegalStateException(
                 "SSLContextImpl is not initialized");
         }
-        return createSSLEngineImpl(host, port);
+        return new SSLEngineImpl(this, host, port);
     }
 
     @Override
@@ -228,35 +236,78 @@
         return ephemeralKeyManager;
     }
 
+    abstract SSLParameters getDefaultServerSSLParams();
+    abstract SSLParameters getDefaultClientSSLParams();
+    abstract SSLParameters getSupportedSSLParams();
 
     // Get supported ProtocolList.
-    abstract ProtocolList getSuportedProtocolList();
+    ProtocolList getSuportedProtocolList() {
+        if (supportedProtocolList == null) {
+            supportedProtocolList =
+                new ProtocolList(getSupportedSSLParams().getProtocols());
+        }
 
-    // Get default ProtocolList for server mode.
-    abstract ProtocolList getServerDefaultProtocolList();
-
-    // Get default ProtocolList for client mode.
-    abstract ProtocolList getClientDefaultProtocolList();
-
-    // Get supported CipherSuiteList.
-    abstract CipherSuiteList getSupportedCipherSuiteList();
-
-    // Get default CipherSuiteList for server mode.
-    abstract CipherSuiteList getServerDefaultCipherSuiteList();
-
-    // Get default CipherSuiteList for client mode.
-    abstract CipherSuiteList getClientDefaultCipherSuiteList();
+        return supportedProtocolList;
+    }
 
     // Get default ProtocolList.
     ProtocolList getDefaultProtocolList(boolean roleIsServer) {
-        return roleIsServer ? getServerDefaultProtocolList()
-                : getClientDefaultProtocolList();
+        if (roleIsServer) {
+            if (defaultServerProtocolList == null) {
+                defaultServerProtocolList = new ProtocolList(
+                        getDefaultServerSSLParams().getProtocols());
+            }
+
+            return defaultServerProtocolList;
+        } else {
+            if (defaultClientProtocolList == null) {
+                defaultClientProtocolList = new ProtocolList(
+                        getDefaultClientSSLParams().getProtocols());
+            }
+
+            return defaultClientProtocolList;
+        }
+    }
+
+    // Get supported CipherSuiteList.
+    CipherSuiteList getSupportedCipherSuiteList() {
+        // The maintenance of cipher suites needs to be synchronized.
+        synchronized (this) {
+            // Clear cache of available ciphersuites.
+            clearAvailableCache();
+
+            if (supportedCipherSuiteList == null) {
+                supportedCipherSuiteList = getApplicableCipherSuiteList(
+                        getSuportedProtocolList(), false);
+            }
+
+            return supportedCipherSuiteList;
+        }
     }
 
     // Get default CipherSuiteList.
     CipherSuiteList getDefaultCipherSuiteList(boolean roleIsServer) {
-        return roleIsServer ? getServerDefaultCipherSuiteList()
-                : getClientDefaultCipherSuiteList();
+        // The maintenance of cipher suites needs to be synchronized.
+        synchronized (this) {
+            // Clear cache of available ciphersuites.
+            clearAvailableCache();
+
+            if (roleIsServer) {
+                if (defaultServerCipherSuiteList == null) {
+                    defaultServerCipherSuiteList = getApplicableCipherSuiteList(
+                        getDefaultProtocolList(true), true);
+                }
+
+                return defaultServerCipherSuiteList;
+            } else {
+                if (defaultClientCipherSuiteList == null) {
+                    defaultClientCipherSuiteList = getApplicableCipherSuiteList(
+                        getDefaultProtocolList(false), true);
+                }
+
+                return defaultClientCipherSuiteList;
+            }
+        }
     }
 
     /**
@@ -264,24 +315,16 @@
      * protocols.  See: SSLSocket/SSLEngine.setEnabledProtocols()
      */
     boolean isDefaultProtocolList(ProtocolList protocols) {
-        return (protocols == getServerDefaultProtocolList()) ||
-                (protocols == getClientDefaultProtocolList());
+        return (protocols == defaultServerProtocolList) ||
+               (protocols == defaultClientProtocolList);
     }
 
-    /**
-     * Return whether a protocol list is the original default enabled
-     * protocols.  See: SSLSocket/SSLEngine.setEnabledProtocols()
-     */
-    boolean isDefaultCipherSuiteList(CipherSuiteList cipherSuites) {
-        return (cipherSuites == getServerDefaultCipherSuiteList()) ||
-                (cipherSuites == getClientDefaultCipherSuiteList());
-    }
 
     /*
      * Return the list of all available CipherSuites with a priority of
      * minPriority or above.
      */
-    private static CipherSuiteList getApplicableCipherSuiteList(
+    private CipherSuiteList getApplicableCipherSuiteList(
             ProtocolList protocols, boolean onlyEnabled) {
 
         int minPriority = CipherSuite.SUPPORTED_SUITES_PRIORITY;
@@ -327,20 +370,22 @@
         return new CipherSuiteList(suites);
     }
 
-    private static String[] getAvailableProtocols(
-            ProtocolVersion[] protocolCandidates) {
-
-        List<String> availableProtocols = Collections.<String>emptyList();
-        if (protocolCandidates !=  null && protocolCandidates.length != 0) {
-            availableProtocols = new ArrayList<>(protocolCandidates.length);
-            for (ProtocolVersion p : protocolCandidates) {
-                if (ProtocolVersion.availableProtocols.contains(p)) {
-                    availableProtocols.add(p.name);
-                }
-            }
+    /**
+     * Clear cache of available ciphersuites. If we support all ciphers
+     * internally, there is no need to clear the cache and calling this
+     * method has no effect.
+     *
+     * Note that every call to clearAvailableCache() and the maintenance of
+     * cipher suites need to be synchronized with this instance.
+     */
+    private void clearAvailableCache() {
+        if (CipherSuite.DYNAMIC_AVAILABILITY) {
+            supportedCipherSuiteList = null;
+            defaultServerCipherSuiteList = null;
+            defaultClientCipherSuiteList = null;
+            CipherSuite.BulkCipher.clearAvailableCache();
+            JsseJce.clearEcAvailable();
         }
-
-        return availableProtocols.toArray(new String[0]);
     }
 
     /*
@@ -373,37 +418,39 @@
      */
 
     /*
-     * The base abstract SSLContext implementation for the Transport Layer
-     * Security (TLS) protocols.
+     * The base abstract SSLContext implementation.
      *
      * This abstract class encapsulates supported and the default server
-     * SSL/TLS parameters.
+     * SSL parameters.
      *
      * @see SSLContext
      */
-    private abstract static class AbstractTLSContext extends SSLContextImpl {
-        private static final ProtocolList supportedProtocolList;
-        private static final ProtocolList serverDefaultProtocolList;
-
-        private static final CipherSuiteList supportedCipherSuiteList;
-        private static final CipherSuiteList serverDefaultCipherSuiteList;
+    private abstract static class AbstractSSLContext extends SSLContextImpl {
+        // parameters
+        private static final SSLParameters defaultServerSSLParams;
+        private static final SSLParameters supportedSSLParams;
 
         static {
+            // supported SSL parameters
+            supportedSSLParams = new SSLParameters();
+
+            // candidates for available protocols
+            ProtocolVersion[] candidates;
+
             if (SunJSSE.isFIPS()) {
-                supportedProtocolList = new ProtocolList(new String[] {
+                supportedSSLParams.setProtocols(new String[] {
                     ProtocolVersion.TLS10.name,
                     ProtocolVersion.TLS11.name,
                     ProtocolVersion.TLS12.name
                 });
 
-                serverDefaultProtocolList = new ProtocolList(
-                        getAvailableProtocols(new ProtocolVersion[] {
+                candidates = new ProtocolVersion[] {
                     ProtocolVersion.TLS10,
                     ProtocolVersion.TLS11,
                     ProtocolVersion.TLS12
-                }));
+                };
             } else {
-                supportedProtocolList = new ProtocolList(new String[] {
+                supportedSSLParams.setProtocols(new String[] {
                     ProtocolVersion.SSL20Hello.name,
                     ProtocolVersion.SSL30.name,
                     ProtocolVersion.TLS10.name,
@@ -411,50 +458,44 @@
                     ProtocolVersion.TLS12.name
                 });
 
-                serverDefaultProtocolList = new ProtocolList(
-                        getAvailableProtocols(new ProtocolVersion[] {
+                candidates = new ProtocolVersion[] {
                     ProtocolVersion.SSL20Hello,
                     ProtocolVersion.SSL30,
                     ProtocolVersion.TLS10,
                     ProtocolVersion.TLS11,
                     ProtocolVersion.TLS12
-                }));
+                };
             }
 
-            supportedCipherSuiteList = getApplicableCipherSuiteList(
-                    supportedProtocolList, false);          // all supported
-            serverDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    serverDefaultProtocolList, true);       // enabled only
+            defaultServerSSLParams = new SSLParameters();
+            defaultServerSSLParams.setProtocols(
+                getAvailableProtocols(candidates).toArray(new String[0]));
         }
 
         @Override
-        ProtocolList getSuportedProtocolList() {
-            return supportedProtocolList;
+        SSLParameters getDefaultServerSSLParams() {
+            return defaultServerSSLParams;
         }
 
         @Override
-        CipherSuiteList getSupportedCipherSuiteList() {
-            return supportedCipherSuiteList;
+        SSLParameters getSupportedSSLParams() {
+            return supportedSSLParams;
         }
 
-        @Override
-        ProtocolList getServerDefaultProtocolList() {
-            return serverDefaultProtocolList;
-        }
+        static List<String> getAvailableProtocols(
+                ProtocolVersion[] protocolCandidates) {
 
-        @Override
-        CipherSuiteList getServerDefaultCipherSuiteList() {
-            return serverDefaultCipherSuiteList;
-        }
+            List<String> availableProtocols = Collections.<String>emptyList();
+            if (protocolCandidates !=  null && protocolCandidates.length != 0) {
+                availableProtocols = new ArrayList<>(protocolCandidates.length);
+                for (ProtocolVersion p : protocolCandidates) {
+                    if (ProtocolVersion.availableProtocols.contains(p)) {
+                        availableProtocols.add(p.name);
+                    }
+                }
+            }
 
-        @Override
-        SSLEngine createSSLEngineImpl() {
-            return new SSLEngineImpl(this);
-        }
-
-        @Override
-        SSLEngine createSSLEngineImpl(String host, int port) {
-            return new SSLEngineImpl(this, host, port);
+            return availableProtocols;
         }
     }
 
@@ -463,36 +504,31 @@
      *
      * @see SSLContext
      */
-    public static final class TLS10Context extends AbstractTLSContext {
-        private static final ProtocolList clientDefaultProtocolList;
-        private static final CipherSuiteList clientDefaultCipherSuiteList;
+    public static final class TLS10Context extends AbstractSSLContext {
+        private static final SSLParameters defaultClientSSLParams;
 
         static {
+            // candidates for available protocols
+            ProtocolVersion[] candidates;
             if (SunJSSE.isFIPS()) {
-                clientDefaultProtocolList = new ProtocolList(
-                        getAvailableProtocols(new ProtocolVersion[] {
+                candidates = new ProtocolVersion[] {
                     ProtocolVersion.TLS10
-                }));
+                };
             } else {
-                clientDefaultProtocolList = new ProtocolList(
-                        getAvailableProtocols(new ProtocolVersion[] {
+                candidates = new ProtocolVersion[] {
                     ProtocolVersion.SSL30,
                     ProtocolVersion.TLS10
-                }));
+                };
             }
 
-            clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    clientDefaultProtocolList, true);       // enabled only
+            defaultClientSSLParams = new SSLParameters();
+            defaultClientSSLParams.setProtocols(
+                getAvailableProtocols(candidates).toArray(new String[0]));
         }
 
         @Override
-        ProtocolList getClientDefaultProtocolList() {
-            return clientDefaultProtocolList;
-        }
-
-        @Override
-        CipherSuiteList getClientDefaultCipherSuiteList() {
-            return clientDefaultCipherSuiteList;
+        SSLParameters getDefaultClientSSLParams() {
+            return defaultClientSSLParams;
         }
     }
 
@@ -501,38 +537,33 @@
      *
      * @see SSLContext
      */
-    public static final class TLS11Context extends AbstractTLSContext {
-        private static final ProtocolList clientDefaultProtocolList;
-        private static final CipherSuiteList clientDefaultCipherSuiteList;
+    public static final class TLS11Context extends AbstractSSLContext {
+        private static final SSLParameters defaultClientSSLParams;
 
         static {
+            // candidates for available protocols
+            ProtocolVersion[] candidates;
             if (SunJSSE.isFIPS()) {
-                clientDefaultProtocolList = new ProtocolList(
-                        getAvailableProtocols(new ProtocolVersion[] {
+                candidates = new ProtocolVersion[] {
                     ProtocolVersion.TLS10,
                     ProtocolVersion.TLS11
-                }));
+                };
             } else {
-                clientDefaultProtocolList = new ProtocolList(
-                        getAvailableProtocols(new ProtocolVersion[] {
+                candidates = new ProtocolVersion[] {
                     ProtocolVersion.SSL30,
                     ProtocolVersion.TLS10,
                     ProtocolVersion.TLS11
-                }));
+                };
             }
 
-            clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    clientDefaultProtocolList, true);       // enabled only
+            defaultClientSSLParams = new SSLParameters();
+            defaultClientSSLParams.setProtocols(
+                getAvailableProtocols(candidates).toArray(new String[0]));
         }
 
         @Override
-        ProtocolList getClientDefaultProtocolList() {
-            return clientDefaultProtocolList;
-        }
-
-        @Override
-        CipherSuiteList getClientDefaultCipherSuiteList() {
-            return clientDefaultCipherSuiteList;
+        SSLParameters getDefaultClientSSLParams() {
+            return defaultClientSSLParams;
         }
     }
 
@@ -541,101 +572,35 @@
      *
      * @see SSLContext
      */
-    public static final class TLS12Context extends AbstractTLSContext {
-        private static final ProtocolList clientDefaultProtocolList;
-        private static final CipherSuiteList clientDefaultCipherSuiteList;
+    public static final class TLS12Context extends AbstractSSLContext {
+        private static final SSLParameters defaultClientSSLParams;
 
         static {
+            // candidates for available protocols
+            ProtocolVersion[] candidates;
             if (SunJSSE.isFIPS()) {
-                clientDefaultProtocolList = new ProtocolList(
-                        getAvailableProtocols(new ProtocolVersion[] {
+                candidates = new ProtocolVersion[] {
                     ProtocolVersion.TLS10,
                     ProtocolVersion.TLS11,
                     ProtocolVersion.TLS12
-                }));
+                };
             } else {
-                clientDefaultProtocolList = new ProtocolList(
-                        getAvailableProtocols(new ProtocolVersion[] {
+                candidates = new ProtocolVersion[] {
                     ProtocolVersion.SSL30,
                     ProtocolVersion.TLS10,
                     ProtocolVersion.TLS11,
                     ProtocolVersion.TLS12
-                }));
+                };
             }
 
-            clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                    clientDefaultProtocolList, true);       // enabled only
+            defaultClientSSLParams = new SSLParameters();
+            defaultClientSSLParams.setProtocols(
+                getAvailableProtocols(candidates).toArray(new String[0]));
         }
 
         @Override
-        ProtocolList getClientDefaultProtocolList() {
-            return clientDefaultProtocolList;
-        }
-
-        @Override
-        CipherSuiteList getClientDefaultCipherSuiteList() {
-            return clientDefaultCipherSuiteList;
-        }
-    }
-
-    /*
-     * The interface for the customized SSL/(D)TLS SSLContext.
-     *
-     * @see SSLContext
-     */
-    private static class CustomizedSSLProtocols {
-        private static final String PROPERTY_NAME = "jdk.tls.client.protocols";
-        static IllegalArgumentException reservedException = null;
-        static ArrayList<ProtocolVersion>
-                customizedProtocols = new ArrayList<>();
-
-        // Don't want a java.lang.LinkageError for illegal system property.
-        //
-        // Please don't throw exception in this static block.  Otherwise,
-        // java.lang.LinkageError may be thrown during the instantiation of
-        // the provider service. Instead, please handle the initialization
-        // exception in the caller's constructor.
-        static {
-            String property = AccessController.doPrivileged(
-                    new GetPropertyAction(PROPERTY_NAME));
-            if (property != null && property.length() != 0) {
-                // remove double quote marks from beginning/end of the property
-                if (property.length() > 1 && property.charAt(0) == '"' &&
-                        property.charAt(property.length() - 1) == '"') {
-                    property = property.substring(1, property.length() - 1);
-                }
-            }
-
-            if (property != null && property.length() != 0) {
-                String[] protocols = property.split(",");
-                for (int i = 0; i < protocols.length; i++) {
-                    protocols[i] = protocols[i].trim();
-                    // Is it a supported protocol name?
-                    try {
-                        ProtocolVersion pro =
-                                ProtocolVersion.valueOf(protocols[i]);
-
-                        if (SunJSSE.isFIPS() &&
-                                ((pro.v == ProtocolVersion.SSL30.v) ||
-                                        (pro.v == ProtocolVersion.SSL20Hello.v))) {
-                            reservedException = new IllegalArgumentException(
-                                    PROPERTY_NAME + ": " + pro +
-                                            " is not FIPS compliant");
-
-                            break;
-                        }
-
-                        // ignore duplicated protocols
-                        if (!customizedProtocols.contains(pro)) {
-                            customizedProtocols.add(pro);
-                        }
-                    } catch (IllegalArgumentException iae) {
-                        reservedException = new IllegalArgumentException(
-                                PROPERTY_NAME + ": " + protocols[i] +
-                                        " is not a standard SSL protocol name", iae);
-                    }
-                }
-            }
+        SSLParameters getDefaultClientSSLParams() {
+            return defaultClientSSLParams;
         }
     }
 
@@ -644,11 +609,9 @@
      *
      * @see SSLContext
      */
-    private static class CustomizedTLSContext extends AbstractTLSContext {
-
-        private static final ProtocolList clientDefaultProtocolList;
-        private static final CipherSuiteList clientDefaultCipherSuiteList;
-
+    private static class CustomizedSSLContext extends AbstractSSLContext {
+        private static final String PROPERTY_NAME = "jdk.tls.client.protocols";
+        private static final SSLParameters defaultClientSSLParams;
         private static IllegalArgumentException reservedException = null;
 
         // Don't want a java.lang.LinkageError for illegal system property.
@@ -658,65 +621,86 @@
         // the provider service. Instead, let's handle the initialization
         // exception in constructor.
         static {
-            reservedException = CustomizedSSLProtocols.reservedException;
-            if (reservedException == null) {
-                ArrayList<ProtocolVersion>
-                        customizedTLSProtocols = new ArrayList<>();
-                for (ProtocolVersion protocol :
-                        CustomizedSSLProtocols.customizedProtocols) {
-                        customizedTLSProtocols.add(protocol);
-                }
+            // candidates for available protocols
+            ProtocolVersion[] candidates;
 
-                // candidates for available protocols
-                ProtocolVersion[] candidates;
-                if (customizedTLSProtocols.isEmpty()) {
-                    // Use the default enabled client protocols if no
-                    // customized TLS protocols.
-                    if (SunJSSE.isFIPS()) {
-                        candidates = new ProtocolVersion[] {
-                                ProtocolVersion.TLS10,
-                                ProtocolVersion.TLS11,
-                                ProtocolVersion.TLS12
-                        };
-                    } else {
-                        candidates = new ProtocolVersion[] {
-                                ProtocolVersion.SSL30,
-                                ProtocolVersion.TLS10,
-                                ProtocolVersion.TLS11,
-                                ProtocolVersion.TLS12
-                        };
-                    }
+            String property = AccessController.doPrivileged(
+                    new GetPropertyAction(PROPERTY_NAME));
+            if (property == null || property.length() == 0) {
+                // the default enabled client TLS protocols
+                if (SunJSSE.isFIPS()) {
+                    candidates = new ProtocolVersion[] {
+                        ProtocolVersion.TLS10,
+                        ProtocolVersion.TLS11,
+                        ProtocolVersion.TLS12
+                    };
                 } else {
-                    // Use the customized TLS protocols.
-                    candidates =
-                            new ProtocolVersion[customizedTLSProtocols.size()];
-                    candidates = customizedTLSProtocols.toArray(candidates);
+                    candidates = new ProtocolVersion[] {
+                        ProtocolVersion.SSL30,
+                        ProtocolVersion.TLS10,
+                        ProtocolVersion.TLS11,
+                        ProtocolVersion.TLS12
+                    };
+                }
+            } else {
+                // remove double quote marks from beginning/end of the property
+                if (property.length() > 1 && property.charAt(0) == '"' &&
+                        property.charAt(property.length() - 1) == '"') {
+                    property = property.substring(1, property.length() - 1);
                 }
 
-                clientDefaultProtocolList = new ProtocolList(
-                        getAvailableProtocols(candidates));
-                clientDefaultCipherSuiteList = getApplicableCipherSuiteList(
-                        clientDefaultProtocolList, true);   // enabled only
-            } else {
-                clientDefaultProtocolList = null;       // unlikely to be used
-                clientDefaultCipherSuiteList = null;    // unlikely to be used
+                String[] protocols = null;
+                if (property != null && property.length() != 0) {
+                    protocols = property.split(",");
+                } else {
+                    reservedException = new IllegalArgumentException(
+                        "No protocol specified in " +
+                        PROPERTY_NAME + " system property");
+                    protocols = new String[0];
+                }
+
+                candidates = new ProtocolVersion[protocols.length];
+                for (int i = 0; i < protocols.length; i++) {
+                    protocols[i] = protocols[i].trim();
+                    // Is it a supported protocol name?
+                    try {
+                        candidates[i] = ProtocolVersion.valueOf(protocols[i]);
+                    } catch (IllegalArgumentException iae) {
+                        reservedException = new IllegalArgumentException(
+                            PROPERTY_NAME + ": " + protocols[i] +
+                            " is not a standard SSL/TLS protocol name", iae);
+                        break;
+                    }
+                }
+
+                if ((reservedException == null) && SunJSSE.isFIPS()) {
+                    for (ProtocolVersion protocolVersion : candidates) {
+                        if (ProtocolVersion.SSL20Hello.v == protocolVersion.v ||
+                                ProtocolVersion.SSL30.v == protocolVersion.v) {
+                            reservedException = new IllegalArgumentException(
+                                    PROPERTY_NAME + ": " + protocolVersion +
+                                    " is not FIPS compliant");
+                        }
+                    }
+                }
+            }
+
+            defaultClientSSLParams = new SSLParameters();
+            if (reservedException == null) {
+                defaultClientSSLParams.setProtocols(
+                    getAvailableProtocols(candidates).toArray(new String[0]));
             }
         }
 
-        protected CustomizedTLSContext() {
+        protected CustomizedSSLContext() {
             if (reservedException != null) {
                 throw reservedException;
             }
         }
 
         @Override
-        ProtocolList getClientDefaultProtocolList() {
-            return clientDefaultProtocolList;
-        }
-
-        @Override
-        CipherSuiteList getClientDefaultCipherSuiteList() {
-            return clientDefaultCipherSuiteList;
+        SSLParameters getDefaultClientSSLParams() {
+            return defaultClientSSLParams;
         }
     }
 
@@ -725,57 +709,75 @@
      *
      * @see SSLContext
      */
-    public static final class TLSContext extends CustomizedTLSContext {
+    public static final class TLSContext extends CustomizedSSLContext {
         // use the default constructor and methods
     }
 
-    // lazy initialization holder class idiom for static default parameters
-    //
-    // See Effective Java Second Edition: Item 71.
-    private static final class DefaultManagersHolder {
+    /*
+     * The SSLContext implementation for default "Default" algorithm
+     *
+     * @see SSLContext
+     */
+    public static final class DefaultSSLContext extends CustomizedSSLContext {
         private static final String NONE = "NONE";
         private static final String P11KEYSTORE = "PKCS11";
 
-        private static final TrustManager[] trustManagers;
-        private static final KeyManager[] keyManagers;
+        private static volatile SSLContextImpl defaultImpl;
 
-        static Exception reservedException = null;
+        private static TrustManager[] defaultTrustManagers;
+        private static KeyManager[] defaultKeyManagers;
 
-        static {
-            TrustManager[] tmMediator;
+        public DefaultSSLContext() throws Exception {
             try {
-                tmMediator = getTrustManagers();
+                super.engineInit(getDefaultKeyManager(),
+                        getDefaultTrustManager(), null);
             } catch (Exception e) {
-                reservedException = e;
-                tmMediator = new TrustManager[0];
-            }
-            trustManagers = tmMediator;
-
-            if (reservedException == null) {
-                KeyManager[] kmMediator;
-                try {
-                    kmMediator = getKeyManagers();
-                } catch (Exception e) {
-                    reservedException = e;
-                    kmMediator = new KeyManager[0];
+                if (debug != null && Debug.isOn("defaultctx")) {
+                    System.out.println("default context init failed: " + e);
                 }
-                keyManagers = kmMediator;
-            } else {
-                keyManagers = new KeyManager[0];
+                throw e;
+            }
+
+            if (defaultImpl == null) {
+                defaultImpl = this;
             }
         }
 
-        private static TrustManager[] getTrustManagers() throws Exception {
+        @Override
+        protected void engineInit(KeyManager[] km, TrustManager[] tm,
+            SecureRandom sr) throws KeyManagementException {
+            throw new KeyManagementException
+                ("Default SSLContext is initialized automatically");
+        }
+
+        static synchronized SSLContextImpl getDefaultImpl() throws Exception {
+            if (defaultImpl == null) {
+                new DefaultSSLContext();
+            }
+            return defaultImpl;
+        }
+
+        private static synchronized TrustManager[] getDefaultTrustManager()
+                throws Exception {
+            if (defaultTrustManagers != null) {
+                return defaultTrustManagers;
+            }
+
             KeyStore ks =
                 TrustManagerFactoryImpl.getCacertsKeyStore("defaultctx");
 
             TrustManagerFactory tmf = TrustManagerFactory.getInstance(
                 TrustManagerFactory.getDefaultAlgorithm());
             tmf.init(ks);
-            return tmf.getTrustManagers();
+            defaultTrustManagers = tmf.getTrustManagers();
+            return defaultTrustManagers;
         }
 
-        private static KeyManager[] getKeyManagers() throws Exception {
+        private static synchronized KeyManager[] getDefaultKeyManager()
+                throws Exception {
+            if (defaultKeyManagers != null) {
+                return defaultKeyManagers;
+            }
 
             final Map<String,String> props = new HashMap<>();
             AccessController.doPrivileged(
@@ -872,75 +874,11 @@
                 kmf.init(ks, passwd);
             }
 
-            return kmf.getKeyManagers();
+            defaultKeyManagers = kmf.getKeyManagers();
+            return defaultKeyManagers;
         }
     }
 
-    // lazy initialization holder class idiom for static default parameters
-    //
-    // See Effective Java Second Edition: Item 71.
-    private static final class DefaultSSLContextHolder {
-
-        private static final SSLContextImpl sslContext;
-        static Exception reservedException = null;
-
-        static {
-            SSLContextImpl mediator = null;
-            if (DefaultManagersHolder.reservedException != null) {
-                reservedException = DefaultManagersHolder.reservedException;
-            } else {
-                try {
-                    mediator = new DefaultSSLContext();
-                } catch (Exception e) {
-                    reservedException = e;
-                }
-            }
-
-            sslContext = mediator;
-        }
-    }
-
-    /*
-     * The SSLContext implementation for default "Default" algorithm
-     *
-     * @see SSLContext
-     */
-    public static final class DefaultSSLContext extends CustomizedTLSContext {
-
-        // public constructor for SSLContext.getInstance("Default")
-        public DefaultSSLContext() throws Exception {
-            if (DefaultManagersHolder.reservedException != null) {
-                throw DefaultManagersHolder.reservedException;
-            }
-
-            try {
-                super.engineInit(DefaultManagersHolder.keyManagers,
-                        DefaultManagersHolder.trustManagers, null);
-            } catch (Exception e) {
-                if (debug != null && Debug.isOn("defaultctx")) {
-                    System.out.println("default context init failed: " + e);
-                }
-                throw e;
-            }
-        }
-
-        @Override
-        protected void engineInit(KeyManager[] km, TrustManager[] tm,
-                                  SecureRandom sr) throws KeyManagementException {
-            throw new KeyManagementException
-                    ("Default SSLContext is initialized automatically");
-        }
-
-        static SSLContextImpl getDefaultImpl() throws Exception {
-            if (DefaultSSLContextHolder.reservedException != null) {
-                throw DefaultSSLContextHolder.reservedException;
-            }
-
-            return DefaultSSLContextHolder.sslContext;
-        }
-    }
-
-
 }
 
 
@@ -1115,7 +1053,7 @@
             }
         } catch (CertPathValidatorException cpve) {
             throw new CertificateException(
-                "Certificates do not conform to algorithm constraints", cpve);
+                "Certificates does not conform to algorithm constraints");
         }
     }
 }
diff --git a/jdk/src/share/classes/sun/security/ssl/SSLSocketImpl.java b/jdk/src/share/classes/sun/security/ssl/SSLSocketImpl.java
index 1fb35d6..6b98e93 100644
--- a/jdk/src/share/classes/sun/security/ssl/SSLSocketImpl.java
+++ b/jdk/src/share/classes/sun/security/ssl/SSLSocketImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 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
@@ -220,11 +220,6 @@
                                     Collections.<SNIServerName>emptyList();
     Collection<SNIMatcher>      sniMatchers =
                                     Collections.<SNIMatcher>emptyList();
-    // Is the serverNames set to empty with SSLParameters.setServerNames()?
-    private boolean             noSniExtension = false;
-
-    // Is the sniMatchers set to empty with SSLParameters.setSNIMatchers()?
-    private boolean             noSniMatcher = false;
 
     /*
      * READ ME * READ ME * READ ME * READ ME * READ ME * READ ME *
@@ -671,11 +666,6 @@
         }
 
         super.connect(endpoint, timeout);
-
-        if (host == null || host.length() == 0) {
-            useImplicitHost(false);
-        }
-
         doneConnect();
     }
 
@@ -2168,61 +2158,41 @@
         output.r.setVersion(protocolVersion);
     }
 
-    //
-    // ONLY used by ClientHandshaker for the server hostname during handshaking
-    //
     synchronized String getHost() {
         // Note that the host may be null or empty for localhost.
         if (host == null || host.length() == 0) {
-            useImplicitHost(true);
+            if (!trustNameService) {
+                // If the local name service is not trustworthy, reverse host
+                // name resolution should not be performed for endpoint
+                // identification.  Use the application original specified
+                // hostname or IP address instead.
+                host = getOriginalHostname(getInetAddress());
+            } else {
+                host = getInetAddress().getHostName();
+            }
         }
 
         return host;
     }
 
     /*
-     * Try to set and use the implicit specified hostname
+     * Get the original application specified hostname.
      */
-    private synchronized void useImplicitHost(boolean noSniUpdate) {
-
-        // Note: If the local name service is not trustworthy, reverse
-        // host name resolution should not be performed for endpoint
-        // identification.  Use the application original specified
-        // hostname or IP address instead.
-
-        // Get the original hostname via jdk.internal.misc.SharedSecrets
-        InetAddress inetAddress = getInetAddress();
-        if (inetAddress == null) {      // not connected
-            return;
-        }
-
+    private static String getOriginalHostname(InetAddress inetAddress) {
+        /*
+         * Get the original hostname via sun.misc.SharedSecrets.
+         */
         JavaNetAccess jna = SharedSecrets.getJavaNetAccess();
         String originalHostname = jna.getOriginalHostName(inetAddress);
-        if ((originalHostname != null) &&
-                (originalHostname.length() != 0)) {
 
-            host = originalHostname;
-            if (!noSniUpdate && serverNames.isEmpty() && !noSniExtension) {
-                serverNames =
-                        Utilities.addToSNIServerNameList(serverNames, host);
-
-                if (!roleIsServer &&
-                        (handshaker != null) && !handshaker.started()) {
-                    handshaker.setSNIServerNames(serverNames);
-                }
-            }
-
-            return;
+        /*
+         * If no application specified hostname, use the IP address.
+         */
+        if (originalHostname == null || originalHostname.length() == 0) {
+            originalHostname = inetAddress.getHostAddress();
         }
 
-        // No explicitly specified hostname, no server name indication.
-        if (!trustNameService) {
-            // The local name service is not trustworthy, use IP address.
-            host = inetAddress.getHostAddress();
-        } else {
-            // Use the underlying reverse host name resolution service.
-            host = getInetAddress().getHostName();
-        }
+        return originalHostname;
     }
 
 
@@ -2235,10 +2205,6 @@
         this.host = host;
         this.serverNames =
             Utilities.addToSNIServerNameList(this.serverNames, this.host);
-
-        if (!roleIsServer && (handshaker != null) && !handshaker.started()) {
-            handshaker.setSNIServerNames(serverNames);
-        }
     }
 
     /**
@@ -2605,21 +2571,8 @@
         // the super implementation does not handle the following parameters
         params.setEndpointIdentificationAlgorithm(identificationProtocol);
         params.setAlgorithmConstraints(algorithmConstraints);
-
-        if (sniMatchers.isEmpty() && !noSniMatcher) {
-            // 'null' indicates none has been set
-            params.setSNIMatchers(null);
-        } else {
-            params.setSNIMatchers(sniMatchers);
-        }
-
-        if (serverNames.isEmpty() && !noSniExtension) {
-            // 'null' indicates none has been set
-            params.setServerNames(null);
-        } else {
-            params.setServerNames(serverNames);
-        }
-
+        params.setSNIMatchers(sniMatchers);
+        params.setServerNames(serverNames);
         params.setUseCipherSuitesOrder(preferLocalCipherSuites);
 
         return params;
@@ -2639,13 +2592,11 @@
 
         List<SNIServerName> sniNames = params.getServerNames();
         if (sniNames != null) {
-            noSniExtension = sniNames.isEmpty();
             serverNames = sniNames;
         }
 
         Collection<SNIMatcher> matchers = params.getSNIMatchers();
         if (matchers != null) {
-            noSniMatcher = matchers.isEmpty();
             sniMatchers = matchers;
         }
 
diff --git a/jdk/src/share/classes/sun/security/ssl/ServerHandshaker.java b/jdk/src/share/classes/sun/security/ssl/ServerHandshaker.java
index 413256a..9caa64a 100644
--- a/jdk/src/share/classes/sun/security/ssl/ServerHandshaker.java
+++ b/jdk/src/share/classes/sun/security/ssl/ServerHandshaker.java
@@ -137,10 +137,8 @@
                 customizedDHKeySize = Integer.parseUnsignedInt(property);
                 if (customizedDHKeySize < 1024 || customizedDHKeySize > 2048) {
                     throw new IllegalArgumentException(
-                        "Unsupported customized DH key size: " +
-                        customizedDHKeySize + ". " +
-                        "The key size can only range from 1024" +
-                        " to 2048 (inclusive)");
+                        "Customized DH key size should be positive integer " +
+                        "between 1024 and 2048 bits, inclusive");
                 }
             } catch (NumberFormatException nfe) {
                 throw new IllegalArgumentException(
@@ -1025,18 +1023,11 @@
             if (trySetCipherSuite(suite) == false) {
                 continue;
             }
-
-            if (debug != null && Debug.isOn("handshake")) {
-                System.out.println("Standard ciphersuite chosen: " + suite);
-            }
             return;
         }
 
         for (CipherSuite suite : legacySuites) {
             if (trySetCipherSuite(suite)) {
-                if (debug != null && Debug.isOn("handshake")) {
-                    System.out.println("Legacy ciphersuite chosen: " + suite);
-                }
                 return;
             }
         }
diff --git a/jdk/src/share/classes/sun/security/tools/jarsigner/Main.java b/jdk/src/share/classes/sun/security/tools/jarsigner/Main.java
index 07962dc..961921c 100644
--- a/jdk/src/share/classes/sun/security/tools/jarsigner/Main.java
+++ b/jdk/src/share/classes/sun/security/tools/jarsigner/Main.java
@@ -53,9 +53,6 @@
 import java.security.cert.PKIXParameters;
 import java.security.cert.TrustAnchor;
 import java.util.Map.Entry;
-import sun.security.pkcs.PKCS7;
-import sun.security.pkcs.SignerInfo;
-import sun.security.timestamp.TimestampToken;
 import sun.security.tools.KeyStoreUtil;
 import sun.security.tools.PathList;
 import sun.security.x509.*;
@@ -100,15 +97,6 @@
 
     private static final long SIX_MONTHS = 180*24*60*60*1000L; //milliseconds
 
-    private static final DisabledAlgorithmConstraints DISABLED_CHECK =
-            new DisabledAlgorithmConstraints(
-                    DisabledAlgorithmConstraints.PROPERTY_JAR_DISABLED_ALGS);
-
-    private static final Set<CryptoPrimitive> DIGEST_PRIMITIVE_SET = Collections
-            .unmodifiableSet(EnumSet.of(CryptoPrimitive.MESSAGE_DIGEST));
-    private static final Set<CryptoPrimitive> SIG_PRIMITIVE_SET = Collections
-            .unmodifiableSet(EnumSet.of(CryptoPrimitive.SIGNATURE));
-
     // Attention:
     // This is the entry that get launched by the security tool jarsigner.
     public static void main(String args[]) throws Exception {
@@ -184,8 +172,6 @@
     private boolean badExtendedKeyUsage = false;
     private boolean badNetscapeCertType = false;
 
-    private boolean seeWeak = false;
-
     CertificateFactory certificateFactory;
     CertPathValidator validator;
     PKIXParameters pkixParameters;
@@ -591,10 +577,6 @@
     {
         boolean anySigned = false;  // if there exists entry inside jar signed
         JarFile jf = null;
-        Map<String,String> digestMap = new HashMap<>();
-        Map<String,PKCS7> sigMap = new HashMap<>();
-        Map<String,String> sigNameMap = new HashMap<>();
-        Map<String,String> unparsableSignatures = new HashMap<>();
 
         try {
             jf = new JarFile(jarName, true);
@@ -605,44 +587,17 @@
             while (entries.hasMoreElements()) {
                 JarEntry je = entries.nextElement();
                 entriesVec.addElement(je);
-                try (InputStream is = jf.getInputStream(je)) {
-                    String name = je.getName();
-                    if (signatureRelated(name)
-                            && SignatureFileVerifier.isBlockOrSF(name)) {
-                        String alias = name.substring(name.lastIndexOf('/') + 1,
-                                name.lastIndexOf('.'));
+                InputStream is = null;
                 try {
-                            if (name.endsWith(".SF")) {
-                                Manifest sf = new Manifest(is);
-                                boolean found = false;
-                                for (Object obj : sf.getMainAttributes().keySet()) {
-                                    String key = obj.toString();
-                                    if (key.endsWith("-Digest-Manifest")) {
-                                        digestMap.put(alias,
-                                                key.substring(0, key.length() - 16));
-                                        found = true;
-                                        break;
-                                    }
-                                }
-                                if (!found) {
-                                    unparsableSignatures.putIfAbsent(alias,
-                                        String.format(
-                                            rb.getString("history.unparsable"),
-                                            name));
-                                }
-                            } else {
-                                sigNameMap.put(alias, name);
-                                sigMap.put(alias, new PKCS7(is));
-                            }
-                        } catch (IOException ioe) {
-                            unparsableSignatures.putIfAbsent(alias, String.format(
-                                    rb.getString("history.unparsable"), name));
-                        }
-                    } else {
-                        while (is.read(buffer, 0, buffer.length) != -1) {
+                    is = jf.getInputStream(je);
+                    int n;
+                    while ((n = is.read(buffer, 0, buffer.length)) != -1) {
                         // we just read. this will throw a SecurityException
                         // if  a signature/digest check fails.
                     }
+                } finally {
+                    if (is != null) {
+                        is.close();
                     }
                 }
             }
@@ -801,106 +756,13 @@
                     System.out.println(rb.getString(
                         ".X.not.signed.by.specified.alias.es."));
                 }
-            }
-            if (man == null) {
                 System.out.println();
+            }
+            if (man == null)
                 System.out.println(rb.getString("no.manifest."));
-            }
-
-            // Even if the verbose option is not specified, all out strings
-            // must be generated so seeWeak can be updated.
-            if (!digestMap.isEmpty()
-                    || !sigMap.isEmpty()
-                    || !unparsableSignatures.isEmpty()) {
-                if (verbose != null) {
-                System.out.println();
-            }
-                for (String s : sigMap.keySet()) {
-                    if (!digestMap.containsKey(s)) {
-                        unparsableSignatures.putIfAbsent(s, String.format(
-                                rb.getString("history.nosf"), s));
-                    }
-                }
-                for (String s : digestMap.keySet()) {
-                    PKCS7 p7 = sigMap.get(s);
-                    if (p7 != null) {
-                        String history;
-                        try {
-                            SignerInfo si = p7.getSignerInfos()[0];
-                            X509Certificate signer = si.getCertificate(p7);
-                            String digestAlg = digestMap.get(s);
-                            String sigAlg = AlgorithmId.makeSigAlg(
-                                    si.getDigestAlgorithmId().getName(),
-                                    si.getDigestEncryptionAlgorithmId().getName());
-                            PublicKey key = signer.getPublicKey();
-                            PKCS7 tsToken = si.getTsToken();
-                            if (tsToken != null) {
-                                SignerInfo tsSi = tsToken.getSignerInfos()[0];
-                                X509Certificate tsSigner = tsSi.getCertificate(tsToken);
-                                byte[] encTsTokenInfo = tsToken.getContentInfo().getData();
-                                TimestampToken tsTokenInfo = new TimestampToken(encTsTokenInfo);
-                                PublicKey tsKey = tsSigner.getPublicKey();
-                                String tsDigestAlg = tsTokenInfo.getHashAlgorithm().getName();
-                                String tsSigAlg = AlgorithmId.makeSigAlg(
-                                        tsSi.getDigestAlgorithmId().getName(),
-                                        tsSi.getDigestEncryptionAlgorithmId().getName());
-                                Calendar c = Calendar.getInstance(
-                                        TimeZone.getTimeZone("UTC"),
-                                        Locale.getDefault(Locale.Category.FORMAT));
-                                c.setTime(tsTokenInfo.getDate());
-                                history = String.format(
-                                        rb.getString("history.with.ts"),
-                                        signer.getSubjectX500Principal(),
-                                        withWeak(digestAlg, DIGEST_PRIMITIVE_SET),
-                                        withWeak(sigAlg, SIG_PRIMITIVE_SET),
-                                        withWeak(key),
-                                        c,
-                                        tsSigner.getSubjectX500Principal(),
-                                        withWeak(tsDigestAlg, DIGEST_PRIMITIVE_SET),
-                                        withWeak(tsSigAlg, SIG_PRIMITIVE_SET),
-                                        withWeak(tsKey));
-                            } else {
-                                history = String.format(
-                                        rb.getString("history.without.ts"),
-                                        signer.getSubjectX500Principal(),
-                                        withWeak(digestAlg, DIGEST_PRIMITIVE_SET),
-                                        withWeak(sigAlg, SIG_PRIMITIVE_SET),
-                                        withWeak(key));
-                            }
-                        } catch (Exception e) {
-                            // The only usage of sigNameMap, remember the name
-                            // of the block file if it's invalid.
-                            history = String.format(
-                                    rb.getString("history.unparsable"),
-                                    sigNameMap.get(s));
-                        }
-                        if (verbose != null) {
-                            System.out.println(history);
-                        }
-                    } else {
-                        unparsableSignatures.putIfAbsent(s, String.format(
-                                rb.getString("history.nobk"), s));
-                    }
-                }
-                if (verbose != null) {
-                    for (String s : unparsableSignatures.keySet()) {
-                        System.out.println(unparsableSignatures.get(s));
-                    }
-                }
-            }
-            System.out.println();
 
             if (!anySigned) {
-                if (seeWeak) {
-                    if (verbose != null) {
-                        System.out.println(rb.getString("jar.treated.unsigned.see.weak.verbose"));
-                        System.out.println("\n  " +
-                                DisabledAlgorithmConstraints.PROPERTY_JAR_DISABLED_ALGS +
-                                "=" + Security.getProperty(DisabledAlgorithmConstraints.PROPERTY_JAR_DISABLED_ALGS));
-                    } else {
-                        System.out.println(rb.getString("jar.treated.unsigned.see.weak"));
-                    }
-                } else if (hasSignature) {
+                if (hasSignature) {
                     System.out.println(rb.getString("jar.treated.unsigned"));
                 } else {
                     System.out.println(rb.getString("jar.is.unsigned"));
@@ -1007,26 +869,6 @@
         System.exit(1);
     }
 
-    private String withWeak(String alg, Set<CryptoPrimitive> primitiveSet) {
-        if (DISABLED_CHECK.permits(primitiveSet, alg, null)) {
-            return alg;
-        } else {
-            seeWeak = true;
-            return String.format(rb.getString("with.weak"), alg);
-        }
-    }
-
-    private String withWeak(PublicKey key) {
-        if (DISABLED_CHECK.permits(SIG_PRIMITIVE_SET, key)) {
-            return String.format(
-                    rb.getString("key.bit"), KeyUtil.getKeySize(key));
-        } else {
-            seeWeak = true;
-            return String.format(
-                    rb.getString("key.bit.weak"), KeyUtil.getKeySize(key));
-        }
-    }
-
     private static MessageFormat validityTimeForm = null;
     private static MessageFormat notYetTimeForm = null;
     private static MessageFormat expiredTimeForm = null;
diff --git a/jdk/src/share/classes/sun/security/tools/jarsigner/Resources.java b/jdk/src/share/classes/sun/security/tools/jarsigner/Resources.java
index bff9dd7..909d573 100644
--- a/jdk/src/share/classes/sun/security/tools/jarsigner/Resources.java
+++ b/jdk/src/share/classes/sun/security/tools/jarsigner/Resources.java
@@ -138,26 +138,11 @@
         {"jar.is.unsigned",
                 "jar is unsigned."},
         {"jar.treated.unsigned",
-                "WARNING: Signature is either not parsable or not verifiable, and the jar will be treated as unsigned. For more information, re-run jarsigner with debug enabled (-J-Djava.security.debug=jar)."},
-        {"jar.treated.unsigned.see.weak",
-                "The jar will be treated as unsigned, because it is signed with a weak algorithm that is now disabled.\n\nRe-run jarsigner with the -verbose option for more details."},
-        {"jar.treated.unsigned.see.weak.verbose",
-                "WARNING: The jar will be treated as unsigned, because it is signed with a weak algorithm that is now disabled by the security property:"},
+                "Signature not parsable or verifiable. The jar will be treated as unsigned. The jar may have been signed with a weak algorithm that is now disabled. For more information, rerun jarsigner with debug enabled (-J-Djava.security.debug=jar)."},
         {"jar.signed.", "jar signed."},
         {"jar.signed.with.signer.errors.", "jar signed, with signer errors."},
         {"jar.verified.", "jar verified."},
         {"jar.verified.with.signer.errors.", "jar verified, with signer errors."},
-
-        {"history.with.ts", "- Signed by \"%1$s\"\n    Digest algorithm: %2$s\n    Signature algorithm: %3$s, %4$s\n  Timestamped by \"%6$s\" on %5$tc\n    Timestamp digest algorithm: %7$s\n    Timestamp signature algorithm: %8$s, %9$s"},
-        {"history.without.ts", "- Signed by \"%1$s\"\n    Digest algorithm: %2$s\n    Signature algorithm: %3$s, %4$s"},
-        {"history.unparsable", "- Unparsable signature-related file %s"},
-        {"history.nosf", "- Missing signature-related file META-INF/%s.SF"},
-        {"history.nobk", "- Missing block file for signature-related file META-INF/%s.SF"},
-
-        {"with.weak", "%s (weak)"},
-        {"key.bit", "%d-bit key"},
-        {"key.bit.weak", "%d-bit key (weak)"},
-
         {"jarsigner.", "jarsigner: "},
         {"signature.filename.must.consist.of.the.following.characters.A.Z.0.9.or.",
                 "signature filename must consist of the following characters: A-Z, 0-9, _ or -"},
diff --git a/jdk/src/share/classes/sun/tools/native2ascii/Main.java b/jdk/src/share/classes/sun/tools/native2ascii/Main.java
index 00e8332..1f02353 100644
--- a/jdk/src/share/classes/sun/tools/native2ascii/Main.java
+++ b/jdk/src/share/classes/sun/tools/native2ascii/Main.java
@@ -71,8 +71,11 @@
 import java.nio.charset.CharsetEncoder;
 import java.nio.charset.Charset;
 import java.nio.charset.IllegalCharsetNameException;
+import java.nio.file.Files;
 import java.io.UnsupportedEncodingException;
 import java.nio.charset.UnsupportedCharsetException;
+import sun.tools.native2ascii.A2NFilter;
+import sun.tools.native2ascii.N2AFilter;
 
 /**
  * Main program of the native2ascii
@@ -91,7 +94,7 @@
     /**
      * Run the converter
      */
-    public synchronized boolean convert(String argv[]) {
+    public synchronized boolean convert(String argv[]){
         List<String> v = new ArrayList<>(2);
         File outputFile = null;
         boolean createOutputFile = false;
@@ -99,14 +102,14 @@
         // Parse arguments
         for (int i = 0; i < argv.length; i++) {
             if (argv[i].equals("-encoding")) {
-                if ((i + 1) < argv.length) {
+                if ((i + 1) < argv.length){
                     encodingString = argv[++i];
                 } else {
                     error(getMsg("err.bad.arg"));
                     usage();
                     return false;
                 }
-            } else if (argv[i].equals("-reverse")) {
+            } else if (argv[i].equals("-reverse")){
                 reverse = true;
             } else {
                 if (v.size() > 1) {
@@ -116,18 +119,15 @@
                 v.add(argv[i]);
             }
         }
+        if (encodingString == null)
+           defaultEncoding = Charset.defaultCharset().name();
 
-        if (encodingString == null) {
-            defaultEncoding = Charset.defaultCharset().name();
-        }
         char[] lineBreak = System.getProperty("line.separator").toCharArray();
-
         try {
             initializeConverter();
 
-            if (v.size() == 1) {
+            if (v.size() == 1)
                 inputFileName = v.get(0);
-            }
 
             if (v.size() == 2) {
                 inputFileName = v.get(0);
@@ -137,38 +137,40 @@
 
             if (createOutputFile) {
                 outputFile = new File(outputFileName);
-                if (outputFile.exists() && !outputFile.canWrite()) {
-                    throw new Exception(formatMsg("err.cannot.write", outputFileName));
-                }
+                    if (outputFile.exists() && !outputFile.canWrite()) {
+                        throw new Exception(formatMsg("err.cannot.write", outputFileName));
+                    }
             }
 
-            if (reverse) {
-                try (BufferedReader reader = getA2NInput(inputFileName);
-                        Writer osw = getA2NOutput(outputFileName);) {
-                    String line;
-                    while ((line = reader.readLine()) != null) {
-                        osw.write(line.toCharArray());
-                        osw.write(lineBreak);
-                        if (outputFileName == null) { // flush stdout
-                            osw.flush();
-                        }
+            if (reverse){
+                BufferedReader reader = getA2NInput(inputFileName);
+                Writer osw = getA2NOutput(outputFileName);
+                String line;
+
+                while ((line = reader.readLine()) != null) {
+                    osw.write(line.toCharArray());
+                    osw.write(lineBreak);
+                    if (outputFileName == null) { // flush stdout
+                        osw.flush();
                     }
                 }
+                reader.close();  // Close the stream.
+                osw.close();
             } else {
-                // N2A
-                try (BufferedReader in = getN2AInput(inputFileName);
-                        BufferedWriter out = getN2AOutput(outputFileName);) {
-                    String inLine;
-                    while ((inLine = in.readLine()) != null) {
-                        out.write(inLine.toCharArray());
-                        out.write(lineBreak);
-                        if (outputFileName == null) { // flush stdout
-                            out.flush();
-                        }
+             //N2A
+                String inLine;
+                BufferedReader in = getN2AInput(inputFileName);
+                BufferedWriter out = getN2AOutput(outputFileName);
+
+                while ((inLine = in.readLine()) != null) {
+                    out.write(inLine.toCharArray());
+                    out.write(lineBreak);
+                    if (outputFileName == null) { // flush stdout
+                        out.flush();
                     }
                 }
+                out.close();
             }
-
             // Since we are done rename temporary file to desired output file
             if (createOutputFile) {
                 if (outputFile.exists()) {
@@ -180,7 +182,8 @@
                 }
                 tempFile.renameTo(outputFile);
             }
-        } catch (Exception e) {
+
+        } catch(Exception e){
             error(e.toString());
             return false;
         }
diff --git a/jdk/src/share/classes/sun/util/resources/CurrencyNames.properties b/jdk/src/share/classes/sun/util/resources/CurrencyNames.properties
index b002202..55ecf42 100644
--- a/jdk/src/share/classes/sun/util/resources/CurrencyNames.properties
+++ b/jdk/src/share/classes/sun/util/resources/CurrencyNames.properties
@@ -60,6 +60,9 @@
 # or other dealings in these Data Files or Software without prior
 # written authorization of the copyright holder.
 
+#
+# Generated automatically from the Common Locale Data Repository. DO NOT EDIT!
+#
 ADP=ADP
 AED=AED
 AFA=AFA
@@ -355,7 +358,7 @@
 gyd=Guyanaese Dollar
 hkd=Hong Kong Dollar
 hnl=Honduran Lempira
-hrk=Kuna
+hrk=Croatian Kuna
 htg=Haitian Gourde
 huf=Hungarian Forint
 idr=Indonesian Rupiah
diff --git a/jdk/src/share/classes/sun/util/resources/TimeZoneNames.java b/jdk/src/share/classes/sun/util/resources/TimeZoneNames.java
index e9459d9..5722da9 100644
--- a/jdk/src/share/classes/sun/util/resources/TimeZoneNames.java
+++ b/jdk/src/share/classes/sun/util/resources/TimeZoneNames.java
@@ -188,9 +188,6 @@
         String MHT[] = new String[] {"Marshall Islands Time", "MHT",
                                      "Marshall Islands Summer Time", "MHST",
                                      "Marshall Islands Time", "MHT"};
-        String MMT[] = new String[] {"Myanmar Time", "MMT",
-                                     "Myanmar Summer Time", "MMST",
-                                     "Myanmar Time", "MMT"};
         String MSK[] = new String[] {"Moscow Standard Time", "MSK",
                                      "Moscow Daylight Time", "MSD",
                                      "Moscow Time", "MT"};
@@ -686,7 +683,9 @@
             {"Asia/Qyzylorda", new String[] {"Qyzylorda Time", "QYZT",
                                              "Qyzylorda Summer Time", "QYZST",
                                              "Qyzylorda Time", "QYZT"}},
-            {"Asia/Rangoon", MMT},
+            {"Asia/Rangoon", new String[] {"Myanmar Time", "MMT",
+                                           "Myanmar Summer Time", "MMST",
+                                           "Myanmar Time", "MMT"}},
             {"Asia/Riyadh", ARAST},
             {"Asia/Saigon", ICT},
             {"Asia/Sakhalin", new String[] {"Sakhalin Time", "SAKT",
@@ -719,7 +718,6 @@
                                                "Vladivostok Summer Time", "VLAST",
                                                "Vladivostok Time", "VLAT"}},
             {"Asia/Yakutsk", YAKT},
-            {"Asia/Yangon", MMT},
             {"Asia/Yekaterinburg", new String[] {"Yekaterinburg Time", "YEKT",
                                                  "Yekaterinburg Summer Time", "YEKST",
                                                  "Yekaterinburg Time", "YEKT"}},
diff --git a/jdk/src/share/classes/sun/util/resources/de/TimeZoneNames_de.java b/jdk/src/share/classes/sun/util/resources/de/TimeZoneNames_de.java
index 9cdca7f..8fa22f9 100644
--- a/jdk/src/share/classes/sun/util/resources/de/TimeZoneNames_de.java
+++ b/jdk/src/share/classes/sun/util/resources/de/TimeZoneNames_de.java
@@ -189,9 +189,6 @@
         String MHT[] = new String[] {"Marshallinseln Zeit", "MHT",
                                      "Marshallinseln Sommerzeit", "MHST",
                                      "Marshallinseln Zeit", "MHT"};
-        String MMT[] = new String[] {"Myanmar Zeit", "MMT",
-                                     "Myanmar Sommerzeit", "MMST",
-                                     "Myanmar Zeit", "MMT"};
         String MSK[] = new String[] {"Moskauer Normalzeit", "MSK",
                                      "Moskauer Sommerzeit", "MSD",
                                      "Zeitzone f\u00FCr Moskau", "MT"};
@@ -687,7 +684,9 @@
             {"Asia/Qyzylorda", new String[] {"Qyzylorda Zeit", "QYZT",
                                              "Qyzylorda Sommerzeit", "QYZST",
                                              "Qyzylorda Zeit", "QYZT"}},
-            {"Asia/Rangoon", MMT},
+            {"Asia/Rangoon", new String[] {"Myanmar Zeit", "MMT",
+                                           "Myanmar Sommerzeit", "MMST",
+                                           "Myanmar Zeit", "MMT"}},
             {"Asia/Riyadh", ARAST},
             {"Asia/Saigon", ICT},
             {"Asia/Sakhalin", new String[] {"Sakhalin Zeit", "SAKT",
@@ -720,7 +719,6 @@
                                                "Wladiwostok Sommerzeit", "VLAST",
                                                "Wladiwostok Zeit", "VLAT"}},
             {"Asia/Yakutsk", YAKT},
-            {"Asia/Yangon", MMT},
             {"Asia/Yekaterinburg", new String[] {"Jekaterinburger Zeit", "YEKT",
                                                  "Jekaterinburger Sommerzeit", "YEKST",
                                                  "Jekaterinburger Zeit", "YEKT"}},
diff --git a/jdk/src/share/classes/sun/util/resources/es/TimeZoneNames_es.java b/jdk/src/share/classes/sun/util/resources/es/TimeZoneNames_es.java
index 1d41d22..c20c02e 100644
--- a/jdk/src/share/classes/sun/util/resources/es/TimeZoneNames_es.java
+++ b/jdk/src/share/classes/sun/util/resources/es/TimeZoneNames_es.java
@@ -189,9 +189,6 @@
         String MHT[] = new String[] {"Hora de las Islas Marshall", "MHT",
                                      "Hora de verano de las Islas Marshall", "MHST",
                                      "Hora de Islas Marshall", "MHT"};
-        String MMT[] = new String[] {"Hora de Myanmar", "MMT",
-                                     "Hora de verano de Myanmar", "MMST",
-                                     "Hora de Myanmar", "MMT"};
         String MSK[] = new String[] {"Hora est\u00e1ndar de Mosc\u00fa", "MSK",
                                      "Hora de verano de Mosc\u00fa", "MSD",
                                      "Hora de Mosc\u00FA", "MT"};
@@ -687,7 +684,9 @@
             {"Asia/Qyzylorda", new String[] {"Hora de Qyzylorda", "QYZT",
                                              "Hora de verano de Qyzylorda", "QYZST",
                                              "Hora de Qyzylorda", "QYZT"}},
-            {"Asia/Rangoon", MMT},
+            {"Asia/Rangoon", new String[] {"Hora de Myanmar", "MMT",
+                                           "Hora de verano de Myanmar", "MMST",
+                                           "Hora de Myanmar", "MMT"}},
             {"Asia/Riyadh", ARAST},
             {"Asia/Saigon", ICT},
             {"Asia/Sakhalin", new String[] {"Hora de Sajalin", "SAKT",
@@ -720,7 +719,6 @@
                                                "Hora de verano de Vladivostok", "VLAST",
                                                "Hora de Vladivostok", "VLAT"}},
             {"Asia/Yakutsk", YAKT},
-            {"Asia/Yangon", MMT},
             {"Asia/Yekaterinburg", new String[] {"Hora de Ekaterinburgo", "YEKT",
                                                  "Hora de verano de Ekaterinburgo", "YEKST",
                                                  "Hora de Ekaterinburgo", "YEKT"}},
diff --git a/jdk/src/share/classes/sun/util/resources/fr/TimeZoneNames_fr.java b/jdk/src/share/classes/sun/util/resources/fr/TimeZoneNames_fr.java
index 5e3d2bc..3d81200 100644
--- a/jdk/src/share/classes/sun/util/resources/fr/TimeZoneNames_fr.java
+++ b/jdk/src/share/classes/sun/util/resources/fr/TimeZoneNames_fr.java
@@ -189,9 +189,6 @@
         String MHT[] = new String[] {"Heure des Iles Marshall", "MHT",
                                      "Heure d'\u00e9t\u00e9 des Iles Marshall", "MHST",
                                      "Heure des Iles Marshall", "MHT"};
-        String MMT[] = new String[] {"Heure de Myanmar", "MMT",
-                                     "Heure d'\u00e9t\u00e9 de Myanmar", "MMST",
-                                     "Heure de Myanmar", "MMT"};
         String MSK[] = new String[] {"Heure standard de Moscou", "MSK",
                                      "Heure avanc\u00e9e de Moscou", "MSD",
                                      "Moscou", "MT"};
@@ -687,7 +684,9 @@
             {"Asia/Qyzylorda", new String[] {"Heure de Kyzylorda", "QYZT",
                                              "Heure d'\u00e9t\u00e9 de Kyzylorda", "QYZST",
                                              "Heure de Kyzylorda", "QYZT"}},
-            {"Asia/Rangoon", MMT},
+            {"Asia/Rangoon", new String[] {"Heure de Myanmar", "MMT",
+                                           "Heure d'\u00e9t\u00e9 de Myanmar", "MMST",
+                                           "Heure de Myanmar", "MMT"}},
             {"Asia/Riyadh", ARAST},
             {"Asia/Saigon", ICT},
             {"Asia/Sakhalin", new String[] {"Heure de Sakhalin", "SAKT",
@@ -720,7 +719,6 @@
                                                "Heure d'\u00e9t\u00e9 de Vladivostok", "VLAST",
                                                "Heure de Vladivostok", "VLAT"}},
             {"Asia/Yakutsk", YAKT},
-            {"Asia/Yangon", MMT},
             {"Asia/Yekaterinburg", new String[] {"Heure de Yekaterinburg", "YEKT",
                                                  "Heure d'\u00e9t\u00e9 de Yekaterinburg", "YEKST",
                                                  "Heure de Yekaterinburg", "YEKT"}},
diff --git a/jdk/src/share/classes/sun/util/resources/it/TimeZoneNames_it.java b/jdk/src/share/classes/sun/util/resources/it/TimeZoneNames_it.java
index 49930fd..33350c4 100644
--- a/jdk/src/share/classes/sun/util/resources/it/TimeZoneNames_it.java
+++ b/jdk/src/share/classes/sun/util/resources/it/TimeZoneNames_it.java
@@ -189,9 +189,6 @@
         String MHT[] = new String[] {"Ora delle Isole Marshall", "MHT",
                                      "Ora estiva delle Isole Marshall", "MHST",
                                      "Ora delle Isole Marshall", "MHT"};
-        String MMT[] = new String[] {"Ora della Birmania/Myanmar", "MMT",
-                                     "Ora estiva della Birmania/Myanmar", "MMST",
-                                     "Ora della Birmania/Myanmar", "MMT"};
         String MSK[] = new String[] {"Ora standard di Mosca", "MSK",
                                      "Ora legale di Mosca", "MSD",
                                      "Ora Mosca", "MT"};
@@ -687,7 +684,9 @@
             {"Asia/Qyzylorda", new String[] {"Ora di Qyzylorda", "QYZT",
                                              "Ora estiva di Qyzylorda", "QYZST",
                                              "Ora di Qyzylorda", "QYZT"}},
-            {"Asia/Rangoon", MMT},
+            {"Asia/Rangoon", new String[] {"Ora della Birmania/Myanmar", "MMT",
+                                           "Ora estiva della Birmania/Myanmar", "MMST",
+                                           "Ora della Birmania/Myanmar", "MMT"}},
             {"Asia/Riyadh", ARAST},
             {"Asia/Saigon", ICT},
             {"Asia/Sakhalin", new String[] {"Ora di Sakhalin", "SAKT",
@@ -720,7 +719,6 @@
                                                "Ora estiva di Vladivostok", "VLAST",
                                                "Ora di Vladivostok", "VLAT"}},
             {"Asia/Yakutsk", YAKT},
-            {"Asia/Yangon", MMT},
             {"Asia/Yekaterinburg", new String[] {"Ora di Ekaterinburg", "YEKT",
                                                  "Ora estiva di Ekaterinburg", "YEKST",
                                                  "Ora di Ekaterinburg", "YEKT"}},
diff --git a/jdk/src/share/classes/sun/util/resources/ja/TimeZoneNames_ja.java b/jdk/src/share/classes/sun/util/resources/ja/TimeZoneNames_ja.java
index 90c26c0..57a3fb7 100644
--- a/jdk/src/share/classes/sun/util/resources/ja/TimeZoneNames_ja.java
+++ b/jdk/src/share/classes/sun/util/resources/ja/TimeZoneNames_ja.java
@@ -189,9 +189,6 @@
         String MHT[] = new String[] {"\u30de\u30fc\u30b7\u30e3\u30eb\u5cf6\u6642\u9593", "MHT",
                                      "\u30de\u30fc\u30b7\u30e3\u30eb\u5cf6\u590f\u6642\u9593", "MHST",
                                      "\u30DE\u30FC\u30B7\u30E3\u30EB\u8AF8\u5CF6\u6642\u9593", "MHT"};
-        String MMT[] = new String[] {"\u30df\u30e3\u30f3\u30de\u30fc\u6642\u9593", "MMT",
-                                     "\u30df\u30e3\u30f3\u30de\u30fc\u590f\u6642\u9593", "MMST",
-                                     "\u30DF\u30E3\u30F3\u30DE\u30FC\u6642\u9593", "MMT"};
         String MSK[] = new String[] {"\u30e2\u30b9\u30af\u30ef\u6a19\u6e96\u6642", "MSK",
                                      "\u30e2\u30b9\u30af\u30ef\u590f\u6642\u9593", "MSD",
                                      "\u30E2\u30B9\u30AF\u30EF\u6642\u9593", "MT"};
@@ -687,7 +684,9 @@
             {"Asia/Qyzylorda", new String[] {"\u30ad\u30b8\u30eb\u30aa\u30eb\u30c0\u6642\u9593", "QYZT",
                                              "\u30ad\u30b8\u30eb\u30aa\u30eb\u30c0\u590f\u6642\u9593", "QYZST",
                                              "\u30AF\u30BA\u30ED\u30EB\u30C0\u6642\u9593", "QYZT"}},
-            {"Asia/Rangoon", MMT},
+            {"Asia/Rangoon", new String[] {"\u30df\u30e3\u30f3\u30de\u30fc\u6642\u9593", "MMT",
+                                           "\u30df\u30e3\u30f3\u30de\u30fc\u590f\u6642\u9593", "MMST",
+                                           "\u30DF\u30E3\u30F3\u30DE\u30FC\u6642\u9593", "MMT"}},
             {"Asia/Riyadh", ARAST},
             {"Asia/Saigon", ICT},
             {"Asia/Sakhalin", new String[] {"\u6a3a\u592a\u6642\u9593", "SAKT",
@@ -720,7 +719,6 @@
                                                "\u30a6\u30e9\u30b8\u30aa\u30b9\u30c8\u30af\u590f\u6642\u9593", "VLAST",
                                                "\u30A6\u30E9\u30B8\u30AA\u30B9\u30C8\u30AF\u6642\u9593", "VLAT"}},
             {"Asia/Yakutsk", YAKT},
-            {"Asia/Yangon", MMT},
             {"Asia/Yekaterinburg", new String[] {"\u30a8\u30ab\u30c6\u30ea\u30f3\u30d6\u30eb\u30b0\u6642\u9593", "YEKT",
                                                  "\u30a8\u30ab\u30c6\u30ea\u30f3\u30d6\u30eb\u30b0\u590f\u6642\u9593", "YEKST",
                                                  "\u30A8\u30AB\u30C6\u30EA\u30F3\u30D6\u30EB\u30AF\u6642\u9593", "YEKT"}},
diff --git a/jdk/src/share/classes/sun/util/resources/ko/TimeZoneNames_ko.java b/jdk/src/share/classes/sun/util/resources/ko/TimeZoneNames_ko.java
index 9aee59b..d17154b 100644
--- a/jdk/src/share/classes/sun/util/resources/ko/TimeZoneNames_ko.java
+++ b/jdk/src/share/classes/sun/util/resources/ko/TimeZoneNames_ko.java
@@ -189,9 +189,6 @@
         String MHT[] = new String[] {"\ub9c8\uc15c\uc81c\ub3c4 \uc2dc\uac04", "MHT",
                                      "\ub9c8\uc15c\uc81c\ub3c4 \uc77c\uad11\uc808\uc57d\uc2dc\uac04", "MHST",
                                      "\uB9C8\uC15C \uC81C\uB3C4 \uD45C\uC900\uC2DC", "MHT"};
-        String MMT[] = new String[] {"\ubbf8\uc580\ub9c8 \uc2dc\uac04", "MMT",
-                                     "\ubbf8\uc580\ub9c8 \uc77c\uad11\uc808\uc57d\uc2dc\uac04", "MMST",
-                                     "\uBBF8\uC580\uB9C8 \uD45C\uC900\uC2DC", "MMT"};
         String MSK[] = new String[] {"\ubaa8\uc2a4\ud06c\ubc14 \ud45c\uc900\uc2dc", "MSK",
                                      "\ubaa8\uc2a4\ud06c\ubc14 \uc77c\uad11\uc808\uc57d\uc2dc\uac04", "MSD",
                                      "\uBAA8\uC2A4\uD06C\uBC14 \uD45C\uC900\uC2DC", "MT"};
@@ -687,7 +684,9 @@
             {"Asia/Qyzylorda", new String[] {"Qyzylorda \ud45c\uc900\uc2dc", "QYZT",
                                              "Qyzylorda \uc77c\uad11\uc808\uc57d\uc2dc\uac04", "QYZST",
                                              "\uD0A4\uC9C8\uB85C\uB974\uB2E4 \uD45C\uC900\uC2DC", "QYZT"}},
-            {"Asia/Rangoon", MMT},
+            {"Asia/Rangoon", new String[] {"\ubbf8\uc580\ub9c8 \uc2dc\uac04", "MMT",
+                                           "\ubbf8\uc580\ub9c8 \uc77c\uad11\uc808\uc57d\uc2dc\uac04", "MMST",
+                                           "\uBBF8\uC580\uB9C8 \uD45C\uC900\uC2DC", "MMT"}},
             {"Asia/Riyadh", ARAST},
             {"Asia/Saigon", ICT},
             {"Asia/Sakhalin", new String[] {"\uc0ac\ud560\ub9b0 \uc2dc\uac04", "SAKT",
@@ -720,7 +719,6 @@
                                                "\ube14\ub77c\ub514\ubcf4\uc2a4\ud1a1 \uc77c\uad11\uc808\uc57d\uc2dc\uac04", "VLAST",
                                                "\uBE14\uB77C\uB514\uBCF4\uC2A4\uD1A1 \uD45C\uC900\uC2DC", "VLAT"}},
             {"Asia/Yakutsk", YAKT},
-            {"Asia/Yangon", MMT},
             {"Asia/Yekaterinburg", new String[] {"\uc608\uce74\ud14c\ub9b0\ubc84\uadf8 \uc2dc\uac04", "YEKT",
                                                  "\uc608\uce74\ud14c\ub9b0\ubc84\uadf8 \uc77c\uad11\uc808\uc57d\uc2dc\uac04", "YEKST",
                                                  "\uC608\uCE74\uD14C\uB9B0\uBD80\uB974\uD06C \uD45C\uC900\uC2DC", "YEKT"}},
diff --git a/jdk/src/share/classes/sun/util/resources/pt/TimeZoneNames_pt_BR.java b/jdk/src/share/classes/sun/util/resources/pt/TimeZoneNames_pt_BR.java
index ec3afb5..32747fe 100644
--- a/jdk/src/share/classes/sun/util/resources/pt/TimeZoneNames_pt_BR.java
+++ b/jdk/src/share/classes/sun/util/resources/pt/TimeZoneNames_pt_BR.java
@@ -189,9 +189,6 @@
         String MSK[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o de Moscou", "MSK",
                                      "Hor\u00e1rio de luz natural de Moscou", "MSD",
                                      "Hor\u00E1rio de Moscou", "MT"};
-        String MMT[] = new String[] {"Fuso hor\u00e1rio de Mianmar", "MMT",
-                                     "Fuso hor\u00e1rio de ver\u00e3o de Mianmar", "MMST",
-                                     "Hor\u00E1rio de Mianmar", "MMT"};
         String MST[] = new String[] {"Fuso hor\u00e1rio padr\u00e3o das montanhas", "MST",
                                      "Hor\u00e1rio de luz natural das montanhas", "MDT",
                                      "Hor\u00E1rio das Montanhas Rochosas", "MT"};
@@ -687,7 +684,9 @@
             {"Asia/Qyzylorda", new String[] {"Fuso hor\u00e1rio de Kizil-Orda", "QYZT",
                                              "Fuso hor\u00e1rio de ver\u00e3o de Kizil-Orda", "QYZST",
                                              "Hor\u00E1rio de Qyzylorda", "QYZT"}},
-            {"Asia/Rangoon", MMT},
+            {"Asia/Rangoon", new String[] {"Fuso hor\u00e1rio de Mianmar", "MMT",
+                                           "Fuso hor\u00e1rio de ver\u00e3o de Mianmar", "MMST",
+                                           "Hor\u00E1rio de Mianmar", "MMT"}},
             {"Asia/Riyadh", ARAST},
             {"Asia/Saigon", ICT},
             {"Asia/Sakhalin", new String[] {"Fuso hor\u00e1rio de Sakhalina", "SAKT",
@@ -720,7 +719,6 @@
                                                "Fuso hor\u00e1rio de ver\u00e3o de Vladivostok", "VLAST",
                                                "Hor\u00E1rio de Vladivostok", "VLAT"}},
             {"Asia/Yakutsk", YAKT},
-            {"Asia/Yangon", MMT},
             {"Asia/Yekaterinburg", new String[] {"Fuso hor\u00e1rio de Yekaterinburgo", "YEKT",
                                                  "Fuso hor\u00e1rio de ver\u00e3o de Yekaterinburgo", "YEKST",
                                                  "Hor\u00E1rio de Yekaterinburg", "YEKT"}},
diff --git a/jdk/src/share/classes/sun/util/resources/sv/TimeZoneNames_sv.java b/jdk/src/share/classes/sun/util/resources/sv/TimeZoneNames_sv.java
index 903902d..8705bfe 100644
--- a/jdk/src/share/classes/sun/util/resources/sv/TimeZoneNames_sv.java
+++ b/jdk/src/share/classes/sun/util/resources/sv/TimeZoneNames_sv.java
@@ -189,9 +189,6 @@
         String MHT[] = new String[] {"Marshall\u00f6arna, normaltid", "MHT",
                                      "Marshall\u00f6arna, sommartid", "MHST",
                                      "Marshall\u00F6arna-tid", "MHT"};
-        String MMT[] = new String[] {"Myanmar, normaltid", "MMT",
-                                     "Myanmar, sommartid", "MMST",
-                                     "Myanmar-tid", "MMT"};
         String MSK[] = new String[] {"Moskva, normaltid", "MSK",
                                      "Moskva, sommartid", "MSD",
                                      "Moskvas tid", "MT"};
@@ -687,7 +684,9 @@
             {"Asia/Qyzylorda", new String[] {"Qyzylorda, normaltid", "QYZT",
                                              "Qyzylorda, sommartid", "QYZST",
                                              "Qyzylorda-tid", "QYZT"}},
-            {"Asia/Rangoon", MMT},
+            {"Asia/Rangoon", new String[] {"Myanmar, normaltid", "MMT",
+                                           "Myanmar, sommartid", "MMST",
+                                           "Myanmar-tid", "MMT"}},
             {"Asia/Riyadh", ARAST},
             {"Asia/Saigon", ICT},
             {"Asia/Sakhalin", new String[] {"Sakhalin, normaltid", "SAKT",
@@ -720,7 +719,6 @@
                                                "Vladivostok, sommartid", "VLAST",
                                                "Vladivostok-tid", "VLAT"}},
             {"Asia/Yakutsk", YAKT},
-            {"Asia/Yangon", MMT},
             {"Asia/Yekaterinburg", new String[] {"Jekaterinburg, normaltid", "YEKT",
                                                  "Jekaterinburg, sommartid", "YEKST",
                                                  "Jekaterinburg-tid", "YEKT"}},
diff --git a/jdk/src/share/classes/sun/util/resources/zh/TimeZoneNames_zh_CN.java b/jdk/src/share/classes/sun/util/resources/zh/TimeZoneNames_zh_CN.java
index d2ef55b..d5e5215 100644
--- a/jdk/src/share/classes/sun/util/resources/zh/TimeZoneNames_zh_CN.java
+++ b/jdk/src/share/classes/sun/util/resources/zh/TimeZoneNames_zh_CN.java
@@ -189,9 +189,6 @@
         String MHT[] = new String[] {"\u9a6c\u7ecd\u5c14\u7fa4\u5c9b\u65f6\u95f4", "MHT",
                                      "\u9a6c\u7ecd\u5c14\u7fa4\u5c9b\u590f\u4ee4\u65f6", "MHST",
                                      "\u9A6C\u7ECD\u5C14\u7FA4\u5C9B\u65F6\u95F4", "MHT"};
-        String MMT[] = new String[] {"\u7f05\u7538\u65f6\u95f4", "MMT",
-                                     "\u7f05\u7538\u590f\u4ee4\u65f6", "MMST",
-                                     "\u7F05\u7538\u65F6\u95F4", "MMT"};
         String MSK[] = new String[] {"\u83ab\u65af\u79d1\u6807\u51c6\u65f6\u95f4", "MSK",
                                      "\u83ab\u65af\u79d1\u590f\u4ee4\u65f6", "MSD",
                                      "\u83AB\u65AF\u79D1\u65F6\u95F4", "MT"};
@@ -687,7 +684,9 @@
             {"Asia/Qyzylorda", new String[] {"Qyzylorda \u65f6\u95f4", "QYZT",
                                              "Qyzylorda \u590f\u4ee4\u65f6", "QYZST",
                                              "Qyzylorda \u65F6\u95F4", "QYZT"}},
-            {"Asia/Rangoon", MMT},
+            {"Asia/Rangoon", new String[] {"\u7f05\u7538\u65f6\u95f4", "MMT",
+                                           "\u7f05\u7538\u590f\u4ee4\u65f6", "MMST",
+                                           "\u7F05\u7538\u65F6\u95F4", "MMT"}},
             {"Asia/Riyadh", ARAST},
             {"Asia/Saigon", ICT},
             {"Asia/Sakhalin", new String[] {"\u5e93\u9875\u5c9b\u65f6\u95f4", "SAKT",
@@ -720,7 +719,6 @@
                                                "\u6d77\u53c2\u5d34\u590f\u4ee4\u65f6", "VLAST",
                                                "\u6D77\u53C2\u5D34\u65F6\u95F4", "VLAT"}},
             {"Asia/Yakutsk", YAKT},
-            {"Asia/Yangon", MMT},
             {"Asia/Yekaterinburg", new String[] {"Yekaterinburg \u65f6\u95f4", "YEKT",
                                                  "Yekaterinburg \u590f\u4ee4\u65f6", "YEKST",
                                                  "Yekaterinburg \u65F6\u95F4", "YEKT"}},
diff --git a/jdk/src/share/classes/sun/util/resources/zh/TimeZoneNames_zh_TW.java b/jdk/src/share/classes/sun/util/resources/zh/TimeZoneNames_zh_TW.java
index b99f9d5..4dc212b 100644
--- a/jdk/src/share/classes/sun/util/resources/zh/TimeZoneNames_zh_TW.java
+++ b/jdk/src/share/classes/sun/util/resources/zh/TimeZoneNames_zh_TW.java
@@ -189,9 +189,6 @@
         String MHT[] = new String[] {"\u99ac\u7d39\u723e\u7fa4\u5cf6\u6642\u9593", "MHT",
                                      "\u99ac\u7d39\u723e\u7fa4\u5cf6\u590f\u4ee4\u6642\u9593", "MHST",
                                      "\u99AC\u7D39\u723E\u7FA4\u5CF6\u6642\u9593", "MHT"};
-        String MMT[] = new String[] {"\u7dec\u7538\u6642\u9593", "MMT",
-                                     "\u7dec\u7538\u590f\u4ee4\u6642\u9593", "MMST",
-                                     "\u7DEC\u7538\u6642\u9593", "MMT"};
         String MSK[] = new String[] {"\u83ab\u65af\u79d1\u6a19\u6e96\u6642\u9593", "MSK",
                                      "\u83ab\u65af\u79d1\u65e5\u5149\u7bc0\u7d04\u6642\u9593", "MSD",
                                      "\u83AB\u65AF\u79D1\u6642\u9593", "MT"};
@@ -687,7 +684,9 @@
             {"Asia/Qyzylorda", new String[] {"Qyzylorda \u6642\u9593", "QYZT",
                                              "Qyzylorda \u590f\u4ee4\u6642\u9593", "QYZST",
                                              "\u514B\u5B5C\u6D1B\u723E\u9054\u6642\u9593", "QYZT"}},
-            {"Asia/Rangoon", MMT},
+            {"Asia/Rangoon", new String[] {"\u7dec\u7538\u6642\u9593", "MMT",
+                                           "\u7dec\u7538\u590f\u4ee4\u6642\u9593", "MMST",
+                                           "\u7DEC\u7538\u6642\u9593", "MMT"}},
             {"Asia/Riyadh", ARAST},
             {"Asia/Saigon", ICT},
             {"Asia/Sakhalin", new String[] {"\u5eab\u9801\u5cf6\u6642\u9593", "SAKT",
@@ -722,7 +721,6 @@
                                                "\u6d77\u53c3\u5d34\u590f\u4ee4\u6642\u9593", "VLAST",
                                                "\u6D77\u53C3\u5D34\u6642\u9593", "VLAT"}},
             {"Asia/Yakutsk", YAKT},
-            {"Asia/Yangon", MMT},
             {"Asia/Yekaterinburg", new String[] {"Yekaterinburg \u6642\u9593", "YEKT",
                                                  "Yekaterinburg \u590f\u4ee4\u6642\u9593", "YEKST",
                                                  "\u8449\u5361\u6377\u7433\u5821\u6642\u9593", "YEKT"}},
diff --git a/jdk/src/share/lib/security/java.security-aix b/jdk/src/share/lib/security/java.security-aix
index c29c25b..ae47914 100644
--- a/jdk/src/share/lib/security/java.security-aix
+++ b/jdk/src/share/lib/security/java.security-aix
@@ -483,43 +483,6 @@
 #
 jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
 
-# Algorithm restrictions for signed JAR files
-#
-# In some environments, certain algorithms or key lengths may be undesirable
-# for signed JAR validation.  For example, "MD2" is generally no longer
-# considered to be a secure hash algorithm.  This section describes the
-# mechanism for disabling algorithms based on algorithm name and/or key length.
-# JARs signed with any of the disabled algorithms or key sizes will be treated
-# as unsigned.
-#
-# The syntax of the disabled algorithm string is described as follows:
-#   DisabledAlgorithms:
-#       " DisabledAlgorithm { , DisabledAlgorithm } "
-#
-#   DisabledAlgorithm:
-#       AlgorithmName [Constraint]
-#
-#   AlgorithmName:
-#       (see below)
-#
-#   Constraint:
-#       KeySizeConstraint
-#
-#   KeySizeConstraint:
-#       keySize Operator KeyLength
-#
-#   Operator:
-#       <= | < | == | != | >= | >
-#
-#   KeyLength:
-#       Integer value of the algorithm's key length in bits
-#
-# Note: This property is currently used by the JDK Reference
-# implementation. It is not guaranteed to be examined and used by other
-# implementations.
-#
-jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
-
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
 # (SSL/TLS) processing
 #
@@ -662,67 +625,39 @@
 #       EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381 \
 #       FFFFFFFF FFFFFFFF, 2}
 
-# Cryptographic Jurisdiction Policy defaults
+# Algorithm restrictions for signed JAR files
 #
-# Due to the import control restrictions of some countries, the default
-# JCE policy files allow for strong but "limited" cryptographic key
-# lengths to be used.  If your country's cryptographic regulations allow,
-# the "unlimited" strength policy files can be used instead, which contain
-# no restrictions on cryptographic strengths.
+# In some environments, certain algorithms or key lengths may be undesirable
+# for signed JAR validation.  For example, "MD2" is generally no longer
+# considered to be a secure hash algorithm.  This section describes the
+# mechanism for disabling algorithms based on algorithm name and/or key length.
+# JARs signed with any of the disabled algorithms or key sizes will be treated
+# as unsigned.
 #
-# YOU ARE ADVISED TO CONSULT YOUR EXPORT/IMPORT CONTROL COUNSEL OR ATTORNEY
-# TO DETERMINE THE EXACT REQUIREMENTS.
+# The syntax of the disabled algorithm string is described as follows:
+#   DisabledAlgorithms:
+#       " DisabledAlgorithm { , DisabledAlgorithm } "
 #
-# <java-home> (below) refers to the directory where the JRE was
-# installed. It is determined based on whether you are running JCE
-# on a JRE or a JRE contained within the Java Development Kit, or
-# JDK(TM). The JDK contains the JRE, but at a different level in the
-# file hierarchy. For example, if the JDK is installed in
-# /home/user1/jdk1.8.0 on Unix or in C:\jdk1.8.0 on Windows, then
-# <java-home> is:
+#   DisabledAlgorithm:
+#       AlgorithmName [Constraint]
 #
-#  /home/user1/jdk1.8.0/jre           [Unix]
-#  C:\jdk1.8.0\jre                    [Windows]
+#   AlgorithmName:
+#       (see below)
 #
-# If on the other hand the JRE is installed in /home/user1/jre1.8.0
-# on Unix or in C:\jre1.8.0 on Windows, and the JDK is not
-# installed, then <java-home> is:
+#   Constraint:
+#       KeySizeConstraint
 #
-#  /home/user1/jre1.8.0               [Unix]
-#  C:\jre1.8.0                        [Windows]
+#   KeySizeConstraint:
+#       keySize Operator KeyLength
 #
-# On Windows, for each JDK installation, there may be additional
-# JREs installed under the "Program Files" directory. Please make
-# sure that you install the unlimited strength policy JAR files
-# for all JREs that you plan to use.
+#   Operator:
+#       <= | < | == | != | >= | >
 #
-# The policy files are jar files organized into subdirectories of
-# <java-home>/lib/security/policy.  Each directory contains a complete
-# set of policy files.
+#   KeyLength:
+#       Integer value of the algorithm's key length in bits
 #
-# The "crypto.policy" Security property controls the directory selection,
-# and thus the effective cryptographic policy.
+# Note: This property is currently used by the JDK Reference
+# implementation. It is not guaranteed to be examined and used by other
+# implementations.
 #
-# The default set of directories is:
-#
-#     limited | unlimited
-#
-# however other directories can be created and configured.
-#
-# To support older JDK Update releases, the crypto.policy property
-# is not defined by default. When the property is not defined, an
-# update release binary aware of the new property will use the following
-# logic to decide what crypto policy files get used :
-#
-# * If the US_export_policy.jar and local_policy.jar files are located
-# in the (legacy) <java-home>/lib/security directory, then the rules
-# embedded in those jar files will be used. This helps preserve compatibility
-# for users upgrading from an older installation.
-#
-# * If crypto.policy is not defined and no such jar files are present in
-# the legacy locations, then the JDK will use the limited settings
-# (equivalent to crypto.policy=limited)
-#
-# Please see the JCA documentation for additional information on these
-# files and formats.
-#crypto.policy=unlimited
+jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024
diff --git a/jdk/src/share/lib/security/java.security-linux b/jdk/src/share/lib/security/java.security-linux
index c29c25b..ae47914 100644
--- a/jdk/src/share/lib/security/java.security-linux
+++ b/jdk/src/share/lib/security/java.security-linux
@@ -483,43 +483,6 @@
 #
 jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
 
-# Algorithm restrictions for signed JAR files
-#
-# In some environments, certain algorithms or key lengths may be undesirable
-# for signed JAR validation.  For example, "MD2" is generally no longer
-# considered to be a secure hash algorithm.  This section describes the
-# mechanism for disabling algorithms based on algorithm name and/or key length.
-# JARs signed with any of the disabled algorithms or key sizes will be treated
-# as unsigned.
-#
-# The syntax of the disabled algorithm string is described as follows:
-#   DisabledAlgorithms:
-#       " DisabledAlgorithm { , DisabledAlgorithm } "
-#
-#   DisabledAlgorithm:
-#       AlgorithmName [Constraint]
-#
-#   AlgorithmName:
-#       (see below)
-#
-#   Constraint:
-#       KeySizeConstraint
-#
-#   KeySizeConstraint:
-#       keySize Operator KeyLength
-#
-#   Operator:
-#       <= | < | == | != | >= | >
-#
-#   KeyLength:
-#       Integer value of the algorithm's key length in bits
-#
-# Note: This property is currently used by the JDK Reference
-# implementation. It is not guaranteed to be examined and used by other
-# implementations.
-#
-jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
-
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
 # (SSL/TLS) processing
 #
@@ -662,67 +625,39 @@
 #       EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381 \
 #       FFFFFFFF FFFFFFFF, 2}
 
-# Cryptographic Jurisdiction Policy defaults
+# Algorithm restrictions for signed JAR files
 #
-# Due to the import control restrictions of some countries, the default
-# JCE policy files allow for strong but "limited" cryptographic key
-# lengths to be used.  If your country's cryptographic regulations allow,
-# the "unlimited" strength policy files can be used instead, which contain
-# no restrictions on cryptographic strengths.
+# In some environments, certain algorithms or key lengths may be undesirable
+# for signed JAR validation.  For example, "MD2" is generally no longer
+# considered to be a secure hash algorithm.  This section describes the
+# mechanism for disabling algorithms based on algorithm name and/or key length.
+# JARs signed with any of the disabled algorithms or key sizes will be treated
+# as unsigned.
 #
-# YOU ARE ADVISED TO CONSULT YOUR EXPORT/IMPORT CONTROL COUNSEL OR ATTORNEY
-# TO DETERMINE THE EXACT REQUIREMENTS.
+# The syntax of the disabled algorithm string is described as follows:
+#   DisabledAlgorithms:
+#       " DisabledAlgorithm { , DisabledAlgorithm } "
 #
-# <java-home> (below) refers to the directory where the JRE was
-# installed. It is determined based on whether you are running JCE
-# on a JRE or a JRE contained within the Java Development Kit, or
-# JDK(TM). The JDK contains the JRE, but at a different level in the
-# file hierarchy. For example, if the JDK is installed in
-# /home/user1/jdk1.8.0 on Unix or in C:\jdk1.8.0 on Windows, then
-# <java-home> is:
+#   DisabledAlgorithm:
+#       AlgorithmName [Constraint]
 #
-#  /home/user1/jdk1.8.0/jre           [Unix]
-#  C:\jdk1.8.0\jre                    [Windows]
+#   AlgorithmName:
+#       (see below)
 #
-# If on the other hand the JRE is installed in /home/user1/jre1.8.0
-# on Unix or in C:\jre1.8.0 on Windows, and the JDK is not
-# installed, then <java-home> is:
+#   Constraint:
+#       KeySizeConstraint
 #
-#  /home/user1/jre1.8.0               [Unix]
-#  C:\jre1.8.0                        [Windows]
+#   KeySizeConstraint:
+#       keySize Operator KeyLength
 #
-# On Windows, for each JDK installation, there may be additional
-# JREs installed under the "Program Files" directory. Please make
-# sure that you install the unlimited strength policy JAR files
-# for all JREs that you plan to use.
+#   Operator:
+#       <= | < | == | != | >= | >
 #
-# The policy files are jar files organized into subdirectories of
-# <java-home>/lib/security/policy.  Each directory contains a complete
-# set of policy files.
+#   KeyLength:
+#       Integer value of the algorithm's key length in bits
 #
-# The "crypto.policy" Security property controls the directory selection,
-# and thus the effective cryptographic policy.
+# Note: This property is currently used by the JDK Reference
+# implementation. It is not guaranteed to be examined and used by other
+# implementations.
 #
-# The default set of directories is:
-#
-#     limited | unlimited
-#
-# however other directories can be created and configured.
-#
-# To support older JDK Update releases, the crypto.policy property
-# is not defined by default. When the property is not defined, an
-# update release binary aware of the new property will use the following
-# logic to decide what crypto policy files get used :
-#
-# * If the US_export_policy.jar and local_policy.jar files are located
-# in the (legacy) <java-home>/lib/security directory, then the rules
-# embedded in those jar files will be used. This helps preserve compatibility
-# for users upgrading from an older installation.
-#
-# * If crypto.policy is not defined and no such jar files are present in
-# the legacy locations, then the JDK will use the limited settings
-# (equivalent to crypto.policy=limited)
-#
-# Please see the JCA documentation for additional information on these
-# files and formats.
-#crypto.policy=unlimited
+jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024
diff --git a/jdk/src/share/lib/security/java.security-macosx b/jdk/src/share/lib/security/java.security-macosx
index 1e135b4..2e25f91 100644
--- a/jdk/src/share/lib/security/java.security-macosx
+++ b/jdk/src/share/lib/security/java.security-macosx
@@ -486,43 +486,6 @@
 #
 jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
 
-# Algorithm restrictions for signed JAR files
-#
-# In some environments, certain algorithms or key lengths may be undesirable
-# for signed JAR validation.  For example, "MD2" is generally no longer
-# considered to be a secure hash algorithm.  This section describes the
-# mechanism for disabling algorithms based on algorithm name and/or key length.
-# JARs signed with any of the disabled algorithms or key sizes will be treated
-# as unsigned.
-#
-# The syntax of the disabled algorithm string is described as follows:
-#   DisabledAlgorithms:
-#       " DisabledAlgorithm { , DisabledAlgorithm } "
-#
-#   DisabledAlgorithm:
-#       AlgorithmName [Constraint]
-#
-#   AlgorithmName:
-#       (see below)
-#
-#   Constraint:
-#       KeySizeConstraint
-#
-#   KeySizeConstraint:
-#       keySize Operator KeyLength
-#
-#   Operator:
-#       <= | < | == | != | >= | >
-#
-#   KeyLength:
-#       Integer value of the algorithm's key length in bits
-#
-# Note: This property is currently used by the JDK Reference
-# implementation. It is not guaranteed to be examined and used by other
-# implementations.
-#
-jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
-
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
 # (SSL/TLS) processing
 #
@@ -665,67 +628,39 @@
 #       EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381 \
 #       FFFFFFFF FFFFFFFF, 2}
 
-# Cryptographic Jurisdiction Policy defaults
+# Algorithm restrictions for signed JAR files
 #
-# Due to the import control restrictions of some countries, the default
-# JCE policy files allow for strong but "limited" cryptographic key
-# lengths to be used.  If your country's cryptographic regulations allow,
-# the "unlimited" strength policy files can be used instead, which contain
-# no restrictions on cryptographic strengths.
+# In some environments, certain algorithms or key lengths may be undesirable
+# for signed JAR validation.  For example, "MD2" is generally no longer
+# considered to be a secure hash algorithm.  This section describes the
+# mechanism for disabling algorithms based on algorithm name and/or key length.
+# JARs signed with any of the disabled algorithms or key sizes will be treated
+# as unsigned.
 #
-# YOU ARE ADVISED TO CONSULT YOUR EXPORT/IMPORT CONTROL COUNSEL OR ATTORNEY
-# TO DETERMINE THE EXACT REQUIREMENTS.
+# The syntax of the disabled algorithm string is described as follows:
+#   DisabledAlgorithms:
+#       " DisabledAlgorithm { , DisabledAlgorithm } "
 #
-# <java-home> (below) refers to the directory where the JRE was
-# installed. It is determined based on whether you are running JCE
-# on a JRE or a JRE contained within the Java Development Kit, or
-# JDK(TM). The JDK contains the JRE, but at a different level in the
-# file hierarchy. For example, if the JDK is installed in
-# /home/user1/jdk1.8.0 on Unix or in C:\jdk1.8.0 on Windows, then
-# <java-home> is:
+#   DisabledAlgorithm:
+#       AlgorithmName [Constraint]
 #
-#  /home/user1/jdk1.8.0/jre           [Unix]
-#  C:\jdk1.8.0\jre                    [Windows]
+#   AlgorithmName:
+#       (see below)
 #
-# If on the other hand the JRE is installed in /home/user1/jre1.8.0
-# on Unix or in C:\jre1.8.0 on Windows, and the JDK is not
-# installed, then <java-home> is:
+#   Constraint:
+#       KeySizeConstraint
 #
-#  /home/user1/jre1.8.0               [Unix]
-#  C:\jre1.8.0                        [Windows]
+#   KeySizeConstraint:
+#       keySize Operator KeyLength
 #
-# On Windows, for each JDK installation, there may be additional
-# JREs installed under the "Program Files" directory. Please make
-# sure that you install the unlimited strength policy JAR files
-# for all JREs that you plan to use.
+#   Operator:
+#       <= | < | == | != | >= | >
 #
-# The policy files are jar files organized into subdirectories of
-# <java-home>/lib/security/policy.  Each directory contains a complete
-# set of policy files.
+#   KeyLength:
+#       Integer value of the algorithm's key length in bits
 #
-# The "crypto.policy" Security property controls the directory selection,
-# and thus the effective cryptographic policy.
+# Note: This property is currently used by the JDK Reference
+# implementation. It is not guaranteed to be examined and used by other
+# implementations.
 #
-# The default set of directories is:
-#
-#     limited | unlimited
-#
-# however other directories can be created and configured.
-#
-# To support older JDK Update releases, the crypto.policy property
-# is not defined by default. When the property is not defined, an
-# update release binary aware of the new property will use the following
-# logic to decide what crypto policy files get used :
-#
-# * If the US_export_policy.jar and local_policy.jar files are located
-# in the (legacy) <java-home>/lib/security directory, then the rules
-# embedded in those jar files will be used. This helps preserve compatibility
-# for users upgrading from an older installation.
-#
-# * If crypto.policy is not defined and no such jar files are present in
-# the legacy locations, then the JDK will use the limited settings
-# (equivalent to crypto.policy=limited)
-#
-# Please see the JCA documentation for additional information on these
-# files and formats.
-#crypto.policy=unlimited
+jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024
diff --git a/jdk/src/share/lib/security/java.security-solaris b/jdk/src/share/lib/security/java.security-solaris
index f4209ca..078fd66 100644
--- a/jdk/src/share/lib/security/java.security-solaris
+++ b/jdk/src/share/lib/security/java.security-solaris
@@ -485,43 +485,6 @@
 #
 jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
 
-# Algorithm restrictions for signed JAR files
-#
-# In some environments, certain algorithms or key lengths may be undesirable
-# for signed JAR validation.  For example, "MD2" is generally no longer
-# considered to be a secure hash algorithm.  This section describes the
-# mechanism for disabling algorithms based on algorithm name and/or key length.
-# JARs signed with any of the disabled algorithms or key sizes will be treated
-# as unsigned.
-#
-# The syntax of the disabled algorithm string is described as follows:
-#   DisabledAlgorithms:
-#       " DisabledAlgorithm { , DisabledAlgorithm } "
-#
-#   DisabledAlgorithm:
-#       AlgorithmName [Constraint]
-#
-#   AlgorithmName:
-#       (see below)
-#
-#   Constraint:
-#       KeySizeConstraint
-#
-#   KeySizeConstraint:
-#       keySize Operator KeyLength
-#
-#   Operator:
-#       <= | < | == | != | >= | >
-#
-#   KeyLength:
-#       Integer value of the algorithm's key length in bits
-#
-# Note: This property is currently used by the JDK Reference
-# implementation. It is not guaranteed to be examined and used by other
-# implementations.
-#
-jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
-
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
 # (SSL/TLS) processing
 #
@@ -664,67 +627,39 @@
 #       EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381 \
 #       FFFFFFFF FFFFFFFF, 2}
 
-# Cryptographic Jurisdiction Policy defaults
+# Algorithm restrictions for signed JAR files
 #
-# Due to the import control restrictions of some countries, the default
-# JCE policy files allow for strong but "limited" cryptographic key
-# lengths to be used.  If your country's cryptographic regulations allow,
-# the "unlimited" strength policy files can be used instead, which contain
-# no restrictions on cryptographic strengths.
+# In some environments, certain algorithms or key lengths may be undesirable
+# for signed JAR validation.  For example, "MD2" is generally no longer
+# considered to be a secure hash algorithm.  This section describes the
+# mechanism for disabling algorithms based on algorithm name and/or key length.
+# JARs signed with any of the disabled algorithms or key sizes will be treated
+# as unsigned.
 #
-# YOU ARE ADVISED TO CONSULT YOUR EXPORT/IMPORT CONTROL COUNSEL OR ATTORNEY
-# TO DETERMINE THE EXACT REQUIREMENTS.
+# The syntax of the disabled algorithm string is described as follows:
+#   DisabledAlgorithms:
+#       " DisabledAlgorithm { , DisabledAlgorithm } "
 #
-# <java-home> (below) refers to the directory where the JRE was
-# installed. It is determined based on whether you are running JCE
-# on a JRE or a JRE contained within the Java Development Kit, or
-# JDK(TM). The JDK contains the JRE, but at a different level in the
-# file hierarchy. For example, if the JDK is installed in
-# /home/user1/jdk1.8.0 on Unix or in C:\jdk1.8.0 on Windows, then
-# <java-home> is:
+#   DisabledAlgorithm:
+#       AlgorithmName [Constraint]
 #
-#  /home/user1/jdk1.8.0/jre           [Unix]
-#  C:\jdk1.8.0\jre                    [Windows]
+#   AlgorithmName:
+#       (see below)
 #
-# If on the other hand the JRE is installed in /home/user1/jre1.8.0
-# on Unix or in C:\jre1.8.0 on Windows, and the JDK is not
-# installed, then <java-home> is:
+#   Constraint:
+#       KeySizeConstraint
 #
-#  /home/user1/jre1.8.0               [Unix]
-#  C:\jre1.8.0                        [Windows]
+#   KeySizeConstraint:
+#       keySize Operator KeyLength
 #
-# On Windows, for each JDK installation, there may be additional
-# JREs installed under the "Program Files" directory. Please make
-# sure that you install the unlimited strength policy JAR files
-# for all JREs that you plan to use.
+#   Operator:
+#       <= | < | == | != | >= | >
 #
-# The policy files are jar files organized into subdirectories of
-# <java-home>/lib/security/policy.  Each directory contains a complete
-# set of policy files.
+#   KeyLength:
+#       Integer value of the algorithm's key length in bits
 #
-# The "crypto.policy" Security property controls the directory selection,
-# and thus the effective cryptographic policy.
+# Note: This property is currently used by the JDK Reference
+# implementation. It is not guaranteed to be examined and used by other
+# implementations.
 #
-# The default set of directories is:
-#
-#     limited | unlimited
-#
-# however other directories can be created and configured.
-#
-# To support older JDK Update releases, the crypto.policy property
-# is not defined by default. When the property is not defined, an
-# update release binary aware of the new property will use the following
-# logic to decide what crypto policy files get used :
-#
-# * If the US_export_policy.jar and local_policy.jar files are located
-# in the (legacy) <java-home>/lib/security directory, then the rules
-# embedded in those jar files will be used. This helps preserve compatibility
-# for users upgrading from an older installation.
-#
-# * If crypto.policy is not defined and no such jar files are present in
-# the legacy locations, then the JDK will use the limited settings
-# (equivalent to crypto.policy=limited)
-#
-# Please see the JCA documentation for additional information on these
-# files and formats.
-#crypto.policy=unlimited
+jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024
diff --git a/jdk/src/share/lib/security/java.security-windows b/jdk/src/share/lib/security/java.security-windows
index 99b1466..d2ddbe5 100644
--- a/jdk/src/share/lib/security/java.security-windows
+++ b/jdk/src/share/lib/security/java.security-windows
@@ -486,43 +486,6 @@
 #
 jdk.certpath.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
 
-# Algorithm restrictions for signed JAR files
-#
-# In some environments, certain algorithms or key lengths may be undesirable
-# for signed JAR validation.  For example, "MD2" is generally no longer
-# considered to be a secure hash algorithm.  This section describes the
-# mechanism for disabling algorithms based on algorithm name and/or key length.
-# JARs signed with any of the disabled algorithms or key sizes will be treated
-# as unsigned.
-#
-# The syntax of the disabled algorithm string is described as follows:
-#   DisabledAlgorithms:
-#       " DisabledAlgorithm { , DisabledAlgorithm } "
-#
-#   DisabledAlgorithm:
-#       AlgorithmName [Constraint]
-#
-#   AlgorithmName:
-#       (see below)
-#
-#   Constraint:
-#       KeySizeConstraint
-#
-#   KeySizeConstraint:
-#       keySize Operator KeyLength
-#
-#   Operator:
-#       <= | < | == | != | >= | >
-#
-#   KeyLength:
-#       Integer value of the algorithm's key length in bits
-#
-# Note: This property is currently used by the JDK Reference
-# implementation. It is not guaranteed to be examined and used by other
-# implementations.
-#
-jdk.jar.disabledAlgorithms=MD2, MD5, RSA keySize < 1024
-
 # Algorithm restrictions for Secure Socket Layer/Transport Layer Security
 # (SSL/TLS) processing
 #
@@ -665,67 +628,39 @@
 #       EE386BFB 5A899FA5 AE9F2411 7C4B1FE6 49286651 ECE65381 \
 #       FFFFFFFF FFFFFFFF, 2}
 
-# Cryptographic Jurisdiction Policy defaults
+# Algorithm restrictions for signed JAR files
 #
-# Due to the import control restrictions of some countries, the default
-# JCE policy files allow for strong but "limited" cryptographic key
-# lengths to be used.  If your country's cryptographic regulations allow,
-# the "unlimited" strength policy files can be used instead, which contain
-# no restrictions on cryptographic strengths.
+# In some environments, certain algorithms or key lengths may be undesirable
+# for signed JAR validation.  For example, "MD2" is generally no longer
+# considered to be a secure hash algorithm.  This section describes the
+# mechanism for disabling algorithms based on algorithm name and/or key length.
+# JARs signed with any of the disabled algorithms or key sizes will be treated
+# as unsigned.
 #
-# YOU ARE ADVISED TO CONSULT YOUR EXPORT/IMPORT CONTROL COUNSEL OR ATTORNEY
-# TO DETERMINE THE EXACT REQUIREMENTS.
+# The syntax of the disabled algorithm string is described as follows:
+#   DisabledAlgorithms:
+#       " DisabledAlgorithm { , DisabledAlgorithm } "
 #
-# <java-home> (below) refers to the directory where the JRE was
-# installed. It is determined based on whether you are running JCE
-# on a JRE or a JRE contained within the Java Development Kit, or
-# JDK(TM). The JDK contains the JRE, but at a different level in the
-# file hierarchy. For example, if the JDK is installed in
-# /home/user1/jdk1.8.0 on Unix or in C:\jdk1.8.0 on Windows, then
-# <java-home> is:
+#   DisabledAlgorithm:
+#       AlgorithmName [Constraint]
 #
-#  /home/user1/jdk1.8.0/jre           [Unix]
-#  C:\jdk1.8.0\jre                    [Windows]
+#   AlgorithmName:
+#       (see below)
 #
-# If on the other hand the JRE is installed in /home/user1/jre1.8.0
-# on Unix or in C:\jre1.8.0 on Windows, and the JDK is not
-# installed, then <java-home> is:
+#   Constraint:
+#       KeySizeConstraint
 #
-#  /home/user1/jre1.8.0               [Unix]
-#  C:\jre1.8.0                        [Windows]
+#   KeySizeConstraint:
+#       keySize Operator KeyLength
 #
-# On Windows, for each JDK installation, there may be additional
-# JREs installed under the "Program Files" directory. Please make
-# sure that you install the unlimited strength policy JAR files
-# for all JREs that you plan to use.
+#   Operator:
+#       <= | < | == | != | >= | >
 #
-# The policy files are jar files organized into subdirectories of
-# <java-home>/lib/security/policy.  Each directory contains a complete
-# set of policy files.
+#   KeyLength:
+#       Integer value of the algorithm's key length in bits
 #
-# The "crypto.policy" Security property controls the directory selection,
-# and thus the effective cryptographic policy.
+# Note: This property is currently used by the JDK Reference
+# implementation. It is not guaranteed to be examined and used by other
+# implementations.
 #
-# The default set of directories is:
-#
-#     limited | unlimited
-#
-# however other directories can be created and configured.
-#
-# To support older JDK Update releases, the crypto.policy property
-# is not defined by default. When the property is not defined, an
-# update release binary aware of the new property will use the following
-# logic to decide what crypto policy files get used :
-#
-# * If the US_export_policy.jar and local_policy.jar files are located
-# in the (legacy) <java-home>/lib/security directory, then the rules
-# embedded in those jar files will be used. This helps preserve compatibility
-# for users upgrading from an older installation.
-#
-# * If crypto.policy is not defined and no such jar files are present in
-# the legacy locations, then the JDK will use the limited settings
-# (equivalent to crypto.policy=limited)
-#
-# Please see the JCA documentation for additional information on these
-# files and formats.
-#crypto.policy=unlimited
+jdk.jar.disabledAlgorithms=MD2, RSA keySize < 1024
diff --git a/jdk/src/share/lib/security/sunpkcs11-solaris.cfg b/jdk/src/share/lib/security/sunpkcs11-solaris.cfg
index 29aae46..4cade8e 100644
--- a/jdk/src/share/lib/security/sunpkcs11-solaris.cfg
+++ b/jdk/src/share/lib/security/sunpkcs11-solaris.cfg
@@ -18,7 +18,6 @@
 
 disabledMechanisms = {
   CKM_DSA_KEY_PAIR_GEN
-  SecureRandom
 # the following mechanisms are disabled due to performance issues
 # (Solaris bug 6337157)
   CKM_DSA_SHA1
diff --git a/jdk/src/share/native/com/sun/tools/jdi/SharedMemoryConnection.c b/jdk/src/share/native/com/sun/tools/jdi/SharedMemoryConnection.c
index e28efe6..5936b5a 100644
--- a/jdk/src/share/native/com/sun/tools/jdi/SharedMemoryConnection.c
+++ b/jdk/src/share/native/com/sun/tools/jdi/SharedMemoryConnection.c
@@ -174,20 +174,9 @@
      * Get the packet header
      */
     (*env)->GetByteArrayRegion(env, b, 0, sizeof(pktHeader), pktHeader);
-    if ((*env)->ExceptionOccurred(env)) {
-        /* b shorter than sizeof(pktHeader) */
-        return;
-    }
 
     total_length = (int)pktHeader[3] | ((int)pktHeader[2] << 8) |
                    ((int)pktHeader[1] << 16) | ((int)pktHeader[0] << 24);
-
-    if (total_length < sizeof(pktHeader)) {
-        throwException(env, "java/lang/IllegalArgumentException",
-                            "JDWP header is incorrect");
-        return;
-    }
-
     /*
      * The id field is in big endian (also errorCode field in the case
      * of reply packets).
@@ -206,9 +195,9 @@
     }
 
     /*
-     * The length of the JDWP packet is sizeof(pktHeader) + data
+     * The length of the JDWP packet is 11 + data
      */
-    data_length = total_length - sizeof(pktHeader);
+    data_length = total_length - 11;
 
     if (data_length == 0) {
         data = NULL;
@@ -220,7 +209,7 @@
             return;
         }
 
-        (*env)->GetByteArrayRegion(env, b, sizeof(pktHeader), /*sizeof(CmdPacket)+4*/ data_length, data);
+        (*env)->GetByteArrayRegion(env, b, 11, /*sizeof(CmdPacket)+4*/ data_length, data);
         if ((*env)->ExceptionOccurred(env)) {
             free(data);
             return;
diff --git a/jdk/src/share/native/java/io/io_util.c b/jdk/src/share/native/java/io/io_util.c
index f256af4..5dd8223 100644
--- a/jdk/src/share/native/java/io/io_util.c
+++ b/jdk/src/share/native/java/io/io_util.c
@@ -216,7 +216,6 @@
 #else
         why = JNU_NewStringPlatform(env, buf);
 #endif
-        CHECK_NULL(why);
     }
     x = JNU_NewObjectByName(env,
                             "java/io/FileNotFoundException",
diff --git a/jdk/src/share/native/java/lang/ClassLoader.c b/jdk/src/share/native/java/lang/ClassLoader.c
index 40b0b85..1d9da67 100644
--- a/jdk/src/share/native/java/lang/ClassLoader.c
+++ b/jdk/src/share/native/java/lang/ClassLoader.c
@@ -132,6 +132,7 @@
     if (name != NULL) {
         utfName = getUTF(env, name, buf, sizeof(buf));
         if (utfName == NULL) {
+            JNU_ThrowOutOfMemoryError(env, NULL);
             goto free_body;
         }
         VerifyFixClassname(utfName);
@@ -142,6 +143,7 @@
     if (source != NULL) {
         utfSource = getUTF(env, source, sourceBuf, sizeof(sourceBuf));
         if (utfSource == NULL) {
+            JNU_ThrowOutOfMemoryError(env, NULL);
             goto free_utfName;
         }
     } else {
@@ -515,6 +517,7 @@
     procHandle = getProcessHandle();
     cname = JNU_GetStringPlatformChars(env, name, 0);
     if (cname == NULL) {
+        JNU_ThrowOutOfMemoryError(env, NULL);
         return NULL;
     }
     // Copy name Skipping PREFIX
diff --git a/jdk/src/share/native/java/lang/System.c b/jdk/src/share/native/java/lang/System.c
index 5c36460..cb0044f 100644
--- a/jdk/src/share/native/java/lang/System.c
+++ b/jdk/src/share/native/java/lang/System.c
@@ -56,56 +56,44 @@
     return JVM_IHashCode(env, x);
 }
 
-#define PUTPROP(props, key, val)                                     \
-    if (1) {                                                         \
-        jstring jkey, jval;                                          \
-        jobject r;                                                   \
-        jkey = (*env)->NewStringUTF(env, key);                       \
-        if (jkey == NULL) return NULL;                               \
-        jval = (*env)->NewStringUTF(env, val);                       \
-        if (jval == NULL) return NULL;                               \
-        r = (*env)->CallObjectMethod(env, props, putID, jkey, jval); \
-        if ((*env)->ExceptionOccurred(env)) return NULL;             \
-        (*env)->DeleteLocalRef(env, jkey);                           \
-        (*env)->DeleteLocalRef(env, jval);                           \
-        (*env)->DeleteLocalRef(env, r);                              \
+#define PUTPROP(props, key, val) \
+    if (1) { \
+        jstring jkey = (*env)->NewStringUTF(env, key); \
+        jstring jval = (*env)->NewStringUTF(env, val); \
+        jobject r = (*env)->CallObjectMethod(env, props, putID, jkey, jval); \
+        if ((*env)->ExceptionOccurred(env)) return NULL; \
+        (*env)->DeleteLocalRef(env, jkey); \
+        (*env)->DeleteLocalRef(env, jval); \
+        (*env)->DeleteLocalRef(env, r); \
     } else ((void) 0)
 
 /*  "key" is a char type string with only ASCII character in it.
     "val" is a nchar (typedefed in java_props.h) type string  */
 
-#define PUTPROP_ForPlatformNString(props, key, val)                  \
-    if (1) {                                                         \
-        jstring jkey, jval;                                          \
-        jobject r;                                                   \
-        jkey = (*env)->NewStringUTF(env, key);                       \
-        if (jkey == NULL) return NULL;                               \
-        jval = GetStringPlatform(env, val);                          \
-        if (jval == NULL) return NULL;                               \
-        r = (*env)->CallObjectMethod(env, props, putID, jkey, jval); \
-        if ((*env)->ExceptionOccurred(env)) return NULL;             \
-        (*env)->DeleteLocalRef(env, jkey);                           \
-        (*env)->DeleteLocalRef(env, jval);                           \
-        (*env)->DeleteLocalRef(env, r);                              \
+#define PUTPROP_ForPlatformNString(props, key, val) \
+    if (1) { \
+        jstring jkey = (*env)->NewStringUTF(env, key);  \
+        jstring jval = GetStringPlatform(env, val); \
+        jobject r = (*env)->CallObjectMethod(env, props, putID, jkey, jval); \
+        if ((*env)->ExceptionOccurred(env)) return NULL; \
+        (*env)->DeleteLocalRef(env, jkey); \
+        (*env)->DeleteLocalRef(env, jval); \
+        (*env)->DeleteLocalRef(env, r); \
     } else ((void) 0)
-#define REMOVEPROP(props, key)                                    \
-    if (1) {                                                      \
-        jstring jkey;                                             \
-        jobject r;                                                \
-        jkey = JNU_NewStringPlatform(env, key);                   \
-        if (jkey == NULL) return NULL;                            \
-        r = (*env)->CallObjectMethod(env, props, removeID, jkey); \
-        if ((*env)->ExceptionOccurred(env)) return NULL;          \
-        (*env)->DeleteLocalRef(env, jkey);                        \
-        (*env)->DeleteLocalRef(env, r);                           \
+#define REMOVEPROP(props, key) \
+    if (1) { \
+        jstring jkey = JNU_NewStringPlatform(env, key); \
+        jobject r = (*env)->CallObjectMethod(env, props, removeID, jkey); \
+        if ((*env)->ExceptionOccurred(env)) return NULL; \
+        (*env)->DeleteLocalRef(env, jkey); \
+        (*env)->DeleteLocalRef(env, r); \
     } else ((void) 0)
-#define GETPROP(props, key, jret)                                     \
-    if (1) {                                                          \
-        jstring jkey = JNU_NewStringPlatform(env, key);               \
-        if (jkey == NULL) return NULL;                                \
+#define GETPROP(props, key, jret) \
+    if (1) { \
+        jstring jkey = JNU_NewStringPlatform(env, key); \
         jret = (*env)->CallObjectMethod(env, props, getPropID, jkey); \
-        if ((*env)->ExceptionOccurred(env)) return NULL;              \
-        (*env)->DeleteLocalRef(env, jkey);                            \
+        if ((*env)->ExceptionOccurred(env)) return NULL; \
+        (*env)->DeleteLocalRef(env, jkey); \
     } else ((void) 0)
 
 #ifndef VENDOR /* Third party may overwrite this. */
@@ -181,31 +169,23 @@
 Java_java_lang_System_initProperties(JNIEnv *env, jclass cla, jobject props)
 {
     char buf[128];
-    java_props_t *sprops;
-    jmethodID putID, removeID, getPropID;
+    java_props_t *sprops = GetJavaProperties(env);
+    jmethodID putID = (*env)->GetMethodID(env,
+                                          (*env)->GetObjectClass(env, props),
+                                          "put",
+            "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
+    jmethodID removeID = (*env)->GetMethodID(env,
+                                          (*env)->GetObjectClass(env, props),
+                                          "remove",
+            "(Ljava/lang/Object;)Ljava/lang/Object;");
+    jmethodID getPropID = (*env)->GetMethodID(env,
+                                          (*env)->GetObjectClass(env, props),
+                                          "getProperty",
+            "(Ljava/lang/String;)Ljava/lang/String;");
     jobject ret = NULL;
     jstring jVMVal = NULL;
 
-    sprops = GetJavaProperties(env);
-    CHECK_NULL_RETURN(sprops, NULL);
-
-    putID = (*env)->GetMethodID(env,
-                                (*env)->GetObjectClass(env, props),
-                                "put",
-            "(Ljava/lang/Object;Ljava/lang/Object;)Ljava/lang/Object;");
-    CHECK_NULL_RETURN(putID, NULL);
-
-    removeID = (*env)->GetMethodID(env,
-                                   (*env)->GetObjectClass(env, props),
-                                   "remove",
-            "(Ljava/lang/Object;)Ljava/lang/Object;");
-    CHECK_NULL_RETURN(removeID, NULL);
-
-    getPropID = (*env)->GetMethodID(env,
-                                    (*env)->GetObjectClass(env, props),
-                                    "getProperty",
-            "(Ljava/lang/String;)Ljava/lang/String;");
-    CHECK_NULL_RETURN(getPropID, NULL);
+    if (sprops == NULL || putID == NULL ) return NULL;
 
     PUTPROP(props, "java.specification.version",
             JDK_MAJOR_VERSION "." JDK_MINOR_VERSION);
@@ -402,7 +382,6 @@
     GETPROP(props, "sun.locale.formatasdefault", jVMVal);
     if (jVMVal) {
         const char * val = (*env)->GetStringUTFChars(env, jVMVal, 0);
-        CHECK_NULL_RETURN(val, NULL);
         fmtdefault = !strcmp(val, "true");
         (*env)->ReleaseStringUTFChars(env, jVMVal, val);
         (*env)->DeleteLocalRef(env, jVMVal);
diff --git a/jdk/src/share/native/java/net/Inet4Address.c b/jdk/src/share/native/java/net/Inet4Address.c
index cc43241..62ad3d6 100644
--- a/jdk/src/share/native/java/net/Inet4Address.c
+++ b/jdk/src/share/native/java/net/Inet4Address.c
@@ -34,8 +34,6 @@
 jclass ia4_class;
 jmethodID ia4_ctrID;
 
-static int ia4_initialized = 0;
-
 /*
  * Class:     java_net_Inet4Address
  * Method:    init
@@ -43,13 +41,9 @@
  */
 JNIEXPORT void JNICALL
 Java_java_net_Inet4Address_init(JNIEnv *env, jclass cls) {
-    if (!ia4_initialized) {
-        jclass c = (*env)->FindClass(env, "java/net/Inet4Address");
-        CHECK_NULL(c);
-        ia4_class = (*env)->NewGlobalRef(env, c);
-        CHECK_NULL(ia4_class);
-        ia4_ctrID = (*env)->GetMethodID(env, ia4_class, "<init>", "()V");
-        CHECK_NULL(ia4_ctrID);
-        ia4_initialized = 1;
-    }
+    jclass c = (*env)->FindClass(env, "java/net/Inet4Address");
+    CHECK_NULL(c);
+    ia4_class = (*env)->NewGlobalRef(env, c);
+    CHECK_NULL(ia4_class);
+    ia4_ctrID = (*env)->GetMethodID(env, ia4_class, "<init>", "()V");
 }
diff --git a/jdk/src/share/native/java/net/Inet6Address.c b/jdk/src/share/native/java/net/Inet6Address.c
index 3d0151a..9b828af 100644
--- a/jdk/src/share/native/java/net/Inet6Address.c
+++ b/jdk/src/share/native/java/net/Inet6Address.c
@@ -42,8 +42,6 @@
 jfieldID ia6_scopeifnameID;
 jmethodID ia6_ctrID;
 
-static int ia6_initialized = 0;
-
 /*
  * Class:     java_net_Inet6Address
  * Method:    init
@@ -51,28 +49,24 @@
  */
 JNIEXPORT void JNICALL
 Java_java_net_Inet6Address_init(JNIEnv *env, jclass cls) {
-    if (!ia6_initialized) {
-        jclass ia6h_class;
-        jclass c = (*env)->FindClass(env, "java/net/Inet6Address");
-        CHECK_NULL(c);
-        ia6_class = (*env)->NewGlobalRef(env, c);
-        CHECK_NULL(ia6_class);
-        ia6h_class = (*env)->FindClass(env, "java/net/Inet6Address$Inet6AddressHolder");
-        CHECK_NULL(ia6h_class);
-        ia6_holder6ID = (*env)->GetFieldID(env, ia6_class, "holder6", "Ljava/net/Inet6Address$Inet6AddressHolder;");
-        CHECK_NULL(ia6_holder6ID);
-        ia6_ipaddressID = (*env)->GetFieldID(env, ia6h_class, "ipaddress", "[B");
-        CHECK_NULL(ia6_ipaddressID);
-        ia6_scopeidID = (*env)->GetFieldID(env, ia6h_class, "scope_id", "I");
-        CHECK_NULL(ia6_scopeidID);
-        ia6_cachedscopeidID = (*env)->GetFieldID(env, ia6_class, "cached_scope_id", "I");
-        CHECK_NULL(ia6_cachedscopeidID);
-        ia6_scopeidsetID = (*env)->GetFieldID(env, ia6h_class, "scope_id_set", "Z");
-        CHECK_NULL(ia6_scopeidsetID);
-        ia6_scopeifnameID = (*env)->GetFieldID(env, ia6h_class, "scope_ifname", "Ljava/net/NetworkInterface;");
-        CHECK_NULL(ia6_scopeifnameID);
-        ia6_ctrID = (*env)->GetMethodID(env, ia6_class, "<init>", "()V");
-        CHECK_NULL(ia6_ctrID);
-        ia6_initialized = 1;
-    }
+    jclass ia6h_class;
+    jclass c = (*env)->FindClass(env, "java/net/Inet6Address");
+    CHECK_NULL(c);
+    ia6_class = (*env)->NewGlobalRef(env, c);
+    CHECK_NULL(ia6_class);
+    ia6h_class = (*env)->FindClass(env, "java/net/Inet6Address$Inet6AddressHolder");
+    CHECK_NULL(ia6h_class);
+    ia6_holder6ID = (*env)->GetFieldID(env, ia6_class, "holder6", "Ljava/net/Inet6Address$Inet6AddressHolder;");
+    CHECK_NULL(ia6_holder6ID);
+    ia6_ipaddressID = (*env)->GetFieldID(env, ia6h_class, "ipaddress", "[B");
+    CHECK_NULL(ia6_ipaddressID);
+    ia6_scopeidID = (*env)->GetFieldID(env, ia6h_class, "scope_id", "I");
+    CHECK_NULL(ia6_scopeidID);
+    ia6_cachedscopeidID = (*env)->GetFieldID(env, ia6_class, "cached_scope_id", "I");
+    CHECK_NULL(ia6_cachedscopeidID);
+    ia6_scopeidsetID = (*env)->GetFieldID(env, ia6h_class, "scope_id_set", "Z");
+    CHECK_NULL(ia6_scopeidsetID);
+    ia6_scopeifnameID = (*env)->GetFieldID(env, ia6h_class, "scope_ifname", "Ljava/net/NetworkInterface;");
+    CHECK_NULL(ia6_scopeifnameID);
+    ia6_ctrID = (*env)->GetMethodID(env, ia6_class, "<init>", "()V");
 }
diff --git a/jdk/src/share/native/java/net/InetAddress.c b/jdk/src/share/native/java/net/InetAddress.c
index a0d55c2..607ed35 100644
--- a/jdk/src/share/native/java/net/InetAddress.c
+++ b/jdk/src/share/native/java/net/InetAddress.c
@@ -41,8 +41,6 @@
 jfieldID iac_origHostNameID;
 jfieldID ia_preferIPv6AddressID;
 
-static int ia_initialized = 0;
-
 /*
  * Class:     java_net_InetAddress
  * Method:    init
@@ -50,28 +48,23 @@
  */
 JNIEXPORT void JNICALL
 Java_java_net_InetAddress_init(JNIEnv *env, jclass cls) {
-    if (!ia_initialized) {
-        jclass c = (*env)->FindClass(env,"java/net/InetAddress");
-        CHECK_NULL(c);
-        ia_class = (*env)->NewGlobalRef(env, c);
-        CHECK_NULL(ia_class);
-        c = (*env)->FindClass(env,"java/net/InetAddress$InetAddressHolder");
-        CHECK_NULL(c);
-        iac_class = (*env)->NewGlobalRef(env, c);
-        CHECK_NULL(iac_class);
-        ia_holderID = (*env)->GetFieldID(env, ia_class, "holder", "Ljava/net/InetAddress$InetAddressHolder;");
-        CHECK_NULL(ia_holderID);
-        ia_preferIPv6AddressID = (*env)->GetStaticFieldID(env, ia_class, "preferIPv6Address", "Z");
-        CHECK_NULL(ia_preferIPv6AddressID);
+    jclass c = (*env)->FindClass(env,"java/net/InetAddress");
+    CHECK_NULL(c);
+    ia_class = (*env)->NewGlobalRef(env, c);
+    CHECK_NULL(ia_class);
+    c = (*env)->FindClass(env,"java/net/InetAddress$InetAddressHolder");
+    CHECK_NULL(c);
+    iac_class = (*env)->NewGlobalRef(env, c);
+    ia_holderID = (*env)->GetFieldID(env, ia_class, "holder", "Ljava/net/InetAddress$InetAddressHolder;");
+    CHECK_NULL(ia_holderID);
+    ia_preferIPv6AddressID = (*env)->GetStaticFieldID(env, ia_class, "preferIPv6Address", "Z");
+    CHECK_NULL(ia_preferIPv6AddressID);
 
-        iac_addressID = (*env)->GetFieldID(env, iac_class, "address", "I");
-        CHECK_NULL(iac_addressID);
-        iac_familyID = (*env)->GetFieldID(env, iac_class, "family", "I");
-        CHECK_NULL(iac_familyID);
-        iac_hostNameID = (*env)->GetFieldID(env, iac_class, "hostName", "Ljava/lang/String;");
-        CHECK_NULL(iac_hostNameID);
-        iac_origHostNameID = (*env)->GetFieldID(env, iac_class, "originalHostName", "Ljava/lang/String;");
-        CHECK_NULL(iac_origHostNameID);
-        ia_initialized = 1;
-    }
+    iac_addressID = (*env)->GetFieldID(env, iac_class, "address", "I");
+    CHECK_NULL(iac_addressID);
+    iac_familyID = (*env)->GetFieldID(env, iac_class, "family", "I");
+    CHECK_NULL(iac_familyID);
+    iac_hostNameID = (*env)->GetFieldID(env, iac_class, "hostName", "Ljava/lang/String;");
+    CHECK_NULL(iac_hostNameID);
+    iac_origHostNameID = (*env)->GetFieldID(env, iac_class, "originalHostName", "Ljava/lang/String;");
 }
diff --git a/jdk/src/share/native/java/net/net_util.c b/jdk/src/share/native/java/net/net_util.c
index 2194e2e..56edb63 100644
--- a/jdk/src/share/native/java/net/net_util.c
+++ b/jdk/src/share/native/java/net/net_util.c
@@ -75,14 +75,11 @@
 
 static int initialized = 0;
 
-JNIEXPORT void JNICALL initInetAddressIDs(JNIEnv *env) {
+static void initInetAddrs(JNIEnv *env) {
     if (!initialized) {
         Java_java_net_InetAddress_init(env, 0);
-        JNU_CHECK_EXCEPTION(env);
         Java_java_net_Inet4Address_init(env, 0);
-        JNU_CHECK_EXCEPTION(env);
         Java_java_net_Inet6Address_init(env, 0);
-        JNU_CHECK_EXCEPTION(env);
         initialized = 1;
     }
 }
@@ -103,32 +100,47 @@
  * get_ methods that return objects return NULL on error.
  */
 jobject getInet6Address_scopeifname(JNIEnv *env, jobject iaObj) {
-    jobject holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, NULL);
     return (*env)->GetObjectField(env, holder, ia6_scopeifnameID);
 }
 
 int setInet6Address_scopeifname(JNIEnv *env, jobject iaObj, jobject scopeifname) {
-    jobject holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, JNI_FALSE);
     (*env)->SetObjectField(env, holder, ia6_scopeifnameID, scopeifname);
     return JNI_TRUE;
 }
 
 int getInet6Address_scopeid_set(JNIEnv *env, jobject iaObj) {
-    jobject holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, -1);
     return (*env)->GetBooleanField(env, holder, ia6_scopeidsetID);
 }
 
 int getInet6Address_scopeid(JNIEnv *env, jobject iaObj) {
-    jobject holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, -1);
     return (*env)->GetIntField(env, holder, ia6_scopeidID);
 }
 
 int setInet6Address_scopeid(JNIEnv *env, jobject iaObj, int scopeid) {
-    jobject holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, JNI_FALSE);
     (*env)->SetIntField(env, holder, ia6_scopeidID, scopeid);
     if (scopeid > 0) {
@@ -142,6 +154,7 @@
     jobject holder, addr;
     jbyteArray barr;
 
+    initInetAddrs(env);
     holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, JNI_FALSE);
     addr =  (*env)->GetObjectField(env, holder, ia6_ipaddressID);
@@ -154,6 +167,7 @@
     jobject holder;
     jbyteArray addr;
 
+    initInetAddrs(env);
     holder = (*env)->GetObjectField(env, iaObj, ia6_holder6ID);
     CHECK_NULL_RETURN(holder, JNI_FALSE);
     addr =  (jbyteArray)(*env)->GetObjectField(env, holder, ia6_ipaddressID);
@@ -167,39 +181,53 @@
 }
 
 void setInetAddress_addr(JNIEnv *env, jobject iaObj, int address) {
-    jobject holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
+    jobject holder;
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
     (*env)->SetIntField(env, holder, iac_addressID, address);
 }
 
 void setInetAddress_family(JNIEnv *env, jobject iaObj, int family) {
-    jobject holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
+    jobject holder;
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
     (*env)->SetIntField(env, holder, iac_familyID, family);
 }
 
 void setInetAddress_hostName(JNIEnv *env, jobject iaObj, jobject host) {
-    jobject holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
+    jobject holder;
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
     (*env)->SetObjectField(env, holder, iac_hostNameID, host);
     (*env)->SetObjectField(env, holder, iac_origHostNameID, host);
 }
 
 int getInetAddress_addr(JNIEnv *env, jobject iaObj) {
-    jobject holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
+    jobject holder;
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
     return (*env)->GetIntField(env, holder, iac_addressID);
 }
 
 int getInetAddress_family(JNIEnv *env, jobject iaObj) {
-    jobject holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
+    jobject holder;
+
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
     return (*env)->GetIntField(env, holder, iac_familyID);
 }
 
 jobject getInetAddress_hostName(JNIEnv *env, jobject iaObj) {
-    jobject holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
+    jobject holder;
+    initInetAddrs(env);
+    holder = (*env)->GetObjectField(env, iaObj, ia_holderID);
     return (*env)->GetObjectField(env, holder, iac_hostNameID);
 }
 
 JNIEXPORT jobject JNICALL
 NET_SockaddrToInetAddress(JNIEnv *env, struct sockaddr *him, int *port) {
     jobject iaObj;
+    initInetAddrs(env);
 #ifdef AF_INET6
     if (him->sa_family == AF_INET6) {
         jbyteArray ipaddress;
@@ -211,15 +239,31 @@
         jbyte *caddr = (jbyte *)&(him6->sin6_addr);
         if (NET_IsIPv4Mapped(caddr)) {
             int address;
-            iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+            static jclass inet4Cls = 0;
+            if (inet4Cls == 0) {
+                jclass c = (*env)->FindClass(env, "java/net/Inet4Address");
+                CHECK_NULL_RETURN(c, NULL);
+                inet4Cls = (*env)->NewGlobalRef(env, c);
+                CHECK_NULL_RETURN(inet4Cls, NULL);
+                (*env)->DeleteLocalRef(env, c);
+            }
+            iaObj = (*env)->NewObject(env, inet4Cls, ia4_ctrID);
             CHECK_NULL_RETURN(iaObj, NULL);
             address = NET_IPv4MappedToIPv4(caddr);
             setInetAddress_addr(env, iaObj, address);
             setInetAddress_family(env, iaObj, IPv4);
         } else {
+            static jclass inet6Cls = 0;
             jint scope;
             int ret;
-            iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
+            if (inet6Cls == 0) {
+                jclass c = (*env)->FindClass(env, "java/net/Inet6Address");
+                CHECK_NULL_RETURN(c, NULL);
+                inet6Cls = (*env)->NewGlobalRef(env, c);
+                CHECK_NULL_RETURN(inet6Cls, NULL);
+                (*env)->DeleteLocalRef(env, c);
+            }
+            iaObj = (*env)->NewObject(env, inet6Cls, ia6_ctrID);
             CHECK_NULL_RETURN(iaObj, NULL);
             ret = setInet6Address_ipaddress(env, iaObj, (char *)&(him6->sin6_addr));
             CHECK_NULL_RETURN(ret, NULL);
@@ -232,7 +276,16 @@
 #endif /* AF_INET6 */
         {
             struct sockaddr_in *him4 = (struct sockaddr_in *)him;
-            iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+            static jclass inet4Cls = 0;
+
+            if (inet4Cls == 0) {
+                jclass c = (*env)->FindClass(env, "java/net/Inet4Address");
+                CHECK_NULL_RETURN(c, NULL);
+                inet4Cls = (*env)->NewGlobalRef(env, c);
+                CHECK_NULL_RETURN(inet4Cls, NULL);
+                (*env)->DeleteLocalRef(env, c);
+            }
+            iaObj = (*env)->NewObject(env, inet4Cls, ia4_ctrID);
             CHECK_NULL_RETURN(iaObj, NULL);
             setInetAddress_family(env, iaObj, IPv4);
             setInetAddress_addr(env, iaObj, ntohl(him4->sin_addr.s_addr));
diff --git a/jdk/src/share/native/java/net/net_util.h b/jdk/src/share/native/java/net/net_util.h
index c8a5e68..9063c3e 100644
--- a/jdk/src/share/native/java/net/net_util.h
+++ b/jdk/src/share/native/java/net/net_util.h
@@ -56,8 +56,6 @@
 extern jfieldID iac_origHostNameID;
 extern jfieldID ia_preferIPv6AddressID;
 
-JNIEXPORT void JNICALL initInetAddressIDs(JNIEnv *env);
-
 /** (Inet6Address accessors)
  * set_ methods return JNI_TRUE on success JNI_FALSE on error
  * get_ methods that return int/boolean, return -1 on error
diff --git a/jdk/src/share/native/java/nio/Bits.c b/jdk/src/share/native/java/nio/Bits.c
index 8bc3ff7..20aa0d1 100644
--- a/jdk/src/share/native/java/nio/Bits.c
+++ b/jdk/src/share/native/java/nio/Bits.c
@@ -51,13 +51,10 @@
 
 #define MBYTE 1048576
 
-#define GETCRITICAL_OR_RETURN(bytes, env, obj) { \
+#define GETCRITICAL(bytes, env, obj) { \
     bytes = (*env)->GetPrimitiveArrayCritical(env, obj, NULL); \
-    if (bytes == NULL)  { \
-        if ((*env)->ExceptionOccurred(env) == NULL) \
-            JNU_ThrowInternalError(env, "Unable to get array"); \
-        return; \
-    } \
+    if (bytes == NULL) \
+        JNU_ThrowInternalError(env, "Unable to get array"); \
 }
 
 #define RELEASECRITICAL(bytes, env, obj, mode) { \
@@ -88,7 +85,7 @@
         else
             size = (size_t)length;
 
-        GETCRITICAL_OR_RETURN(bytes, env, src);
+        GETCRITICAL(bytes, env, src);
 
         srcShort = (jshort *)(bytes + srcPos);
         endShort = srcShort + (size / sizeof(jshort));
@@ -123,7 +120,7 @@
         else
             size = (size_t)length;
 
-        GETCRITICAL_OR_RETURN(bytes, env, dst);
+        GETCRITICAL(bytes, env, dst);
 
         dstShort = (jshort *)(bytes + dstPos);
         endShort = srcShort + (size / sizeof(jshort));
@@ -158,7 +155,7 @@
         else
             size = (size_t)length;
 
-        GETCRITICAL_OR_RETURN(bytes, env, src);
+        GETCRITICAL(bytes, env, src);
 
         srcInt = (jint *)(bytes + srcPos);
         endInt = srcInt + (size / sizeof(jint));
@@ -193,7 +190,7 @@
         else
             size = (size_t)length;
 
-        GETCRITICAL_OR_RETURN(bytes, env, dst);
+        GETCRITICAL(bytes, env, dst);
 
         dstInt = (jint *)(bytes + dstPos);
         endInt = srcInt + (size / sizeof(jint));
@@ -228,7 +225,7 @@
         else
             size = (size_t)length;
 
-        GETCRITICAL_OR_RETURN(bytes, env, src);
+        GETCRITICAL(bytes, env, src);
 
         srcLong = (jlong *)(bytes + srcPos);
         endLong = srcLong + (size / sizeof(jlong));
@@ -263,7 +260,7 @@
         else
             size = (size_t)length;
 
-        GETCRITICAL_OR_RETURN(bytes, env, dst);
+        GETCRITICAL(bytes, env, dst);
 
         dstLong = (jlong *)(bytes + dstPos);
         endLong = srcLong + (size / sizeof(jlong));
diff --git a/jdk/src/share/native/sun/awt/giflib/dgif_lib.c b/jdk/src/share/native/sun/awt/giflib/dgif_lib.c
index 1c1b217..2d3d882 100644
--- a/jdk/src/share/native/sun/awt/giflib/dgif_lib.c
+++ b/jdk/src/share/native/sun/awt/giflib/dgif_lib.c
@@ -114,7 +114,7 @@
     GifFile->SavedImages = NULL;
     GifFile->SColorMap = NULL;
 
-    Private = (GifFilePrivateType *)calloc(1, sizeof(GifFilePrivateType));
+    Private = (GifFilePrivateType *)malloc(sizeof(GifFilePrivateType));
     if (Private == NULL) {
         if (Error != NULL)
             *Error = D_GIF_ERR_NOT_ENOUGH_MEM;
@@ -122,9 +122,6 @@
         free((char *)GifFile);
         return NULL;
     }
-
-    /*@i1@*/memset(Private, '\0', sizeof(GifFilePrivateType));
-
 #ifdef _WIN32
     _setmode(FileHandle, O_BINARY);    /* Make sure it is in binary mode. */
 #endif /* _WIN32 */
@@ -200,14 +197,13 @@
     GifFile->SavedImages = NULL;
     GifFile->SColorMap = NULL;
 
-    Private = (GifFilePrivateType *)calloc(1, sizeof(GifFilePrivateType));
+    Private = (GifFilePrivateType *)malloc(sizeof(GifFilePrivateType));
     if (!Private) {
         if (Error != NULL)
             *Error = D_GIF_ERR_NOT_ENOUGH_MEM;
         free((char *)GifFile);
         return NULL;
     }
-    /*@i1@*/memset(Private, '\0', sizeof(GifFilePrivateType));
 
     GifFile->Private = (void *)Private;
     Private->FileHandle = 0;
@@ -421,8 +417,8 @@
 
     if (GifFile->SavedImages) {
         SavedImage* new_saved_images =
-            (SavedImage *)reallocarray(GifFile->SavedImages,
-                            (GifFile->ImageCount + 1), sizeof(SavedImage));
+            (SavedImage *)realloc(GifFile->SavedImages,
+                            sizeof(SavedImage) * (GifFile->ImageCount + 1));
         if (new_saved_images == NULL) {
             GifFile->Error = D_GIF_ERR_NOT_ENOUGH_MEM;
             return GIF_ERROR;
@@ -792,12 +788,6 @@
     }
     BitsPerPixel = CodeSize;
 
-    /* this can only happen on a severely malformed GIF */
-    if (BitsPerPixel > 8) {
-        GifFile->Error = D_GIF_ERR_READ_FAILED;    /* somewhat bogus error code */
-        return GIF_ERROR;    /* Failed to read Code size. */
-    }
-
     Private->Buf[0] = 0;    /* Input Buffer empty. */
     Private->BitsPerPixel = BitsPerPixel;
     Private->ClearCode = (1 << BitsPerPixel);
@@ -1133,7 +1123,7 @@
               if (ImageSize > (SIZE_MAX / sizeof(GifPixelType))) {
                   return GIF_ERROR;
               }
-              sp->RasterBits = (unsigned char *)reallocarray(NULL, ImageSize,
+              sp->RasterBits = (unsigned char *)malloc(ImageSize *
                       sizeof(GifPixelType));
 
               if (sp->RasterBits == NULL) {
diff --git a/jdk/src/share/native/sun/awt/giflib/gif_lib.h b/jdk/src/share/native/sun/awt/giflib/gif_lib.h
index e8d7090..aa35636 100644
--- a/jdk/src/share/native/sun/awt/giflib/gif_lib.h
+++ b/jdk/src/share/native/sun/awt/giflib/gif_lib.h
@@ -37,7 +37,7 @@
 
 #define GIFLIB_MAJOR 5
 #define GIFLIB_MINOR 1
-#define GIFLIB_RELEASE 4
+#define GIFLIB_RELEASE 1
 
 #define GIF_ERROR   0
 #define GIF_OK      1
@@ -274,9 +274,6 @@
                                      GifPixelType ColorTransIn2[]);
 extern int GifBitSize(int n);
 
-extern void * reallocarray(void *optr, size_t nmemb, size_t size);
-
-
 /******************************************************************************
  Support for the in-core structures allocation (slurp mode).
 ******************************************************************************/
diff --git a/jdk/src/share/native/sun/awt/giflib/gifalloc.c b/jdk/src/share/native/sun/awt/giflib/gifalloc.c
index cc784d1..f7a6a3d 100644
--- a/jdk/src/share/native/sun/awt/giflib/gifalloc.c
+++ b/jdk/src/share/native/sun/awt/giflib/gifalloc.c
@@ -212,8 +212,8 @@
 
         /* perhaps we can shrink the map? */
         if (RoundUpTo < ColorUnion->ColorCount) {
-            GifColorType *new_map = (GifColorType *)reallocarray(Map,
-                                 RoundUpTo, sizeof(GifColorType));
+            GifColorType *new_map = (GifColorType *)realloc(Map,
+                                 sizeof(GifColorType) * RoundUpTo);
             if( new_map == NULL ) {
                 GifFreeMapObject(ColorUnion);
                 return ((ColorMapObject *) NULL);
@@ -256,9 +256,9 @@
     if (*ExtensionBlocks == NULL)
         *ExtensionBlocks=(ExtensionBlock *)malloc(sizeof(ExtensionBlock));
     else {
-        ExtensionBlock* ep_new = (ExtensionBlock *)reallocarray
-                                      (*ExtensionBlocks, (*ExtensionBlockCount + 1),
-                                      sizeof(ExtensionBlock));
+        ExtensionBlock* ep_new = (ExtensionBlock *)realloc(*ExtensionBlocks,
+                                      sizeof(ExtensionBlock) *
+                                      (*ExtensionBlockCount + 1));
         if( ep_new == NULL )
             return (GIF_ERROR);
         *ExtensionBlocks = ep_new;
@@ -349,8 +349,8 @@
     if (GifFile->SavedImages == NULL)
         GifFile->SavedImages = (SavedImage *)malloc(sizeof(SavedImage));
     else
-        GifFile->SavedImages = (SavedImage *)reallocarray(GifFile->SavedImages,
-                               (GifFile->ImageCount + 1), sizeof(SavedImage));
+        GifFile->SavedImages = (SavedImage *)realloc(GifFile->SavedImages,
+                               sizeof(SavedImage) * (GifFile->ImageCount + 1));
 
     if (GifFile->SavedImages == NULL)
         return ((SavedImage *)NULL);
@@ -379,10 +379,9 @@
             }
 
             /* next, the raster */
-            sp->RasterBits = (unsigned char *)reallocarray(NULL,
-                                                  (CopyFrom->ImageDesc.Height *
-                                                  CopyFrom->ImageDesc.Width),
-                                                  sizeof(GifPixelType));
+            sp->RasterBits = (unsigned char *)malloc(sizeof(GifPixelType) *
+                                                   CopyFrom->ImageDesc.Height *
+                                                   CopyFrom->ImageDesc.Width);
             if (sp->RasterBits == NULL) {
                 FreeLastSavedImage(GifFile);
                 return (SavedImage *)(NULL);
@@ -393,9 +392,9 @@
 
             /* finally, the extension blocks */
             if (sp->ExtensionBlocks != NULL) {
-                sp->ExtensionBlocks = (ExtensionBlock *)reallocarray(NULL,
-                                      CopyFrom->ExtensionBlockCount,
-                                      sizeof(ExtensionBlock));
+                sp->ExtensionBlocks = (ExtensionBlock *)malloc(
+                                      sizeof(ExtensionBlock) *
+                                      CopyFrom->ExtensionBlockCount);
                 if (sp->ExtensionBlocks == NULL) {
                     FreeLastSavedImage(GifFile);
                     return (SavedImage *)(NULL);
diff --git a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c
index 66eb80a..342fe26 100644
--- a/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c
+++ b/jdk/src/share/native/sun/awt/image/jpeg/imageioJPEG.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 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
@@ -553,43 +553,30 @@
 METHODDEF(void)
 sun_jpeg_output_message (j_common_ptr cinfo)
 {
-    char buffer[JMSG_LENGTH_MAX];
-    jstring string;
-    imageIODataPtr data = (imageIODataPtr) cinfo->client_data;
-    JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
-    jobject theObject;
+  char buffer[JMSG_LENGTH_MAX];
+  jstring string;
+  imageIODataPtr data = (imageIODataPtr) cinfo->client_data;
+  JNIEnv *env = (JNIEnv *)JNU_GetEnv(jvm, JNI_VERSION_1_2);
+  jobject theObject;
 
-    /* Create the message */
-    (*cinfo->err->format_message) (cinfo, buffer);
+  /* Create the message */
+  (*cinfo->err->format_message) (cinfo, buffer);
 
-    // Create a new java string from the message
-    string = (*env)->NewStringUTF(env, buffer);
-    CHECK_NULL(string);
+  // Create a new java string from the message
+  string = (*env)->NewStringUTF(env, buffer);
+  CHECK_NULL(string);
 
-    theObject = data->imageIOobj;
+  theObject = data->imageIOobj;
 
-    if (cinfo->is_decompressor) {
-        struct jpeg_source_mgr *src = ((j_decompress_ptr)cinfo)->src;
-        RELEASE_ARRAYS(env, data, src->next_input_byte);
-        (*env)->CallVoidMethod(env, theObject,
-            JPEGImageReader_warningWithMessageID,
-            string);
-        if ((*env)->ExceptionOccurred(env)
-            || !GET_ARRAYS(env, data, &(src->next_input_byte))) {
-            cinfo->err->error_exit(cinfo);
-        }
-    } else {
-        struct jpeg_destination_mgr *dest = ((j_compress_ptr)cinfo)->dest;
-        RELEASE_ARRAYS(env, data, (const JOCTET *)(dest->next_output_byte));
-        (*env)->CallVoidMethod(env, theObject,
-            JPEGImageWriter_warningWithMessageID,
-            string);
-        if ((*env)->ExceptionOccurred(env)
-            || !GET_ARRAYS(env, data,
-            (const JOCTET **)(&dest->next_output_byte))) {
-            cinfo->err->error_exit(cinfo);
-        }
-    }
+  if (cinfo->is_decompressor) {
+      (*env)->CallVoidMethod(env, theObject,
+                             JPEGImageReader_warningWithMessageID,
+                             string);
+  } else {
+      (*env)->CallVoidMethod(env, theObject,
+                             JPEGImageWriter_warningWithMessageID,
+                             string);
+  }
 }
 
 /* End of verbatim copy from jpegdecoder.c */
@@ -1056,7 +1043,6 @@
         if (!GET_ARRAYS(env, data, &(src->next_input_byte))) {
             cinfo->err->error_exit((j_common_ptr) cinfo);
         }
-        RELEASE_ARRAYS(env, data, src->next_input_byte);
         return;
     }
 
@@ -1812,14 +1798,9 @@
                                cinfo->out_color_space,
                                cinfo->num_components,
                                profileData);
-        if ((*env)->ExceptionOccurred(env)
-            || !GET_ARRAYS(env, data, &(src->next_input_byte))) {
-            cinfo->err->error_exit((j_common_ptr) cinfo);
-        }
         if (reset) {
             jpeg_abort_decompress(cinfo);
         }
-        RELEASE_ARRAYS(env, data, src->next_input_byte);
     }
 
     return retval;
@@ -2030,7 +2011,6 @@
     jpeg_start_decompress(cinfo);
 
     if (numBands !=  cinfo->output_components) {
-        RELEASE_ARRAYS(env, data, src->next_input_byte);
         JNU_ThrowByName(env, "javax/imageio/IIOException",
                         "Invalid argument to native readImage");
         return data->abortFlag;
@@ -2039,7 +2019,6 @@
     if (cinfo->output_components <= 0 ||
         cinfo->image_width > (0xffffffffu / (unsigned int)cinfo->output_components))
     {
-        RELEASE_ARRAYS(env, data, src->next_input_byte);
         JNU_ThrowByName(env, "javax/imageio/IIOException",
                         "Invalid number of output components");
         return data->abortFlag;
@@ -2063,24 +2042,15 @@
             // the first interesting pass.
             jpeg_start_output(cinfo, cinfo->input_scan_number);
             if (wantUpdates) {
-                RELEASE_ARRAYS(env, data, src->next_input_byte);
                 (*env)->CallVoidMethod(env, this,
                                        JPEGImageReader_passStartedID,
                                        cinfo->input_scan_number-1);
-                if ((*env)->ExceptionOccurred(env)
-                    || !GET_ARRAYS(env, data, &(src->next_input_byte))) {
-                    cinfo->err->error_exit((j_common_ptr) cinfo);
-                }
             }
         } else if (wantUpdates) {
-            RELEASE_ARRAYS(env, data, src->next_input_byte);
             (*env)->CallVoidMethod(env, this,
                                    JPEGImageReader_passStartedID,
                                    0);
-            if ((*env)->ExceptionOccurred(env)
-                || !GET_ARRAYS(env, data, &(src->next_input_byte))) {
-                cinfo->err->error_exit((j_common_ptr) cinfo);
-            }
+
         }
 
         // Skip until the first interesting line
@@ -2168,13 +2138,8 @@
             done = TRUE;
         }
         if (wantUpdates) {
-            RELEASE_ARRAYS(env, data, src->next_input_byte);
             (*env)->CallVoidMethod(env, this,
                                    JPEGImageReader_passCompleteID);
-            if ((*env)->ExceptionOccurred(env)
-                || !GET_ARRAYS(env, data, &(src->next_input_byte))) {
-                cinfo->err->error_exit((j_common_ptr) cinfo);
-            }
         }
 
     }
@@ -2669,18 +2634,6 @@
     RELEASE_ARRAYS(env, data, NULL);
 }
 
-static void freeArray(void** arr, jint size) {
-    int i;
-    if (arr != NULL) {
-        for (i = 0; i < size; i++) {
-            if (arr[i] != NULL) {
-                free(arr[i]);
-            }
-        }
-        free(arr);
-    }
-}
-
 JNIEXPORT jboolean JNICALL
 Java_com_sun_imageio_plugins_jpeg_JPEGImageWriter_writeImage
     (JNIEnv *env,
@@ -2789,8 +2742,6 @@
                 scale = (UINT8**) calloc(numBands, sizeof(UINT8*));
 
                 if (scale == NULL) {
-                    (*env)->ReleaseIntArrayElements(env, bandSizes,
-                                                    bandSize, JNI_ABORT);
                     JNU_ThrowByName( env, "java/lang/OutOfMemoryError",
                                      "Writing JPEG Stream");
                     return JNI_FALSE;
@@ -2807,8 +2758,6 @@
                     free(scale[j]);
                 }
                 free(scale);
-                (*env)->ReleaseIntArrayElements(env, bandSizes,
-                                                bandSize, JNI_ABORT);
                 JNU_ThrowByName( env, "java/lang/OutOfMemoryError",
                                  "Writing JPEG Stream");
                 return JNI_FALSE;
@@ -2833,14 +2782,21 @@
     pb = &data->pixelBuf;
 
     if (setPixelBuffer(env, pb, buffer) == NOT_OK) {
-        freeArray(scale, numBands);
+        if (scale != NULL) {
+            for (i = 0; i < numBands; i++) {
+                if (scale[i] != NULL) {
+                    free(scale[i]);
+                }
+            }
+            free(scale);
+        }
         return data->abortFlag;  // We already threw an out of memory exception
     }
 
     // Allocate a 1-scanline buffer
     scanLinePtr = (JSAMPROW)malloc(scanLineSize);
     if (scanLinePtr == NULL) {
-        freeArray(scale, numBands);
+        RELEASE_ARRAYS(env, data, (const JOCTET *)(dest->next_output_byte));
         JNU_ThrowByName( env,
                          "java/lang/OutOfMemoryError",
                          "Writing JPEG Stream");
@@ -2862,7 +2818,15 @@
             JNU_ThrowByName(env, "javax/imageio/IIOException", buffer);
         }
 
-        freeArray(scale, numBands);
+        if (scale != NULL) {
+            for (i = 0; i < numBands; i++) {
+                if (scale[i] != NULL) {
+                    free(scale[i]);
+                }
+            }
+            free(scale);
+        }
+
         free(scanLinePtr);
         return data->abortFlag;
     }
@@ -2910,11 +2874,7 @@
     if (qsels) {
         (*env)->ReleaseIntArrayElements(env, QtableSelectors, qsels, JNI_ABORT);
     }
-    if (!success) {
-        freeArray(scale, numBands);
-        free(scanLinePtr);
-        return data->abortFlag;
-    }
+    if (!success) return data->abortFlag;
 
     jpeg_suppress_tables(cinfo, TRUE);  // Disable writing any current
 
@@ -2932,8 +2892,6 @@
     if (GET_ARRAYS(env, data,
                    (const JOCTET **)(&dest->next_output_byte)) == NOT_OK) {
         (*env)->ExceptionClear(env);
-        freeArray(scale, numBands);
-        free(scanLinePtr);
         JNU_ThrowByName(env,
                         "javax/imageio/IIOException",
                         "Array pin failed");
@@ -2968,12 +2926,7 @@
             cinfo->scan_info = cinfo->script_space;
             scanptr = (int *) cinfo->script_space;
             scanData = (*env)->GetIntArrayElements(env, scanInfo, NULL);
-            if (scanData == NULL) {
-                RELEASE_ARRAYS(env, data, (const JOCTET *)(dest->next_output_byte));
-                freeArray(scale, numBands);
-                free(scanLinePtr);
-                return data->abortFlag;
-            }
+            CHECK_NULL_RETURN(scanData, data->abortFlag);
             // number of jints per scan is 9
             // We avoid a memcpy to handle different size ints
             for (i = 0; i < numScans*9; i++) {
@@ -3069,7 +3022,15 @@
         jpeg_abort((j_common_ptr)cinfo);
     }
 
-    freeArray(scale, numBands);
+    if (scale != NULL) {
+        for (i = 0; i < numBands; i++) {
+            if (scale[i] != NULL) {
+                free(scale[i]);
+            }
+        }
+        free(scale);
+    }
+
     free(scanLinePtr);
     RELEASE_ARRAYS(env, data, NULL);
     return data->abortFlag;
diff --git a/jdk/src/share/native/sun/awt/libpng/CHANGES b/jdk/src/share/native/sun/awt/libpng/CHANGES
index f7973c4..8d9d53e 100644
--- a/jdk/src/share/native/sun/awt/libpng/CHANGES
+++ b/jdk/src/share/native/sun/awt/libpng/CHANGES
@@ -5088,8 +5088,7 @@
 Version 1.6.15beta05 [November 5, 2014]
   Use png_get_libpng_ver(NULL) instead of PNG_LIBPNG_VER_STRING in
     example.c, pngtest.c, and applications in the contrib directory.
-  Fixed an out-of-range read in png_user_version_check() (Bug report from
-    Qixue Xiao, CVE-2015-8540).
+  Avoid out-of-bounds memory access in png_user_version_check().
   Simplified and future-proofed png_user_version_check().
   Fixed GCC unsigned int->float warnings. Various versions of GCC
     seem to generate warnings when an unsigned value is implicitly
@@ -5447,7 +5446,7 @@
 Version 1.6.20beta02 [November 23, 2015]
   Fixed incorrect implementation of png_set_PLTE() that uses png_ptr
     not info_ptr, that left png_set_PLTE() open to the CVE-2015-8126
-    vulnerability.  Fixes CVE-2015-8472.
+    vulnerability.
 
 Version 1.6.20beta03 [November 24, 2015]
   Backported tests from libpng-1.7.0beta69.
@@ -5472,155 +5471,6 @@
 Version 1.6.20 [December 3, 2015]
   No changes.
 
-Version 1.6.21beta01 [December 11, 2015]
-  Fixed syntax "$(command)" in tests/pngstest that some shells other than
-    bash could not parse (Bug report by Nelson Beebe). Use `command` instead.
-
-Version 1.6.21beta02 [December 14, 2015]
-  Moved png_check_keyword() from pngwutil.c to pngset.c
-  Removed LE/BE dependencies in pngvalid, to 'fix' the current problem
-    in the BigEndian tests by not testing it, making the BE code the same 
-    as the LE version.
-  Fixes to pngvalid for various reduced build configurations (eliminate unused
-    statics) and a fix for the case in rgb_to_gray when the digitize option
-    reduces graylo to 0, producing a large error.
-
-Version 1.6.21beta03 [December 18, 2015]
-  Widened the 'limit' check on the internally calculated error limits in
-    the 'DIGITIZE' case (the code used prior to 1.7 for rgb_to_gray error
-    checks) and changed the check to only operate in non-release builds
-    (base build type not RC or RELEASE.)
-  Fixed undefined behavior in pngvalid.c, undefined because
-    (png_byte) << shift is undefined if it changes the signed bit
-    (because png_byte is promoted to int). The libpng exported functions
-    png_get_uint_32 and png_get_uint_16 handle this. (Bug reported by
-    David Drysdale as a result of reports from UBSAN in clang 3.8).
-  This changes pngvalid to use BE random numbers; this used to produce
-    errors but these should not be fixed as a result of the previous changes.
-
-Version 1.6.21rc01 [January 4, 2016]
-  In projects/vstudio, combined readme.txt and WARNING into README.txt
-
-Version 1.6.21rc02 [January 7, 2016]
-  Relocated assert() in contrib/tools/pngfix.c, bug found by American
-    Fuzzy Lop, reported by Brian Carpenter.
-  Marked 'limit' UNUSED in transform_range_check().  This only affects
-    release builds.
-
-Version 1.6.21 [January 15, 2016]
-  Worked around a false-positive Coverity issue in pngvalid.c.
-
-Version 1.6.22beta01 [January 23, 2016]
-  Changed PNG_USE_MKSTEMP to __COVERITY__ to select alternate
-    "tmpfile()" implementation in contrib/libtests/pngstest.c
-  Fixed NO_STDIO build of pngunknown.c to skip calling png_init_io()
-    if there is no stdio.h support.
-  Added a png_image_write_to_memory() API and a number of assist macros
-    to allow an application that uses the simplified API write to bypass
-    stdio and write directly to memory.
-  Added some warnings (png.h) and some check code to detect *possible*
-    overflow in the ROW_STRIDE and simplified image SIZE macros.  This
-    disallows image width/height/format that *might* overflow.  This is
-    a quiet API change that limits in-memory image size (uncompressed) to
-    less than 4GByte and image row size (stride) to less than 2GByte.
-  Revised workaround for false-positive Coverity issue in pngvalid.c.
-
-Version 1.6.22beta02 [February 8, 2016]
-  Only use exit(77) in configure builds.
-  Corrected error in PNG_IMAGE_PNG_SIZE_MAX. This new macro underreported
-    the palette size because it failed to take into account that the memory
-    palette has to be expanded to full RGB when it is written to PNG.
-  Updated CMakeLists.txt, added supporting scripts/gen*.cmake.in
-    and test.cmake.in (Roger Leigh).
-  Relaxed limit checks on gamma values in pngrtran.c. As suggested in
-    the comments gamma values outside the range currently permitted
-    by png_set_alpha_mode are useful for HDR data encoding.  These values
-    are already permitted by png_set_gamma so it is reasonable caution to
-    extend the png_set_alpha_mode range as HDR imaging systems are starting
-    to emerge.
-
-Version 1.6.22beta03 [March 9, 2016]
-  Added a common-law trademark notice and export control information
-    to the LICENSE file, png.h, and the man page.
-  Restored "& 0xff" in png_save_uint_16() and png_save_uint_32() that
-    were accidentally removed from libpng-1.6.17. 
-  Changed PNG_INFO_cHNK and PNG_FREE_cHNK from 0xnnnn to 0xnnnnU in png.h
-    (Robert C. Seacord).
-  Removed dubious "#if INT_MAX" test from png.h that was added to
-    libpng-1.6.19beta02 (John Bowler).
-  Add ${INCLUDES} in scripts/genout.cmake.in (Bug report by Nixon Kwok).
-  Updated LICENSE to say files in the contrib directory are not
-    necessarily under the libpng license, and that some makefiles have
-    other copyright owners.
-  Added INTEL-SSE2 support (Mike Klein and Matt Sarett, Google, Inc.).
-  Made contrib/libtests/timepng more robust.  The code no longer gives
-    up/fails on invalid PNG data, it just skips it (with error messages).
-    The code no longer fails on PNG files with data beyond IEND.  Options
-    exist to use png_read_png (reading the whole image, not by row) and, in
-    that case, to apply any of the supported transforms.  This makes for
-    more realistic testing; the decoded data actually gets used in a
-    meaningful fashion (John Bowler).
-  Fixed some misleading indentation (Krishnaraj Bhat).
-
-Version 1.6.22beta04 [April 5, 2016]
-  Force GCC compilation to C89 if needed (Dagobert Michelsen).
-  SSE filter speed improvements for bpp=3:
-    memcpy-free implementations of load3() / store3().
-    call load3() only when needed at the end of a scanline.
-
-Version 1.6.22beta05 [April 27, 2016]
-  Added PNG_FAST_FILTERS macro (defined as
-    PNG_FILTER_NONE|PNG_FILTER_SUB|PNG_FILTER_UP).
-  Various fixes for contrib/libtests/timepng.c
-  Moved INTEL-SSE code from pngpriv.h into contrib/intel/intel_sse.patch.
-  Fixed typo (missing underscore) in #define PNG_READ_16_TO_8_SUPPORTED
-    (Bug report by Y.Ohashik).
-
-Version 1.6.22beta06 [May 5, 2016]
-  Rebased contrib/intel_sse.patch.
-  Quieted two Coverity issues in contrib/libtests/timepng.c.
-  Fixed issues with scripts/genout.cmake.in (David Capello, Nixon Kwok):
-    Added support to use multiple directories in ZLIBINCDIR variable,
-    Fixed CMAKE_C_FLAGS with multiple values when genout is compiled on MSVC,
-    Fixed pnglibconf.c compilation on OS X including the sysroot path.
-
-Version 1.6.22rc01 [May 14, 2016]
-  No changes.
-
-Version 1.6.22rc02 [May 16, 2016]
-  Removed contrib/timepng from default build; it does not build on platforms
-    that don't supply clock_gettime().
-
-Version 1.6.22rc03 [May 17, 2016]
-  Restored contrib/timepng to default build but check for the presence
-    of clock_gettime() in configure.ac and Makefile.am.
-
-Version 1.6.22 [May 26, 2016]
-  No changes.
-
-Version 1.6.23beta01 [May 29, 2016]
-  Stop a potential memory leak in png_set_tRNS() (Bug report by Ted Ying).
-  Fixed the progressive reader to handle empty first IDAT chunk properly
-    (patch by Timothy Nikkel).  This bug was introduced in libpng-1.6.0 and
-    only affected the libpng16 branch.
-  Added tests in pngvalid.c to check zero-length IDAT chunks in various
-    positions.  Fixed the sequential reader to handle these more robustly
-    (John Bowler).
-
-Version 1.6.23rc01 [June 2, 2016]
-  Corrected progressive read input buffer in pngvalid.c. The previous version
-    the code invariably passed just one byte at a time to libpng.  The intent
-    was to pass a random number of bytes in the range 0..511.
-  Moved sse2 prototype from pngpriv.h to contrib/intel/intel_sse.patch.
-  Added missing ")" in pngerror.c (Matt Sarrett).
-
-Version 1.6.23rc02 [June 4, 2016]
-  Fixed undefined behavior in png_push_save_buffer(). Do not call
-    memcpy() with a null source, even if count is zero (Leon Scroggins III).
-
-Version 1.6.23 [June 9, 2016]
-  Fixed bad link to RFC2083 in png.5 (Nikola Forro).
-
 Send comments/corrections/commendations to png-mng-implement at lists.sf.net
 (subscription required; visit
 https://lists.sourceforge.net/lists/listinfo/png-mng-implement
diff --git a/jdk/src/share/native/sun/awt/libpng/LICENSE b/jdk/src/share/native/sun/awt/libpng/LICENSE
index b7ad4b9..82dbe11 100644
--- a/jdk/src/share/native/sun/awt/libpng/LICENSE
+++ b/jdk/src/share/native/sun/awt/libpng/LICENSE
@@ -10,8 +10,8 @@
 
 This code is released under the libpng license.
 
-libpng versions 1.0.7, July 1, 2000 through 1.6.23, June 9, 2016 are
-Copyright (c) 2000-2002, 2004, 2006-2016 Glenn Randers-Pehrson, are
+libpng versions 1.0.7, July 1, 2000, through 1.6.20, December 3, 2015, are
+Copyright (c) 2000-2002, 2004, 2006-2015 Glenn Randers-Pehrson, are
 derived from libpng-1.0.6, and are distributed according to the same
 disclaimer and license as libpng-1.0.6 with the following individuals
 added to the list of Contributing Authors:
@@ -32,10 +32,6 @@
    risk of satisfactory quality, performance, accuracy, and effort is with
    the user.
 
-Some files in the "contrib" directory and some configure-generated
-files that are distributed with libpng have other copyright owners and
-are released under other open source licenses.
-
 libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
 Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from
 libpng-0.96, and are distributed according to the same disclaimer and
@@ -59,9 +55,6 @@
    Greg Roelofs
    Tom Tanner
 
-Some files in the "scripts" directory have other copyright owners
-but are released under this license.
-
 libpng versions 0.5, May 1995, through 0.88, January 1996, are
 Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
 
@@ -102,29 +95,18 @@
 
 END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE.
 
-TRADEMARK:
+A "png_get_copyright" function is available, for convenient use in "about"
+boxes and the like:
 
-The name "libpng" has not been registered by the Copyright owner
-as a trademark in any jurisdiction.  However, because libpng has
-been distributed and maintained world-wide, continually since 1995,
-the Copyright owner claims "common-law trademark protection" in any
-jurisdiction where common-law trademark is recognized.
+   printf("%s", png_get_copyright(NULL));
 
-OSI CERTIFICATION:
+Also, the PNG logo (in PNG format, of course) is supplied in the
+files "pngbar.png" and "pngbar.jpg (88x31) and "pngnow.png" (98x31).
 
 Libpng is OSI Certified Open Source Software.  OSI Certified Open Source is
 a certification mark of the Open Source Initiative. OSI has not addressed
 the additional disclaimers inserted at version 1.0.7.
 
-EXPORT CONTROL:
-
-The Copyright owner believes that the Export Control Classification
-Number (ECCN) for libpng is EAR99, which means not subject to export
-controls or International Traffic in Arms Regulations (ITAR) because
-it is open source, publicly available software, that does not contain
-any encryption software.  See the EAR, paragraphs 734.3(b)(3) and
-734.7(b).
-
 Glenn Randers-Pehrson
 glennrp at users.sourceforge.net
-June 9, 2016
+December 3, 2015
diff --git a/jdk/src/share/native/sun/awt/libpng/README b/jdk/src/share/native/sun/awt/libpng/README
index 38e9a14..59f1f91 100644
--- a/jdk/src/share/native/sun/awt/libpng/README
+++ b/jdk/src/share/native/sun/awt/libpng/README
@@ -1,4 +1,4 @@
-README for libpng version 1.6.23 - June 9, 2016 (shared library 16.0)
+README for libpng version 1.6.20 - December 3, 2015 (shared library 16.0)
 See the note about version numbers near the top of png.h
 
 See INSTALL for instructions on how to install libpng.
diff --git a/jdk/src/share/native/sun/awt/libpng/png.c b/jdk/src/share/native/sun/awt/libpng/png.c
index f039ff7..38aa059 100644
--- a/jdk/src/share/native/sun/awt/libpng/png.c
+++ b/jdk/src/share/native/sun/awt/libpng/png.c
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.6.19 [November 12, 2015]
- * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -42,7 +42,7 @@
 #include "pngpriv.h"
 
 /* Generate a compiler error if there is an old png.h in the search path. */
-typedef png_libpng_version_1_6_23 Your_png_h_is_not_version_1_6_23;
+typedef png_libpng_version_1_6_20 Your_png_h_is_not_version_1_6_20;
 
 /* Tells libpng that we have already handled the first "num_bytes" bytes
  * of the PNG file signature.  If the PNG data is embedded into another
@@ -803,15 +803,14 @@
 #else
 #  ifdef __STDC__
    return PNG_STRING_NEWLINE \
-      "libpng version 1.6.23 - June 9, 2016" PNG_STRING_NEWLINE \
-      "Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson" \
-      PNG_STRING_NEWLINE \
+      "libpng version 1.6.20 - December 3, 2015" PNG_STRING_NEWLINE \
+      "Copyright (c) 1998-2015 Glenn Randers-Pehrson" PNG_STRING_NEWLINE \
       "Copyright (c) 1996-1997 Andreas Dilger" PNG_STRING_NEWLINE \
       "Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc." \
       PNG_STRING_NEWLINE;
 #  else
-   return "libpng version 1.6.23 - June 9, 2016\
-      Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson\
+   return "libpng version 1.6.20 - December 3, 2015\
+      Copyright (c) 1998-2015 Glenn Randers-Pehrson\
       Copyright (c) 1996-1997 Andreas Dilger\
       Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.";
 #  endif
diff --git a/jdk/src/share/native/sun/awt/libpng/png.h b/jdk/src/share/native/sun/awt/libpng/png.h
index 9f1ab42..c90a90f 100644
--- a/jdk/src/share/native/sun/awt/libpng/png.h
+++ b/jdk/src/share/native/sun/awt/libpng/png.h
@@ -29,9 +29,9 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * libpng version 1.6.23, June 9, 2016
+ * libpng version 1.6.20, December 3, 2015
  *
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -40,7 +40,7 @@
  * Authors and maintainers:
  *   libpng versions 0.71, May 1995, through 0.88, January 1996: Guy Schalnat
  *   libpng versions 0.89, June 1996, through 0.96, May 1997: Andreas Dilger
- *   libpng versions 0.97, January 1998, through 1.6.23, June 9, 2016:
+ *   libpng versions 0.97, January 1998, through 1.6.20, December 3, 2015:
  *     Glenn Randers-Pehrson.
  *   See also "Contributing Authors", below.
  */
@@ -53,12 +53,8 @@
  *
  * This code is released under the libpng license.
  *
- * Some files in the "contrib" directory and some configure-generated
- * files that are distributed with libpng have other copyright owners and
- * are released under other open source licenses.
- *
- * libpng versions 1.0.7, July 1, 2000 through 1.6.23, June 9, 2016 are
- * Copyright (c) 2000-2002, 2004, 2006-2016 Glenn Randers-Pehrson, are
+ * libpng versions 1.0.7, July 1, 2000, through 1.6.20, December 3, 2015, are
+ * Copyright (c) 2000-2002, 2004, 2006-2015 Glenn Randers-Pehrson, are
  * derived from libpng-1.0.6, and are distributed according to the same
  * disclaimer and license as libpng-1.0.6 with the following individuals
  * added to the list of Contributing Authors:
@@ -79,10 +75,6 @@
  *    risk of satisfactory quality, performance, accuracy, and effort is with
  *    the user.
  *
- * Some files in the "contrib" directory have other copyright owners and
- * are released under other open source licenses.
- *
- *
  * libpng versions 0.97, January 1998, through 1.0.6, March 20, 2000, are
  * Copyright (c) 1998-2000 Glenn Randers-Pehrson, are derived from
  * libpng-0.96, and are distributed according to the same disclaimer and
@@ -93,9 +85,6 @@
  *    Glenn Randers-Pehrson
  *    Willem van Schaik
  *
- * Some files in the "scripts" directory have different copyright owners
- * but are also released under this license.
- *
  * libpng versions 0.89, June 1996, through 0.96, May 1997, are
  * Copyright (c) 1996-1997 Andreas Dilger, are derived from libpng-0.88,
  * and are distributed according to the same disclaimer and license as
@@ -109,9 +98,6 @@
  *    Greg Roelofs
  *    Tom Tanner
  *
- * Some files in the "scripts" directory have other copyright owners
- * but are released under this license.
- *
  * libpng versions 0.5, May 1995, through 0.88, January 1996, are
  * Copyright (c) 1995-1996 Guy Eric Schalnat, Group 42, Inc.
  *
@@ -151,29 +137,6 @@
  * appreciated.
  *
  * END OF COPYRIGHT NOTICE, DISCLAIMER, and LICENSE.
- *
- * TRADEMARK:
- *
- * The name "libpng" has not been registered by the Copyright owner
- * as a trademark in any jurisdiction.  However, because libpng has
- * been distributed and maintained world-wide, continually since 1995,
- * the Copyright owner claims "common-law trademark protection" in any
- * jurisdiction where common-law trademark is recognized.
- *
- * OSI CERTIFICATION:
- *
- * Libpng is OSI Certified Open Source Software.  OSI Certified Open Source is
- * a certification mark of the Open Source Initiative. OSI has not addressed
- * the additional disclaimers inserted at version 1.0.7.
- *
- * EXPORT CONTROL:
- *
- * The Copyright owner believes that the Export Control Classification
- * Number (ECCN) for libpng is EAR99, which means not subject to export
- * controls or International Traffic in Arms Regulations (ITAR) because
- * it is open source, publicly available software, that does not contain
- * any encryption software.  See the EAR, paragraphs 734.3(b)(3) and
- * 734.7(b).
  */
 
 /*
@@ -187,6 +150,12 @@
  */
 
 /*
+ * Libpng is OSI Certified Open Source Software.  OSI Certified Open Source is
+ * a certification mark of the Open Source Initiative. OSI has not addressed
+ * the additional disclaimers inserted at version 1.0.7.
+ */
+
+/*
  * The contributing authors would like to thank all those who helped
  * with testing, bug fixes, and patience.  This wouldn't have been
  * possible without all of you.
@@ -241,11 +210,11 @@
  *    ...
  *    1.0.19                  10    10019  10.so.0.19[.0]
  *    ...
- *    1.2.56                  13    10256  12.so.0.56[.0]
+ *    1.2.53                  13    10253  12.so.0.53[.0]
  *    ...
- *    1.5.27                  15    10527  15.so.15.27[.0]
+ *    1.5.23                  15    10523  15.so.15.23[.0]
  *    ...
- *    1.6.23                  16    10623  16.so.16.23[.0]
+ *    1.6.20                  16    10620  16.so.16.20[.0]
  *
  *    Henceforth the source version will match the shared-library major
  *    and minor numbers; the shared-library major version number will be
@@ -273,13 +242,13 @@
  * Y2K compliance in libpng:
  * =========================
  *
- *    June 9, 2016
+ *    December 3, 2015
  *
  *    Since the PNG Development group is an ad-hoc body, we can't make
  *    an official declaration.
  *
  *    This is your unofficial assurance that libpng from version 0.71 and
- *    upward through 1.6.23 are Y2K compliant.  It is my belief that
+ *    upward through 1.6.20 are Y2K compliant.  It is my belief that
  *    earlier versions were also Y2K compliant.
  *
  *    Libpng only has two year fields.  One is a 2-byte unsigned integer
@@ -341,9 +310,9 @@
  */
 
 /* Version information for png.h - this should match the version in png.c */
-#define PNG_LIBPNG_VER_STRING "1.6.23"
+#define PNG_LIBPNG_VER_STRING "1.6.20"
 #define PNG_HEADER_VERSION_STRING \
-     " libpng version 1.6.23 - June 9, 2016\n"
+     " libpng version 1.6.20 - December 3, 2015\n"
 
 #define PNG_LIBPNG_VER_SONUM   16
 #define PNG_LIBPNG_VER_DLLNUM  16
@@ -351,7 +320,7 @@
 /* These should match the first 3 components of PNG_LIBPNG_VER_STRING: */
 #define PNG_LIBPNG_VER_MAJOR   1
 #define PNG_LIBPNG_VER_MINOR   6
-#define PNG_LIBPNG_VER_RELEASE 23
+#define PNG_LIBPNG_VER_RELEASE 20
 
 /* This should match the numeric part of the final component of
  * PNG_LIBPNG_VER_STRING, omitting any leading zero:
@@ -382,7 +351,7 @@
  * version 1.0.0 was mis-numbered 100 instead of 10000).  From
  * version 1.0.1 it's    xxyyzz, where x=major, y=minor, z=release
  */
-#define PNG_LIBPNG_VER 10623 /* 1.6.23 */
+#define PNG_LIBPNG_VER 10620 /* 1.6.20 */
 
 /* Library configuration: these options cannot be changed after
  * the library has been built.
@@ -492,7 +461,7 @@
 /* This triggers a compiler error in png.c, if png.c and png.h
  * do not agree upon the version number.
  */
-typedef char* png_libpng_version_1_6_23;
+typedef char* png_libpng_version_1_6_20;
 
 /* Basic control structions.  Read libpng-manual.txt or libpng.3 for more info.
  *
@@ -793,22 +762,24 @@
  * data in the info_struct to be written into the output file.  The values
  * of the PNG_INFO_<chunk> defines should NOT be changed.
  */
-#define PNG_INFO_gAMA 0x0001U
-#define PNG_INFO_sBIT 0x0002U
-#define PNG_INFO_cHRM 0x0004U
-#define PNG_INFO_PLTE 0x0008U
-#define PNG_INFO_tRNS 0x0010U
-#define PNG_INFO_bKGD 0x0020U
-#define PNG_INFO_hIST 0x0040U
-#define PNG_INFO_pHYs 0x0080U
-#define PNG_INFO_oFFs 0x0100U
-#define PNG_INFO_tIME 0x0200U
-#define PNG_INFO_pCAL 0x0400U
-#define PNG_INFO_sRGB 0x0800U  /* GR-P, 0.96a */
-#define PNG_INFO_iCCP 0x1000U  /* ESR, 1.0.6 */
-#define PNG_INFO_sPLT 0x2000U  /* ESR, 1.0.6 */
-#define PNG_INFO_sCAL 0x4000U  /* ESR, 1.0.6 */
-#define PNG_INFO_IDAT 0x8000U  /* ESR, 1.0.6 */
+#define PNG_INFO_gAMA 0x0001
+#define PNG_INFO_sBIT 0x0002
+#define PNG_INFO_cHRM 0x0004
+#define PNG_INFO_PLTE 0x0008
+#define PNG_INFO_tRNS 0x0010
+#define PNG_INFO_bKGD 0x0020
+#define PNG_INFO_hIST 0x0040
+#define PNG_INFO_pHYs 0x0080
+#define PNG_INFO_oFFs 0x0100
+#define PNG_INFO_tIME 0x0200
+#define PNG_INFO_pCAL 0x0400
+#define PNG_INFO_sRGB 0x0800   /* GR-P, 0.96a */
+#define PNG_INFO_iCCP 0x1000   /* ESR, 1.0.6 */
+#define PNG_INFO_sPLT 0x2000   /* ESR, 1.0.6 */
+#define PNG_INFO_sCAL 0x4000   /* ESR, 1.0.6 */
+#if INT_MAX >= 0x8000 /* else this might break */
+#define PNG_INFO_IDAT 0x8000   /* ESR, 1.0.6 */
+#endif
 
 /* This is used for the transformation routines, as some of them
  * change these values for the row.  It also should enable using
@@ -1379,7 +1350,7 @@
 #endif
 
 #ifdef PNG_READ_STRIP_16_TO_8_SUPPORTED
-#define PNG_READ_16_TO_8_SUPPORTED /* Name prior to 1.5.4 */
+#define PNG_READ_16_TO_8 SUPPORTED /* Name prior to 1.5.4 */
 /* Strip the second byte of information from a 16-bit depth file. */
 PNG_EXPORT(48, void, png_set_strip_16, (png_structrp png_ptr));
 #endif
@@ -1530,8 +1501,8 @@
 #define PNG_FILTER_UP      0x20
 #define PNG_FILTER_AVG     0x40
 #define PNG_FILTER_PAETH   0x80
-#define PNG_FAST_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP)
-#define PNG_ALL_FILTERS (PNG_FAST_FILTERS | PNG_FILTER_AVG | PNG_FILTER_PAETH)
+#define PNG_ALL_FILTERS (PNG_FILTER_NONE | PNG_FILTER_SUB | PNG_FILTER_UP | \
+                         PNG_FILTER_AVG | PNG_FILTER_PAETH)
 
 /* Filter values (not flags) - used in pngwrite.c, pngwutil.c for now.
  * These defines should NOT be changed.
@@ -1808,21 +1779,21 @@
 #define PNG_SET_WILL_FREE_DATA 1
 #define PNG_USER_WILL_FREE_DATA 2
 /* Flags for png_ptr->free_me and info_ptr->free_me */
-#define PNG_FREE_HIST 0x0008U
-#define PNG_FREE_ICCP 0x0010U
-#define PNG_FREE_SPLT 0x0020U
-#define PNG_FREE_ROWS 0x0040U
-#define PNG_FREE_PCAL 0x0080U
-#define PNG_FREE_SCAL 0x0100U
+#define PNG_FREE_HIST 0x0008
+#define PNG_FREE_ICCP 0x0010
+#define PNG_FREE_SPLT 0x0020
+#define PNG_FREE_ROWS 0x0040
+#define PNG_FREE_PCAL 0x0080
+#define PNG_FREE_SCAL 0x0100
 #ifdef PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
-#  define PNG_FREE_UNKN 0x0200U
+#  define PNG_FREE_UNKN 0x0200
 #endif
-/*      PNG_FREE_LIST 0x0400U   removed in 1.6.0 because it is ignored */
-#define PNG_FREE_PLTE 0x1000U
-#define PNG_FREE_TRNS 0x2000U
-#define PNG_FREE_TEXT 0x4000U
-#define PNG_FREE_ALL  0x7fffU
-#define PNG_FREE_MUL  0x4220U /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
+/*      PNG_FREE_LIST 0x0400    removed in 1.6.0 because it is ignored */
+#define PNG_FREE_PLTE 0x1000
+#define PNG_FREE_TRNS 0x2000
+#define PNG_FREE_TEXT 0x4000
+#define PNG_FREE_ALL  0x7fff
+#define PNG_FREE_MUL  0x4220 /* PNG_FREE_SPLT|PNG_FREE_TEXT|PNG_FREE_UNKN */
 
 #ifdef PNG_USER_MEM_SUPPORTED
 PNG_EXPORTA(100, png_voidp, png_malloc_default, (png_const_structrp png_ptr,
@@ -2946,19 +2917,12 @@
     * is the minimum 'row stride', the minimum count of components between each
     * row.  For a color-mapped image this is the minimum number of bytes in a
     * row.
-    *
-    * WARNING: this macro overflows for some images with more than one component
-    * and very large image widths.  libpng will refuse to process an image where
-    * this macro would overflow.
     */
 
 #define PNG_IMAGE_BUFFER_SIZE(image, row_stride)\
    (PNG_IMAGE_PIXEL_COMPONENT_SIZE((image).format)*(image).height*(row_stride))
    /* Return the size, in bytes, of an image buffer given a png_image and a row
     * stride - the number of components to leave space for in each row.
-    *
-    * WARNING: this macro overflows a 32-bit integer for some large PNG images,
-    * libpng will refuse to process an image where such an overflow would occur.
     */
 
 #define PNG_IMAGE_SIZE(image)\
@@ -3079,6 +3043,7 @@
 #endif /* SIMPLIFIED_READ */
 
 #ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
+#ifdef PNG_STDIO_SUPPORTED
 /* WRITE APIS
  * ----------
  * For write you must initialize a png_image structure to describe the image to
@@ -3095,7 +3060,6 @@
  *    values do not correspond to the colors in sRGB.
  * colormap_entries: set to the number of entries in the color-map (0 to 256)
  */
-#ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
 PNG_EXPORT(239, int, png_image_write_to_file, (png_imagep image,
    const char *file, int convert_to_8bit, const void *buffer,
    png_int_32 row_stride, const void *colormap));
@@ -3105,9 +3069,8 @@
    int convert_to_8_bit, const void *buffer, png_int_32 row_stride,
    const void *colormap));
    /* Write the image to the given (FILE*). */
-#endif /* SIMPLIFIED_WRITE_STDIO */
 
-/* With all write APIs if image is in one of the linear formats with 16-bit
+/* With both write APIs if image is in one of the linear formats with 16-bit
  * data then setting convert_to_8_bit will cause the output to be an 8-bit PNG
  * gamma encoded according to the sRGB specification, otherwise a 16-bit linear
  * encoded PNG file is written.
@@ -3119,103 +3082,13 @@
  *
  * With all APIs row_stride is handled as in the read APIs - it is the spacing
  * from one row to the next in component sized units (1 or 2 bytes) and if
- * negative indicates a bottom-up row layout in the buffer.  If row_stride is
- * zero, libpng will calculate it for you from the image width and number of
- * channels.
+ * negative indicates a bottom-up row layout in the buffer.  If row_stride is zero,
+ * libpng will calculate it for you from the image width and number of channels.
  *
- * Note that the write API does not support interlacing, sub-8-bit pixels or
- * most ancillary chunks.  If you need to write text chunks (e.g. for copyright
- * notices) you need to use one of the other APIs.
+ * Note that the write API does not support interlacing, sub-8-bit pixels, indexed
+ * PNG (color_type 3) or most ancillary chunks.
  */
-
-PNG_EXPORT(245, int, png_image_write_to_memory, (png_imagep image, void *memory,
-   png_alloc_size_t * PNG_RESTRICT memory_bytes, int convert_to_8_bit,
-   const void *buffer, png_int_32 row_stride, const void *colormap));
-   /* Write the image to the given memory buffer.  The function both writes the
-    * whole PNG data stream to *memory and updates *memory_bytes with the count
-    * of bytes written.
-    *
-    * 'memory' may be NULL.  In this case *memory_bytes is not read however on
-    * success the number of bytes which would have been written will still be
-    * stored in *memory_bytes.  On failure *memory_bytes will contain 0.
-    *
-    * If 'memory' is not NULL it must point to memory[*memory_bytes] of
-    * writeable memory.
-    *
-    * If the function returns success memory[*memory_bytes] (if 'memory' is not
-    * NULL) contains the written PNG data.  *memory_bytes will always be less
-    * than or equal to the original value.
-    *
-    * If the function returns false and *memory_bytes was not changed an error
-    * occured during write.  If *memory_bytes was changed, or is not 0 if
-    * 'memory' was NULL, the write would have succeeded but for the memory
-    * buffer being too small.  *memory_bytes contains the required number of
-    * bytes and will be bigger that the original value.
-    */
-
-#define png_image_write_get_memory_size(image, size, convert_to_8_bit, buffer,\
-   row_stride, colormap)\
-   png_image_write_to_memory(&(image), 0, &(size), convert_to_8_bit, buffer,\
-         row_stride, colormap)
-   /* Return the amount of memory in 'size' required to compress this image.
-    * The png_image structure 'image' must be filled in as in the above
-    * function and must not be changed before the actual write call, the buffer
-    * and all other parameters must also be identical to that in the final
-    * write call.  The 'size' variable need not be initialized.
-    *
-    * NOTE: the macro returns true/false, if false is returned 'size' will be
-    * set to zero and the write failed and probably will fail if tried again.
-    */
-
-/* You can pre-allocate the buffer by making sure it is of sufficient size
- * regardless of the amount of compression achieved.  The buffer size will
- * always be bigger than the original image and it will never be filled.  The
- * following macros are provided to assist in allocating the buffer.
- */
-#define PNG_IMAGE_DATA_SIZE(image) (PNG_IMAGE_SIZE(image)+(image).height)
-   /* The number of uncompressed bytes in the PNG byte encoding of the image;
-    * uncompressing the PNG IDAT data will give this number of bytes.
-    *
-    * NOTE: while PNG_IMAGE_SIZE cannot overflow for an image in memory this
-    * macro can because of the extra bytes used in the PNG byte encoding.  You
-    * need to avoid this macro if your image size approaches 2^30 in width or
-    * height.  The same goes for the remainder of these macros; they all produce
-    * bigger numbers than the actual in-memory image size.
-    */
-#ifndef PNG_ZLIB_MAX_SIZE
-#  define PNG_ZLIB_MAX_SIZE(b) ((b)+(((b)+7U)>>3)+(((b)+63U)>>6)+11U)
-   /* An upper bound on the number of compressed bytes given 'b' uncompressed
-    * bytes.  This is based on deflateBounds() in zlib; different
-    * implementations of zlib compression may conceivably produce more data so
-    * if your zlib implementation is not zlib itself redefine this macro
-    * appropriately.
-    */
-#endif
-
-#define PNG_IMAGE_COMPRESSED_SIZE_MAX(image)\
-   PNG_ZLIB_MAX_SIZE((png_alloc_size_t)PNG_IMAGE_DATA_SIZE(image))
-   /* An upper bound on the size of the data in the PNG IDAT chunks. */
-
-#define PNG_IMAGE_PNG_SIZE_MAX_(image, image_size)\
-   ((8U/*sig*/+25U/*IHDR*/+16U/*gAMA*/+44U/*cHRM*/+12U/*IEND*/+\
-    (((image).format&PNG_FORMAT_FLAG_COLORMAP)?/*colormap: PLTE, tRNS*/\
-     12U+3U*(image).colormap_entries/*PLTE data*/+\
-     (((image).format&PNG_FORMAT_FLAG_ALPHA)?\
-      12U/*tRNS*/+(image).colormap_entries:0U):0U)+\
-    12U)+(12U*((image_size)/PNG_ZBUF_SIZE))/*IDAT*/+(image_size))
-   /* A helper for the following macro; if your compiler cannot handle the
-    * following macro use this one with the result of
-    * PNG_IMAGE_COMPRESSED_SIZE_MAX(image) as the second argument (most
-    * compilers should handle this just fine.)
-    */
-
-#define PNG_IMAGE_PNG_SIZE_MAX(image)\
-   PNG_IMAGE_PNG_SIZE_MAX_(image, PNG_IMAGE_COMPRESSED_SIZE_MAX(image))
-   /* An upper bound on the total length of the PNG data stream for 'image'.
-    * The result is of type png_alloc_size_t, on 32-bit systems this may
-    * overflow even though PNG_IMAGE_DATA_SIZE does not overflow; the write will
-    * run out of buffer space but return a corrected size which should work.
-    */
+#endif /* STDIO */
 #endif /* SIMPLIFIED_WRITE */
 /*******************************************************************************
  *  END OF SIMPLIFIED API
@@ -3273,7 +3146,7 @@
  * one to use is one more than this.)
  */
 #ifdef PNG_EXPORT_LAST_ORDINAL
-  PNG_EXPORT_LAST_ORDINAL(245);
+  PNG_EXPORT_LAST_ORDINAL(244);
 #endif
 
 #ifdef __cplusplus
diff --git a/jdk/src/share/native/sun/awt/libpng/pngconf.h b/jdk/src/share/native/sun/awt/libpng/pngconf.h
index fd35b2a..482dcf7 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngconf.h
+++ b/jdk/src/share/native/sun/awt/libpng/pngconf.h
@@ -29,9 +29,9 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * libpng version 1.6.23, June 9, 2016
+ * libpng version 1.6.20, December 3, 2015
  *
- * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
diff --git a/jdk/src/share/native/sun/awt/libpng/pngdebug.h b/jdk/src/share/native/sun/awt/libpng/pngdebug.h
index f65bb8a..d308150 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngdebug.h
+++ b/jdk/src/share/native/sun/awt/libpng/pngdebug.h
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.6.8 [December 19, 2013]
- * Copyright (c) 1998-2002,2004,2006-2013 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2013 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
diff --git a/jdk/src/share/native/sun/awt/libpng/pngerror.c b/jdk/src/share/native/sun/awt/libpng/pngerror.c
index 920935a..7ab1cfe 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngerror.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngerror.c
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.6.15 [November 20, 2014]
- * Copyright (c) 1998-2002,2004,2006-2014 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2014 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -72,7 +72,7 @@
    if (png_ptr != NULL)
    {
       if ((png_ptr->flags &
-         (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT)) != 0)
+         (PNG_FLAG_STRIP_ERROR_NUMBERS|PNG_FLAG_STRIP_ERROR_TEXT)) != 0
       {
          if (*error_message == PNG_LITERAL_SHARP)
          {
diff --git a/jdk/src/share/native/sun/awt/libpng/pngget.c b/jdk/src/share/native/sun/awt/libpng/pngget.c
index 3b3fe19..a2c9d3a 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngget.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngget.c
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.6.17 [March 26, 2015]
- * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -484,11 +484,11 @@
    return (retval);
 }
 #endif /* pHYs */
-#endif /* INCH_CONVERSIONS */
+#endif  /* INCH_CONVERSIONS */
 
 /* png_get_channels really belongs in here, too, but it's been around longer */
 
-#endif /* EASY_ACCESS */
+#endif  /* EASY_ACCESS */
 
 
 png_byte PNGAPI
@@ -1170,19 +1170,19 @@
       return 0;
 
 #ifdef PNG_WRITE_SUPPORTED
-   if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0)
+      if ((png_ptr->mode & PNG_IS_READ_STRUCT) != 0)
 #endif
    {
 #ifdef PNG_SEQUENTIAL_READ_SUPPORTED
-      return png_ptr->IDAT_read_size;
+         return png_ptr->IDAT_read_size;
 #else
-      return PNG_IDAT_READ_SIZE;
+         return PNG_IDAT_READ_SIZE;
 #endif
    }
 
 #ifdef PNG_WRITE_SUPPORTED
-   else
-      return png_ptr->zbuffer_size;
+      else
+         return png_ptr->zbuffer_size;
 #endif
 }
 
diff --git a/jdk/src/share/native/sun/awt/libpng/pnginfo.h b/jdk/src/share/native/sun/awt/libpng/pnginfo.h
index 1dbf785..ff35082 100644
--- a/jdk/src/share/native/sun/awt/libpng/pnginfo.h
+++ b/jdk/src/share/native/sun/awt/libpng/pnginfo.h
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.6.1 [March 28, 2013]
- * Copyright (c) 1998-2002,2004,2006-2013 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2013 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
diff --git a/jdk/src/share/native/sun/awt/libpng/pnglibconf.h b/jdk/src/share/native/sun/awt/libpng/pnglibconf.h
index bd14d6e..bcb167e 100644
--- a/jdk/src/share/native/sun/awt/libpng/pnglibconf.h
+++ b/jdk/src/share/native/sun/awt/libpng/pnglibconf.h
@@ -27,15 +27,16 @@
 /* libpng STANDARD API DEFINITION */
 
 /* pnglibconf.h - library build configuration */
+
 /* This file is available under and governed by the GNU General Public
  * License version 2 only, as published by the Free Software Foundation.
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  */
 
-/* libpng version 1.6.23, June 9, 2016 */
+/* libpng version 1.6.20, December 3, 2015 */
 
-/* Copyright (c) 1998-2016 Glenn Randers-Pehrson */
+/* Copyright (c) 1998-2014 Glenn Randers-Pehrson */
 
 /* This code is released under the libpng license. */
 /* For conditions of distribution and use, see the disclaimer */
@@ -140,7 +141,6 @@
 #define PNG_SIMPLIFIED_READ_SUPPORTED
 /*#undef PNG_SIMPLIFIED_WRITE_AFIRST_SUPPORTED*/
 /*#undef PNG_SIMPLIFIED_WRITE_BGR_SUPPORTED*/
-/*#undef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED*/
 /*#undef PNG_SIMPLIFIED_WRITE_SUPPORTED*/
 #define PNG_STDIO_SUPPORTED
 #define PNG_STORE_UNKNOWN_CHUNKS_SUPPORTED
diff --git a/jdk/src/share/native/sun/awt/libpng/pngmem.c b/jdk/src/share/native/sun/awt/libpng/pngmem.c
index 967611f..71c6956 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngmem.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngmem.c
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.6.15 [November 20, 2014]
- * Copyright (c) 1998-2002,2004,2006-2014 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2014 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
diff --git a/jdk/src/share/native/sun/awt/libpng/pngpread.c b/jdk/src/share/native/sun/awt/libpng/pngpread.c
index 289e94c..e17c993 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngpread.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngpread.c
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.23 [June 9, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.18 [July 23, 2015]
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -238,14 +238,12 @@
           (png_ptr->mode & PNG_HAVE_PLTE) == 0)
          png_error(png_ptr, "Missing PLTE before IDAT");
 
+      png_ptr->mode |= PNG_HAVE_IDAT;
       png_ptr->process_mode = PNG_READ_IDAT_MODE;
 
-      if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
-         if ((png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) == 0)
-            if (png_ptr->push_length == 0)
-               return;
-
-      png_ptr->mode |= PNG_HAVE_IDAT;
+      if ((png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) == 0)
+         if (png_ptr->push_length == 0)
+            return;
 
       if ((png_ptr->mode & PNG_AFTER_IDAT) != 0)
          png_benign_error(png_ptr, "Too many IDATs found");
@@ -529,10 +527,7 @@
          png_error(png_ptr, "Insufficient memory for save_buffer");
       }
 
-      if (old_buffer)
-         memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
-      else if (png_ptr->save_buffer_size)
-         png_error(png_ptr, "save_buffer error");
+      memcpy(png_ptr->save_buffer, old_buffer, png_ptr->save_buffer_size);
       png_free(png_ptr, old_buffer);
       png_ptr->save_buffer_max = new_max;
    }
diff --git a/jdk/src/share/native/sun/awt/libpng/pngpriv.h b/jdk/src/share/native/sun/awt/libpng/pngpriv.h
index 05ed1eb..f5c1532 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngpriv.h
+++ b/jdk/src/share/native/sun/awt/libpng/pngpriv.h
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.22 [May 26, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.18 [July 23, 2015]
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -1945,9 +1945,6 @@
    (png_structp png_ptr, unsigned int bpp), PNG_EMPTY);
 #endif
 
-PNG_INTERNAL_FUNCTION(png_uint_32, png_check_keyword, (png_structrp png_ptr,
-   png_const_charp key, png_bytep new_key), PNG_EMPTY);
-
 /* Maintainer: Put new private prototypes here ^ */
 
 #include "pngdebug.h"
diff --git a/jdk/src/share/native/sun/awt/libpng/pngread.c b/jdk/src/share/native/sun/awt/libpng/pngread.c
index 8650556..69d5be2 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngread.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngread.c
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.23 [June 9, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.17 [March 26, 2015]
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -155,10 +155,7 @@
       }
 
       else if ((png_ptr->mode & PNG_HAVE_IDAT) != 0)
-      {
-         png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
          png_ptr->mode |= PNG_AFTER_IDAT;
-      }
 
       /* This should be a binary subdivision search or a hash for
        * matching the chunk name rather than a linear search.
@@ -816,9 +813,6 @@
       png_uint_32 length = png_read_chunk_header(png_ptr);
       png_uint_32 chunk_name = png_ptr->chunk_name;
 
-      if (chunk_name != png_IDAT)
-         png_ptr->mode |= PNG_HAVE_CHUNK_AFTER_IDAT;
-
       if (chunk_name == png_IEND)
          png_handle_IEND(png_ptr, info_ptr, length);
 
@@ -833,9 +827,9 @@
       {
          if (chunk_name == png_IDAT)
          {
-            if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
-                || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
-               png_benign_error(png_ptr, ".Too many IDATs found");
+            if ((length > 0) ||
+                (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
+               png_benign_error(png_ptr, "Too many IDATs found");
          }
          png_handle_unknown(png_ptr, info_ptr, length, keep);
          if (chunk_name == png_PLTE)
@@ -846,14 +840,10 @@
       else if (chunk_name == png_IDAT)
       {
          /* Zero length IDATs are legal after the last IDAT has been
-          * read, but not after other chunks have been read.  1.6 does not
-          * always read all the deflate data; specifically it cannot be relied
-          * upon to read the Adler32 at the end.  If it doesn't ignore IDAT
-          * chunks which are longer than zero as well:
+          * read, but not after other chunks have been read.
           */
-         if ((length > 0 && !(png_ptr->flags & PNG_FLAG_ZSTREAM_ENDED))
-             || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
-            png_benign_error(png_ptr, "..Too many IDATs found");
+         if ((length > 0) || (png_ptr->mode & PNG_HAVE_CHUNK_AFTER_IDAT) != 0)
+            png_benign_error(png_ptr, "Too many IDATs found");
 
          png_crc_finish(png_ptr, length);
       }
@@ -3886,16 +3876,16 @@
             else
                filler = 255;
 
-#ifdef PNG_FORMAT_AFIRST_SUPPORTED
-            if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
-            {
-               where = PNG_FILLER_BEFORE;
-               change &= ~PNG_FORMAT_FLAG_AFIRST;
-            }
+#           ifdef PNG_FORMAT_AFIRST_SUPPORTED
+               if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
+               {
+                  where = PNG_FILLER_BEFORE;
+                  change &= ~PNG_FORMAT_FLAG_AFIRST;
+               }
 
-            else
-#endif
-            where = PNG_FILLER_AFTER;
+               else
+#           endif
+               where = PNG_FILLER_AFTER;
 
             png_set_add_alpha(png_ptr, filler, where);
          }
@@ -4003,12 +3993,12 @@
       if (info_ptr->bit_depth == 16)
          info_format |= PNG_FORMAT_FLAG_LINEAR;
 
-#ifdef PNG_FORMAT_BGR_SUPPORTED
-      if ((png_ptr->transformations & PNG_BGR) != 0)
-         info_format |= PNG_FORMAT_FLAG_BGR;
-#endif
+#     ifdef PNG_FORMAT_BGR_SUPPORTED
+         if ((png_ptr->transformations & PNG_BGR) != 0)
+            info_format |= PNG_FORMAT_FLAG_BGR;
+#     endif
 
-#ifdef PNG_FORMAT_AFIRST_SUPPORTED
+#     ifdef PNG_FORMAT_AFIRST_SUPPORTED
          if (do_local_background == 2)
          {
             if ((format & PNG_FORMAT_FLAG_AFIRST) != 0)
@@ -4109,84 +4099,58 @@
 {
    if (image != NULL && image->version == PNG_IMAGE_VERSION)
    {
-      /* Check for row_stride overflow.  This check is not performed on the
-       * original PNG format because it may not occur in the output PNG format
-       * and libpng deals with the issues of reading the original.
-       */
-      const unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
+      png_uint_32 check;
 
-      if (image->width <= 0x7FFFFFFFU/channels) /* no overflow */
+      if (row_stride == 0)
+         row_stride = PNG_IMAGE_ROW_STRIDE(*image);
+
+      if (row_stride < 0)
+         check = -row_stride;
+
+      else
+         check = row_stride;
+
+      if (image->opaque != NULL && buffer != NULL &&
+         check >= PNG_IMAGE_ROW_STRIDE(*image))
       {
-         png_uint_32 check;
-         const png_uint_32 png_row_stride = image->width * channels;
-
-         if (row_stride == 0)
-            row_stride = (png_int_32)/*SAFE*/png_row_stride;
-
-         if (row_stride < 0)
-            check = -row_stride;
-
-         else
-            check = row_stride;
-
-         if (image->opaque != NULL && buffer != NULL && check >= png_row_stride)
+         if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
+            (image->colormap_entries > 0 && colormap != NULL))
          {
-            /* Now check for overflow of the image buffer calculation; this
-             * limits the whole image size to 32 bits for API compatibility with
-             * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
+            int result;
+            png_image_read_control display;
+
+            memset(&display, 0, (sizeof display));
+            display.image = image;
+            display.buffer = buffer;
+            display.row_stride = row_stride;
+            display.colormap = colormap;
+            display.background = background;
+            display.local_row = NULL;
+
+            /* Choose the correct 'end' routine; for the color-map case all the
+             * setup has already been done.
              */
-            if (image->height <= 0xFFFFFFFF/png_row_stride)
-            {
-               if ((image->format & PNG_FORMAT_FLAG_COLORMAP) == 0 ||
-                  (image->colormap_entries > 0 && colormap != NULL))
-               {
-                  int result;
-                  png_image_read_control display;
-
-                  memset(&display, 0, (sizeof display));
-                  display.image = image;
-                  display.buffer = buffer;
-                  display.row_stride = row_stride;
-                  display.colormap = colormap;
-                  display.background = background;
-                  display.local_row = NULL;
-
-                  /* Choose the correct 'end' routine; for the color-map case
-                   * all the setup has already been done.
-                   */
-                  if ((image->format & PNG_FORMAT_FLAG_COLORMAP) != 0)
-                     result = png_safe_execute(image,
-                                    png_image_read_colormap, &display) &&
-                              png_safe_execute(image,
-                                    png_image_read_colormapped, &display);
-
-                  else
-                     result =
-                        png_safe_execute(image,
-                              png_image_read_direct, &display);
-
-                  png_image_free(image);
-                  return result;
-               }
-
-               else
-                  return png_image_error(image,
-                     "png_image_finish_read[color-map]: no color-map");
-            }
+            if ((image->format & PNG_FORMAT_FLAG_COLORMAP) != 0)
+               result =
+                  png_safe_execute(image, png_image_read_colormap, &display) &&
+                  png_safe_execute(image, png_image_read_colormapped, &display);
 
             else
-               return png_image_error(image,
-                  "png_image_finish_read: image too large");
+               result =
+                  png_safe_execute(image, png_image_read_direct, &display);
+
+            png_image_free(image);
+            return result;
          }
 
          else
             return png_image_error(image,
-               "png_image_finish_read: invalid argument");
+               "png_image_finish_read[color-map]: no color-map");
       }
 
       else
          return png_image_error(image,
-            "png_image_finish_read: row_stride too large");
+            "png_image_finish_read: invalid argument");
    }
 
    else if (image != NULL)
diff --git a/jdk/src/share/native/sun/awt/libpng/pngrio.c b/jdk/src/share/native/sun/awt/libpng/pngrio.c
index 0ac5c4b..b72cafd 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngrio.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngrio.c
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.6.17 [March 26, 2015]
- * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
diff --git a/jdk/src/share/native/sun/awt/libpng/pngrtran.c b/jdk/src/share/native/sun/awt/libpng/pngrtran.c
index 51585b0..b6b731d 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngrtran.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngrtran.c
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.22 [May 26, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.19 [November 12, 2015]
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -187,7 +187,7 @@
    png_set_background_fixed(png_ptr, background_color, background_gamma_code,
       need_expand, png_fixed(png_ptr, background_gamma, "png_set_background"));
 }
-#  endif /* FLOATING_POINT */
+#  endif  /* FLOATING_POINT */
 #endif /* READ_BACKGROUND */
 
 /* Scale 16-bit depth files to 8-bit depth.  If both of these are set then the
@@ -317,12 +317,9 @@
     * is expected to be 1 or greater, but this range test allows for some
     * viewing correction values.  The intent is to weed out users of this API
     * who use the inverse of the gamma value accidentally!  Since some of these
-    * values are reasonable this may have to be changed:
-    *
-    * 1.6.x: changed from 0.07..3 to 0.01..100 (to accomodate the optimal 16-bit
-    * gamma of 36, and its reciprocal.)
+    * values are reasonable this may have to be changed.
     */
-   if (output_gamma < 1000 || output_gamma > 10000000)
+   if (output_gamma < 70000 || output_gamma > 300000)
       png_error(png_ptr, "output gamma out of expected range");
 
    /* The default file gamma is the inverse of the output gamma; the output
@@ -1943,7 +1940,7 @@
             png_ptr->palette[i].blue = (png_byte)component;
          }
    }
-#endif /* READ_SHIFT */
+#endif  /* READ_SHIFT */
 }
 
 /* Modify the info structure to reflect the transformations.  The
diff --git a/jdk/src/share/native/sun/awt/libpng/pngrutil.c b/jdk/src/share/native/sun/awt/libpng/pngrutil.c
index 6722f3b..a2e5846 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngrutil.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngrutil.c
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.20 [December 3, 2014]
- * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.20 [December 3, 2015]
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
diff --git a/jdk/src/share/native/sun/awt/libpng/pngset.c b/jdk/src/share/native/sun/awt/libpng/pngset.c
index a610db6..748008e 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngset.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngset.c
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.23 [June 9, 2016]
- * Copyright (c) 1998-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.19 [November 12, 2015]
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -980,14 +980,12 @@
 
        png_free_data(png_ptr, info_ptr, PNG_FREE_TRNS, 0);
 
+       /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
+       png_ptr->trans_alpha = info_ptr->trans_alpha = png_voidcast(png_bytep,
+         png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH));
+
        if (num_trans > 0 && num_trans <= PNG_MAX_PALETTE_LENGTH)
-       {
-         /* Changed from num_trans to PNG_MAX_PALETTE_LENGTH in version 1.2.1 */
-          info_ptr->trans_alpha = png_voidcast(png_bytep,
-             png_malloc(png_ptr, PNG_MAX_PALETTE_LENGTH));
           memcpy(info_ptr->trans_alpha, trans_alpha, (png_size_t)num_trans);
-       }
-       png_ptr->trans_alpha = info_ptr->trans_alpha;
    }
 
    if (trans_color != NULL)
@@ -1674,88 +1672,4 @@
       png_ptr->num_palette_max = -1;
 }
 #endif
-
-#if defined(PNG_TEXT_SUPPORTED) || defined(PNG_pCAL_SUPPORTED) || \
-    defined(PNG_iCCP_SUPPORTED) || defined(PNG_sPLT_SUPPORTED)
-/* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
- * and if invalid, correct the keyword rather than discarding the entire
- * chunk.  The PNG 1.0 specification requires keywords 1-79 characters in
- * length, forbids leading or trailing whitespace, multiple internal spaces,
- * and the non-break space (0x80) from ISO 8859-1.  Returns keyword length.
- *
- * The 'new_key' buffer must be 80 characters in size (for the keyword plus a
- * trailing '\0').  If this routine returns 0 then there was no keyword, or a
- * valid one could not be generated, and the caller must png_error.
- */
-png_uint_32 /* PRIVATE */
-png_check_keyword(png_structrp png_ptr, png_const_charp key, png_bytep new_key)
-{
-   png_const_charp orig_key = key;
-   png_uint_32 key_len = 0;
-   int bad_character = 0;
-   int space = 1;
-
-   png_debug(1, "in png_check_keyword");
-
-   if (key == NULL)
-   {
-      *new_key = 0;
-      return 0;
-   }
-
-   while (*key && key_len < 79)
-   {
-      png_byte ch = (png_byte)*key++;
-
-      if ((ch > 32 && ch <= 126) || (ch >= 161 /*&& ch <= 255*/))
-         *new_key++ = ch, ++key_len, space = 0;
-
-      else if (space == 0)
-      {
-         /* A space or an invalid character when one wasn't seen immediately
-          * before; output just a space.
-          */
-         *new_key++ = 32, ++key_len, space = 1;
-
-         /* If the character was not a space then it is invalid. */
-         if (ch != 32)
-            bad_character = ch;
-      }
-
-      else if (bad_character == 0)
-         bad_character = ch; /* just skip it, record the first error */
-   }
-
-   if (key_len > 0 && space != 0) /* trailing space */
-   {
-      --key_len, --new_key;
-      if (bad_character == 0)
-         bad_character = 32;
-   }
-
-   /* Terminate the keyword */
-   *new_key = 0;
-
-   if (key_len == 0)
-      return 0;
-
-#ifdef PNG_WARNINGS_SUPPORTED
-   /* Try to only output one warning per keyword: */
-   if (*key != 0) /* keyword too long */
-      png_warning(png_ptr, "keyword truncated");
-
-   else if (bad_character != 0)
-   {
-      PNG_WARNING_PARAMETERS(p)
-
-      png_warning_parameter(p, 1, orig_key);
-      png_warning_parameter_signed(p, 2, PNG_NUMBER_FORMAT_02x, bad_character);
-
-      png_formatted_warning(png_ptr, p, "keyword \"@1\": bad character '0x@2'");
-   }
-#endif /* WARNINGS */
-
-   return key_len;
-}
-#endif /* TEXT || pCAL || iCCP || sPLT */
 #endif /* READ || WRITE */
diff --git a/jdk/src/share/native/sun/awt/libpng/pngstruct.h b/jdk/src/share/native/sun/awt/libpng/pngstruct.h
index ae72f32..e47c02d 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngstruct.h
+++ b/jdk/src/share/native/sun/awt/libpng/pngstruct.h
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.6.18 [July 23, 2015]
- * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
diff --git a/jdk/src/share/native/sun/awt/libpng/pngtest.c b/jdk/src/share/native/sun/awt/libpng/pngtest.c
index 399e67f..ef3a4ab 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngtest.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngtest.c
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.5.25 [December 3, 2015]
- * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -71,15 +71,6 @@
 
 #include "png.h"
 
-/* 1.6.1 added support for the configure test harness, which uses 77 to indicate
- * a skipped test, in earlier versions we need to succeed on a skipped test, so:
- */
-#if PNG_LIBPNG_VER >= 10601 && defined(HAVE_CONFIG_H)
-#  define SKIP 77
-#else
-#  define SKIP 0
-#endif
-
 /* Known chunks that exist in pngtest.png must be supported or pngtest will fail
  * simply as a result of re-ordering them.  This may be fixed in 1.7
  *
@@ -2102,9 +2093,9 @@
    fprintf(STDERR,
       " test ignored because libpng was not built with read support\n");
    /* And skip this test */
-   return SKIP;
+   return PNG_LIBPNG_VER < 10600 ? 0 : 77;
 }
 #endif
 
 /* Generate a compiler error if there is an old png.h in the search path. */
-typedef png_libpng_version_1_6_23 Your_png_h_is_not_version_1_6_23;
+typedef png_libpng_version_1_6_20 Your_png_h_is_not_version_1_6_20;
diff --git a/jdk/src/share/native/sun/awt/libpng/pngtrans.c b/jdk/src/share/native/sun/awt/libpng/pngtrans.c
index e2d11b0..d6016df 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngtrans.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngtrans.c
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.6.18 [July 23, 2015]
- * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
diff --git a/jdk/src/share/native/sun/awt/libpng/pngwio.c b/jdk/src/share/native/sun/awt/libpng/pngwio.c
index ea5f595..7268523 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngwio.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngwio.c
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.6.15 [November 20, 2014]
- * Copyright (c) 1998-2002,2004,2006-2014 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2014 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
diff --git a/jdk/src/share/native/sun/awt/libpng/pngwrite.c b/jdk/src/share/native/sun/awt/libpng/pngwrite.c
index 6dfb3c2..d7d751d 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngwrite.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngwrite.c
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.6.19 [November 12, 2015]
- * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -40,9 +40,9 @@
  */
 
 #include "pngpriv.h"
-#ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
+#if defined(PNG_SIMPLIFIED_WRITE_SUPPORTED) && defined(PNG_STDIO_SUPPORTED)
 #  include <errno.h>
-#endif /* SIMPLIFIED_WRITE_STDIO */
+#endif
 
 #ifdef PNG_WRITE_SUPPORTED
 
@@ -1480,6 +1480,7 @@
 
 
 #ifdef PNG_SIMPLIFIED_WRITE_SUPPORTED
+# ifdef PNG_STDIO_SUPPORTED /* currently required for png_image_write_* */
 /* Initialize the write structure - general purpose utility. */
 static int
 png_image_write_init(png_imagep image)
@@ -1531,10 +1532,6 @@
    png_const_voidp first_row;
    ptrdiff_t       row_bytes;
    png_voidp       local_row;
-   /* Byte count for memory writing */
-   png_bytep        memory;
-   png_alloc_size_t memory_bytes; /* not used for STDIO */
-   png_alloc_size_t output_bytes; /* running total */
 } png_image_write_control;
 
 /* Write png_uint_16 input to a 16-bit PNG; the png_ptr has already been set to
@@ -1962,43 +1959,9 @@
       png_set_benign_errors(png_ptr, 0/*error*/);
 #   endif
 
-   /* Default the 'row_stride' parameter if required, also check the row stride
-    * and total image size to ensure that they are within the system limits.
-    */
-   {
-      const unsigned int channels = PNG_IMAGE_PIXEL_CHANNELS(image->format);
-
-      if (image->width <= 0x7FFFFFFFU/channels) /* no overflow */
-      {
-         png_uint_32 check;
-         const png_uint_32 png_row_stride = image->width * channels;
-
-         if (display->row_stride == 0)
-            display->row_stride = (png_int_32)/*SAFE*/png_row_stride;
-
-         if (display->row_stride < 0)
-            check = -display->row_stride;
-
-         else
-            check = display->row_stride;
-
-         if (check >= png_row_stride)
-         {
-            /* Now check for overflow of the image buffer calculation; this
-             * limits the whole image size to 32 bits for API compatibility with
-             * the current, 32-bit, PNG_IMAGE_BUFFER_SIZE macro.
-             */
-            if (image->height > 0xFFFFFFFF/png_row_stride)
-               png_error(image->opaque->png_ptr, "memory image too large");
-         }
-
-         else
-            png_error(image->opaque->png_ptr, "supplied row stride too small");
-      }
-
-      else
-         png_error(image->opaque->png_ptr, "image row stride too large");
-   }
+   /* Default the 'row_stride' parameter if required. */
+   if (display->row_stride == 0)
+      display->row_stride = PNG_IMAGE_ROW_STRIDE(*image);
 
    /* Set the required transforms then write the rows in the correct order. */
    if ((format & PNG_FORMAT_FLAG_COLORMAP) != 0)
@@ -2175,122 +2138,6 @@
    return 1;
 }
 
-
-static void (PNGCBAPI
-image_memory_write)(png_structp png_ptr, png_bytep/*const*/ data,
-   png_size_t size)
-{
-   png_image_write_control *display = png_voidcast(png_image_write_control*,
-      png_ptr->io_ptr/*backdoor: png_get_io_ptr(png_ptr)*/);
-   const png_alloc_size_t ob = display->output_bytes;
-
-   /* Check for overflow; this should never happen: */
-   if (size <= ((png_alloc_size_t)-1) - ob)
-   {
-      /* I don't think libpng ever does this, but just in case: */
-      if (size > 0)
-      {
-         if (display->memory_bytes >= ob+size) /* writing */
-            memcpy(display->memory+ob, data, size);
-
-         /* Always update the size: */
-         display->output_bytes = ob+size;
-      }
-   }
-
-   else
-      png_error(png_ptr, "png_image_write_to_memory: PNG too big");
-}
-
-static void (PNGCBAPI
-image_memory_flush)(png_structp png_ptr)
-{
-   PNG_UNUSED(png_ptr)
-}
-
-static int
-png_image_write_memory(png_voidp argument)
-{
-   png_image_write_control *display = png_voidcast(png_image_write_control*,
-      argument);
-
-   /* The rest of the memory-specific init and write_main in an error protected
-    * environment.  This case needs to use callbacks for the write operations
-    * since libpng has no built in support for writing to memory.
-    */
-   png_set_write_fn(display->image->opaque->png_ptr, display/*io_ptr*/,
-         image_memory_write, image_memory_flush);
-
-   return png_image_write_main(display);
-}
-
-int PNGAPI
-png_image_write_to_memory(png_imagep image, void *memory,
-   png_alloc_size_t * PNG_RESTRICT memory_bytes, int convert_to_8bit,
-   const void *buffer, png_int_32 row_stride, const void *colormap)
-{
-   /* Write the image to the given buffer, or count the bytes if it is NULL */
-   if (image != NULL && image->version == PNG_IMAGE_VERSION)
-   {
-      if (memory_bytes != NULL && buffer != NULL)
-      {
-         /* This is to give the caller an easier error detection in the NULL
-          * case and guard against uninitialized variable problems:
-          */
-         if (memory == NULL)
-            *memory_bytes = 0;
-
-         if (png_image_write_init(image) != 0)
-         {
-            png_image_write_control display;
-            int result;
-
-            memset(&display, 0, (sizeof display));
-            display.image = image;
-            display.buffer = buffer;
-            display.row_stride = row_stride;
-            display.colormap = colormap;
-            display.convert_to_8bit = convert_to_8bit;
-            display.memory = png_voidcast(png_bytep, memory);
-            display.memory_bytes = *memory_bytes;
-            display.output_bytes = 0;
-
-            result = png_safe_execute(image, png_image_write_memory, &display);
-            png_image_free(image);
-
-            /* write_memory returns true even if we ran out of buffer. */
-            if (result)
-            {
-               /* On out-of-buffer this function returns '0' but still updates
-                * memory_bytes:
-                */
-               if (memory != NULL && display.output_bytes > *memory_bytes)
-                  result = 0;
-
-               *memory_bytes = display.output_bytes;
-            }
-
-            return result;
-         }
-
-         else
-            return 0;
-      }
-
-      else
-         return png_image_error(image,
-            "png_image_write_to_memory: invalid argument");
-   }
-
-   else if (image != NULL)
-      return png_image_error(image,
-         "png_image_write_to_memory: incorrect PNG_IMAGE_VERSION");
-
-   else
-      return 0;
-}
-
-#ifdef PNG_SIMPLIFIED_WRITE_STDIO_SUPPORTED
 int PNGAPI
 png_image_write_to_stdio(png_imagep image, FILE *file, int convert_to_8bit,
    const void *buffer, png_int_32 row_stride, const void *colormap)
@@ -2298,7 +2145,7 @@
    /* Write the image to the given (FILE*). */
    if (image != NULL && image->version == PNG_IMAGE_VERSION)
    {
-      if (file != NULL && buffer != NULL)
+      if (file != NULL)
       {
          if (png_image_write_init(image) != 0)
          {
@@ -2348,7 +2195,7 @@
    /* Write the image to the named file. */
    if (image != NULL && image->version == PNG_IMAGE_VERSION)
    {
-      if (file_name != NULL && buffer != NULL)
+      if (file_name != NULL)
       {
          FILE *fp = fopen(file_name, "wb");
 
@@ -2406,6 +2253,6 @@
    else
       return 0;
 }
-#endif /* SIMPLIFIED_WRITE_STDIO */
+# endif /* STDIO */
 #endif /* SIMPLIFIED_WRITE */
 #endif /* WRITE */
diff --git a/jdk/src/share/native/sun/awt/libpng/pngwtran.c b/jdk/src/share/native/sun/awt/libpng/pngwtran.c
index e962c4f..44e7daf 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngwtran.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngwtran.c
@@ -30,7 +30,7 @@
  * file and, per its terms, should not be removed:
  *
  * Last changed in libpng 1.6.18 [July 23, 2015]
- * Copyright (c) 1998-2002,2004,2006-2015 Glenn Randers-Pehrson
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
diff --git a/jdk/src/share/native/sun/awt/libpng/pngwutil.c b/jdk/src/share/native/sun/awt/libpng/pngwutil.c
index daeb1e7..a51f24b 100644
--- a/jdk/src/share/native/sun/awt/libpng/pngwutil.c
+++ b/jdk/src/share/native/sun/awt/libpng/pngwutil.c
@@ -29,8 +29,8 @@
  * However, the following notice accompanied the original version of this
  * file and, per its terms, should not be removed:
  *
- * Last changed in libpng 1.6.22 [May 26, 2016]
- * Copyright (c) 1998-2002,2004,2006-2016 Glenn Randers-Pehrson
+ * Last changed in libpng 1.6.19 [November 12, 2015]
+ * Copyright (c) 1998-2015 Glenn Randers-Pehrson
  * (Version 0.96 Copyright (c) 1996, 1997 Andreas Dilger)
  * (Version 0.88 Copyright (c) 1995, 1996 Guy Eric Schalnat, Group 42, Inc.)
  *
@@ -51,10 +51,10 @@
 void PNGAPI
 png_save_uint_32(png_bytep buf, png_uint_32 i)
 {
-   buf[0] = (png_byte)((i >> 24) & 0xffU);
-   buf[1] = (png_byte)((i >> 16) & 0xffU);
-   buf[2] = (png_byte)((i >>  8) & 0xffU);
-   buf[3] = (png_byte)( i        & 0xffU);
+   buf[0] = (png_byte)(i >> 24);
+   buf[1] = (png_byte)(i >> 16);
+   buf[2] = (png_byte)(i >> 8);
+   buf[3] = (png_byte)(i     );
 }
 
 /* Place a 16-bit number into a buffer in PNG byte order.
@@ -64,8 +64,8 @@
 void PNGAPI
 png_save_uint_16(png_bytep buf, unsigned int i)
 {
-   buf[0] = (png_byte)((i >> 8) & 0xffU);
-   buf[1] = (png_byte)( i       & 0xffU);
+   buf[0] = (png_byte)(i >> 8);
+   buf[1] = (png_byte)(i     );
 }
 #endif
 
@@ -693,6 +693,90 @@
 }
 #endif /* WRITE_COMPRESSED_TEXT */
 
+#if defined(PNG_WRITE_TEXT_SUPPORTED) || defined(PNG_WRITE_pCAL_SUPPORTED) || \
+    defined(PNG_WRITE_iCCP_SUPPORTED) || defined(PNG_WRITE_sPLT_SUPPORTED)
+/* Check that the tEXt or zTXt keyword is valid per PNG 1.0 specification,
+ * and if invalid, correct the keyword rather than discarding the entire
+ * chunk.  The PNG 1.0 specification requires keywords 1-79 characters in
+ * length, forbids leading or trailing whitespace, multiple internal spaces,
+ * and the non-break space (0x80) from ISO 8859-1.  Returns keyword length.
+ *
+ * The 'new_key' buffer must be 80 characters in size (for the keyword plus a
+ * trailing '\0').  If this routine returns 0 then there was no keyword, or a
+ * valid one could not be generated, and the caller must png_error.
+ */
+static png_uint_32
+png_check_keyword(png_structrp png_ptr, png_const_charp key, png_bytep new_key)
+{
+   png_const_charp orig_key = key;
+   png_uint_32 key_len = 0;
+   int bad_character = 0;
+   int space = 1;
+
+   png_debug(1, "in png_check_keyword");
+
+   if (key == NULL)
+   {
+      *new_key = 0;
+      return 0;
+   }
+
+   while (*key && key_len < 79)
+   {
+      png_byte ch = (png_byte)*key++;
+
+      if ((ch > 32 && ch <= 126) || (ch >= 161 /*&& ch <= 255*/))
+         *new_key++ = ch, ++key_len, space = 0;
+
+      else if (space == 0)
+      {
+         /* A space or an invalid character when one wasn't seen immediately
+          * before; output just a space.
+          */
+         *new_key++ = 32, ++key_len, space = 1;
+
+         /* If the character was not a space then it is invalid. */
+         if (ch != 32)
+            bad_character = ch;
+      }
+
+      else if (bad_character == 0)
+         bad_character = ch; /* just skip it, record the first error */
+   }
+
+   if (key_len > 0 && space != 0) /* trailing space */
+   {
+      --key_len, --new_key;
+      if (bad_character == 0)
+         bad_character = 32;
+   }
+
+   /* Terminate the keyword */
+   *new_key = 0;
+
+   if (key_len == 0)
+      return 0;
+
+#ifdef PNG_WARNINGS_SUPPORTED
+   /* Try to only output one warning per keyword: */
+   if (*key != 0) /* keyword too long */
+      png_warning(png_ptr, "keyword truncated");
+
+   else if (bad_character != 0)
+   {
+      PNG_WARNING_PARAMETERS(p)
+
+      png_warning_parameter(p, 1, orig_key);
+      png_warning_parameter_signed(p, 2, PNG_NUMBER_FORMAT_02x, bad_character);
+
+      png_formatted_warning(png_ptr, p, "keyword \"@1\": bad character '0x@2'");
+   }
+#endif /* WARNINGS */
+
+   return key_len;
+}
+#endif /* WRITE_TEXT || WRITE_pCAL || WRITE_iCCP || WRITE_sPLT */
+
 /* Write the IHDR chunk, and update the png_struct with the necessary
  * information.  Note that the rest of this code depends upon this
  * information being correct.
diff --git a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c
index 2845899..472b5ee 100644
--- a/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c
+++ b/jdk/src/share/native/sun/awt/medialib/awt_ImagingLib.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 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
@@ -772,7 +772,6 @@
     mlib_image *src;
     mlib_image *dst;
     int i;
-    int j = 0;
     int retStatus = 1;
     mlib_status status;
     double *matrix;
@@ -825,15 +824,6 @@
         return 0;
     }
 
-    /* Check for invalid double value in transformation matrix */
-    for (j = 0; j < 6; j++) {
-
-        if (!(IS_FINITE(matrix[j]))) {
-            (*env)->ReleasePrimitiveArrayCritical(env, jmatrix, matrix, JNI_ABORT);
-            return 0;
-        }
-    }
-
     if (s_printIt) {
         printf("matrix is %g %g %g %g %g %g\n", matrix[0], matrix[1],
                matrix[2], matrix[3], matrix[4], matrix[5]);
@@ -990,7 +980,6 @@
     mlib_image *src;
     mlib_image *dst;
     int i;
-    int j = 0;
     int retStatus = 1;
     mlib_status status;
     double *matrix;
@@ -1055,17 +1044,6 @@
         return 0;
     }
 
-    /* Check for invalid double value in transformation matrix */
-    for (j = 0; j < 6; j++) {
-
-        if (!(IS_FINITE(matrix[j]))) {
-            (*env)->ReleasePrimitiveArrayCritical(env, jmatrix, matrix, JNI_ABORT);
-            free(srcRasterP);
-            free(dstRasterP);
-            return 0;
-        }
-    }
-
     if (s_printIt) {
         printf("matrix is %g %g %g %g %g %g\n", matrix[0], matrix[1],
                matrix[2], matrix[3], matrix[4], matrix[5]);
diff --git a/jdk/src/share/native/sun/awt/medialib/mlib_ImageScanPoly.c b/jdk/src/share/native/sun/awt/medialib/mlib_ImageScanPoly.c
index ccc1572..34c2171 100644
--- a/jdk/src/share/native/sun/awt/medialib/mlib_ImageScanPoly.c
+++ b/jdk/src/share/native/sun/awt/medialib/mlib_ImageScanPoly.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1997, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1997, 2003, Oracle and/or its affiliates. All rights reserved.
  * 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,8 +33,6 @@
 #include "mlib_image.h"
 #include "mlib_SysMath.h"
 #include "mlib_ImageAffine.h"
-#include "safe_math.h"
-
 
 /***************************************************************/
 mlib_status mlib_AffineEdges(mlib_affine_param *param,
@@ -85,12 +83,6 @@
   dstYStride = mlib_ImageGetStride(dst);
   paddings = mlib_ImageGetPaddings(src);
 
-  /* All the transformation matrix parameters should be finite. if not, return failure */
-  if (!(IS_FINITE(a) && IS_FINITE(b) && IS_FINITE(c) && IS_FINITE(d) &&
-        IS_FINITE(tx) && IS_FINITE(ty))) {
-    return MLIB_FAILURE;
-  }
-
   if (srcWidth >= (1 << 15) || srcHeight >= (1 << 15)) {
     return MLIB_FAILURE;
   }
@@ -296,10 +288,6 @@
     if (dY1 == dY2)
       continue;
 
-    if (!(IS_FINITE(slope))) {
-       continue;
-    }
-
     if (dY1 < 0.0)
       y1 = 0;
     else {
@@ -340,10 +328,6 @@
     if (dY1 == dY2)
       continue;
 
-    if (!(IS_FINITE(slope))) {
-        continue;
-    }
-
     if (dY1 < 0.0)
       y1 = 0;
     else {
diff --git a/jdk/src/share/native/sun/awt/medialib/safe_math.h b/jdk/src/share/native/sun/awt/medialib/safe_math.h
index a87eba1..34c1fc5 100644
--- a/jdk/src/share/native/sun/awt/medialib/safe_math.h
+++ b/jdk/src/share/native/sun/awt/medialib/safe_math.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -26,15 +26,10 @@
 #ifndef __SAFE_MATH_H__
 #define __SAFE_MATH_H__
 
-#include "mlib_types.h"
-
 #define SAFE_TO_MULT(a, b) \
     (((a) > 0) && ((b) >= 0) && ((0x7fffffff / (a)) > (b)))
 
 #define SAFE_TO_ADD(a, b) \
     (((a) >= 0) && ((b) >= 0) && ((0x7fffffff - (a)) > (b)))
 
-#define IS_FINITE(a) \
-    (((a) >= MLIB_D64_MIN) && ((a) <= MLIB_D64_MAX))
-
 #endif // __SAFE_MATH_H__
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c
index ae7038c..86ec167 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscam02.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2012 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c
index 9e03316..664a3c9 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscgats.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2012 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -625,7 +625,7 @@
 }
 
 // Parses a float number
-// This can not call directly atof because it uses locale dependent
+// This can not call directly atof because it uses locale dependant
 // parsing, while CCMX files always use . as decimal separator
 static
 cmsFloat64Number ParseFloatNumber(const char *Buffer)
@@ -830,11 +830,11 @@
 
                     if (it8 ->sy == SINUM) {
 
-                        snprintf(it8->id, 127, "%d", it8->inum);
+                        sprintf(it8->id, "%d", it8->inum);
                     }
                     else {
 
-                        snprintf(it8->id, 127, it8 ->DoubleFormatter, it8->dnum);
+                        sprintf(it8->id, it8 ->DoubleFormatter, it8->dnum);
                     }
 
                     k = (int) strlen(it8 ->id);
@@ -1392,7 +1392,7 @@
     cmsIT8* it8 = (cmsIT8*) hIT8;
     char Buffer[1024];
 
-    snprintf(Buffer, 1023, it8->DoubleFormatter, Val);
+    sprintf(Buffer, it8->DoubleFormatter, Val);
 
     return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_UNCOOKED) != NULL;
 }
@@ -1402,7 +1402,7 @@
     cmsIT8* it8 = (cmsIT8*) hIT8;
     char Buffer[1024];
 
-    snprintf(Buffer, 1023, "%u", Val);
+    sprintf(Buffer, "%u", Val);
 
     return AddToList(it8, &GetTable(it8)->HeaderList, cProp, NULL, Buffer, WRITE_HEXADECIMAL) != NULL;
 }
@@ -1846,7 +1846,7 @@
 }
 
 
-// -------------------------------------------------------------- Higher level parsing
+// -------------------------------------------------------------- Higer level parsing
 
 static
 cmsBool DataFormatSection(cmsIT8* it8)
@@ -2149,7 +2149,7 @@
 
 
 
-// Init useful pointers
+// Init usefull pointers
 
 static
 void CookPointers(cmsIT8* it8)
@@ -2546,9 +2546,9 @@
 
         fld = GetDataFormat(it8, i);
         if (fld != NULL) {
-            if (cmsstrcasecmp(fld, cSample) == 0)
-                return i;
-        }
+        if (cmsstrcasecmp(fld, cSample) == 0)
+            return i;
+    }
     }
 
     return -1;
@@ -2606,7 +2606,7 @@
 
     _cmsAssert(hIT8 != NULL);
 
-    snprintf(Buff, 255, it8->DoubleFormatter, Val);
+    sprintf(Buff, it8->DoubleFormatter, Val);
 
     return SetData(it8, row, col, Buff);
 }
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c
index 2ac99be..f6ef06c 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmscnvrt.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2012 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -136,7 +136,7 @@
 };
 
 
-// A pointer to the beginning of the list
+// A pointer to the begining of the list
 _cmsIntentsPluginChunkType _cmsIntentsPluginChunk = { NULL };
 
 // Duplicates the zone of memory used by the plug-in in the new context
@@ -299,7 +299,6 @@
     cmsMAT3 Scale, m1, m2, m3, m4;
 
     // TODO: Follow Marc Mahy's recommendation to check if CHAD is same by using M1*M2 == M2*M1. If so, do nothing.
-    // TODO: Add support for ArgyllArts tag
 
     // Adaptation state
     if (AdaptationState == 1.0) {
@@ -918,7 +917,7 @@
         return TRUE;
     }
 
-    // Make sure to pass through K (which now is fixed)
+    // Make sure to pass thru K (which now is fixed)
     Outf[3] = LabK[3];
 
     // Apply TAC if needed
@@ -986,7 +985,7 @@
     memset(&bp, 0, sizeof(bp));
 
     // We need the input LUT of the last profile, assuming this one is responsible of
-    // black generation. This LUT will be searched in inverse order.
+    // black generation. This LUT will be seached in inverse order.
     bp.LabK2cmyk = _cmsReadInputLUT(hProfiles[nProfiles-1], INTENT_RELATIVE_COLORIMETRIC);
     if (bp.LabK2cmyk == NULL) goto Cleanup;
 
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c
index fc74aa7..a708997 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmserr.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2015 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -227,7 +227,7 @@
     }
 }
 
-// Auxiliary to fill memory management functions from plugin (or context 0 defaults)
+// Auxiliar to fill memory management functions from plugin (or context 0 defaults)
 void _cmsInstallAllocFunctions(cmsPluginMemHandler* Plugin, _cmsMemPluginChunkType* ptr)
 {
     if (Plugin == NULL) {
@@ -459,14 +459,14 @@
 
 // Error logging ******************************************************************
 
-// There is no error handling at all. When a function fails, it returns proper value.
+// There is no error handling at all. When a funtion fails, it returns proper value.
 // For example, all create functions does return NULL on failure. Other return FALSE
 // It may be interesting, for the developer, to know why the function is failing.
 // for that reason, lcms2 does offer a logging function. This function does recive
 // a ENGLISH string with some clues on what is going wrong. You can show this
 // info to the end user, or just create some sort of log.
 // The logging function should NOT terminate the program, as this obviously can leave
-// resources. It is the programmer's responsibility to check each function return code
+// resources. It is the programmer's responsability to check each function return code
 // to make sure it didn't fail.
 
 // Error messages are limited to MAX_ERROR_MESSAGE_LEN
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c
index e940fe2..e68f258 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgamma.c
@@ -596,7 +596,7 @@
     return Val;
 }
 
-// Evaluate a segmented function for a single value. Return -1 if no valid segment found .
+// Evaluate a segmented funtion for a single value. Return -1 if no valid segment found .
 // If fn type is 0, perform an interpolation on the table
 static
 cmsFloat64Number EvalSegmentedFn(const cmsToneCurve *g, cmsFloat64Number R)
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c
index 81254c2..0be9173 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsgmt.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2012 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -56,7 +56,7 @@
 #include "lcms2_internal.h"
 
 
-// Auxiliary: append a Lab identity after the given sequence of profiles
+// Auxiliar: append a Lab identity after the given sequence of profiles
 // and return the transform. Lab profile is closed, rest of profiles are kept open.
 cmsHTRANSFORM _cmsChain2Lab(cmsContext            ContextID,
                             cmsUInt32Number        nProfiles,
@@ -201,7 +201,7 @@
     }
 
     // Build the relationship. This effectively limits the maximum accuracy to 16 bits, but
-    // since this is used on black-preserving LUTs, we are not losing  accuracy in any case
+    // since this is used on black-preserving LUTs, we are not loosing  accuracy in any case
     KTone = cmsJoinToneCurve(ContextID, in, out, nPoints);
 
     // Get rid of components
@@ -307,7 +307,7 @@
 }
 
 // Does compute a gamut LUT going back and forth across pcs -> relativ. colorimetric intent -> pcs
-// the dE obtained is then annotated on the LUT. Values truly out of gamut are clipped to dE = 0xFFFE
+// the dE obtained is then annotated on the LUT. Values truely out of gamut are clipped to dE = 0xFFFE
 // and values changed are supposed to be handled by any gamut remapping, so, are out of gamut as well.
 //
 // **WARNING: This algorithm does assume that gamut remapping algorithms does NOT move in-gamut colors,
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmshalf.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmshalf.c
index ddcaf48..11efe3a 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmshalf.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmshalf.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2012 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c
index aa96cbb..20175ef 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsintrp.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2012 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -185,7 +185,7 @@
     int i;
     cmsUInt32Number Samples[MAX_INPUT_DIMENSIONS];
 
-    // Fill the auxiliary array
+    // Fill the auxiliar array
     for (i=0; i < MAX_INPUT_DIMENSIONS; i++)
         Samples[i] = nSamples;
 
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c
index f86f2e7..3811ef9 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio0.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2012 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -353,7 +353,7 @@
     return nReaded;
 }
 
-// Position file pointer in the file
+// Postion file pointer in the file
 static
 cmsBool  FileSeek(cmsIOHANDLER* iohandler, cmsUInt32Number offset)
 {
@@ -397,7 +397,6 @@
 {
     cmsIOHANDLER* iohandler = NULL;
     FILE* fm = NULL;
-    cmsInt32Number fileLen;
 
     _cmsAssert(FileName != NULL);
     _cmsAssert(AccessMode != NULL);
@@ -414,16 +413,7 @@
              cmsSignalError(ContextID, cmsERROR_FILE, "File '%s' not found", FileName);
             return NULL;
         }
-        fileLen = cmsfilelength(fm);
-        if (fileLen < 0)
-        {
-            fclose(fm);
-            _cmsFree(ContextID, iohandler);
-            cmsSignalError(ContextID, cmsERROR_FILE, "Cannot get size of file '%s'", FileName);
-            return NULL;
-        }
-
-        iohandler -> ReportedSize = (cmsUInt32Number) fileLen;
+        iohandler -> ReportedSize = (cmsUInt32Number) cmsfilelength(fm);
         break;
 
     case 'w':
@@ -463,14 +453,6 @@
 cmsIOHANDLER* CMSEXPORT cmsOpenIOhandlerFromStream(cmsContext ContextID, FILE* Stream)
 {
     cmsIOHANDLER* iohandler = NULL;
-    cmsInt32Number fileSize;
-
-    fileSize = cmsfilelength(Stream);
-    if (fileSize < 0)
-    {
-        cmsSignalError(ContextID, cmsERROR_FILE, "Cannot get size of stream");
-        return NULL;
-    }
 
     iohandler = (cmsIOHANDLER*) _cmsMallocZero(ContextID, sizeof(cmsIOHANDLER));
     if (iohandler == NULL) return NULL;
@@ -478,7 +460,7 @@
     iohandler -> ContextID = ContextID;
     iohandler -> stream = (void*) Stream;
     iohandler -> UsedSpace = 0;
-    iohandler -> ReportedSize = (cmsUInt32Number) fileSize;
+    iohandler -> ReportedSize = (cmsUInt32Number) cmsfilelength(Stream);
     iohandler -> PhysicalFile[0] = 0;
 
     iohandler ->Read    = FileRead;
@@ -670,7 +652,7 @@
 }
 
 
-// Check existence
+// Check existance
 cmsBool CMSEXPORT cmsIsTag(cmsHPROFILE hProfile, cmsTagSignature sig)
 {
        _cmsICCPROFILE*  Icc = (_cmsICCPROFILE*) (void*) hProfile;
@@ -726,7 +708,7 @@
         return FALSE;
     }
 
-    // Adjust endianness of the used parameters
+    // Adjust endianess of the used parameters
     Icc -> DeviceClass     = (cmsProfileClassSignature) _cmsAdjustEndianess32(Header.deviceClass);
     Icc -> ColorSpace      = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.colorSpace);
     Icc -> PCS             = (cmsColorSpaceSignature)   _cmsAdjustEndianess32(Header.pcs);
@@ -844,7 +826,7 @@
 
     memset(&Header.reserved, 0, sizeof(Header.reserved));
 
-    // Set profile ID. Endianness is always big endian
+    // Set profile ID. Endianess is always big endian
     memmove(&Header.profileID, &Icc ->ProfileID, 16);
 
     // Dump the header
@@ -854,7 +836,7 @@
 
     // Get true count
     for (i=0;  i < Icc -> TagCount; i++) {
-        if (Icc ->TagNames[i] != (cmsTagSignature) 0)
+        if (Icc ->TagNames[i] != 0)
             Count++;
     }
 
@@ -863,7 +845,7 @@
 
     for (i=0; i < Icc -> TagCount; i++) {
 
-        if (Icc ->TagNames[i] == (cmsTagSignature) 0) continue;   // It is just a placeholder
+        if (Icc ->TagNames[i] == 0) continue;   // It is just a placeholder
 
         Tag.sig    = (cmsTagSignature) _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagNames[i]);
         Tag.offset = _cmsAdjustEndianess32((cmsInt32Number) Icc -> TagOffsets[i]);
@@ -1213,7 +1195,7 @@
 
     for (i=0; i < Icc -> TagCount; i++) {
 
-        if (Icc ->TagNames[i] == (cmsTagSignature) 0) continue;
+        if (Icc ->TagNames[i] == 0) continue;
 
         // Linked tags are not written
         if (Icc ->TagLinked[i] != (cmsTagSignature) 0) continue;
@@ -1347,15 +1329,11 @@
 
     _cmsAssert(hProfile != NULL);
 
-    if (!_cmsLockMutex(Icc->ContextID, Icc->UsrMutex)) return 0;
     memmove(&Keep, Icc, sizeof(_cmsICCPROFILE));
 
     ContextID = cmsGetProfileContextID(hProfile);
     PrevIO = Icc ->IOhandler = cmsOpenIOhandlerFromNULL(ContextID);
-    if (PrevIO == NULL) {
-        _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
-        return 0;
-    }
+    if (PrevIO == NULL) return 0;
 
     // Pass #1 does compute offsets
 
@@ -1375,10 +1353,7 @@
     }
 
     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
-    if (!cmsCloseIOhandler(PrevIO))
-        UsedSpace = 0; // As a error marker
-
-    _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
+    if (!cmsCloseIOhandler(PrevIO)) return 0;
 
     return UsedSpace;
 
@@ -1386,8 +1361,6 @@
 Error:
     cmsCloseIOhandler(PrevIO);
     memmove(Icc, &Keep, sizeof(_cmsICCPROFILE));
-    _cmsUnlockMutex(Icc->ContextID, Icc->UsrMutex);
-
     return 0;
 }
 
@@ -1598,7 +1571,7 @@
     LocalTypeHandler.ICCVersion = Icc ->Version;
     Icc -> TagPtrs[n] = LocalTypeHandler.ReadPtr(&LocalTypeHandler, io, &ElemCount, TagSize);
 
-    // The tag type is supported, but something wrong happened and we cannot read the tag.
+    // The tag type is supported, but something wrong happend and we cannot read the tag.
     // let know the user about this (although it is just a warning)
     if (Icc -> TagPtrs[n] == NULL) {
 
@@ -1917,7 +1890,7 @@
     _cmsUnlockMutex(Icc->ContextID, Icc ->UsrMutex);
 
     if (Icc->TagPtrs[i] == NULL) {
-           Icc->TagNames[i] = (cmsTagSignature) 0;
+           Icc->TagNames[i] = 0;
            return FALSE;
     }
     return TRUE;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c
index c478b2e..4c259f8 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsio1.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2012 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -157,7 +157,7 @@
 }
 
 
-// Auxiliary, read colorants as a MAT3 structure. Used by any function that needs a matrix-shaper
+// Auxiliar, read colorants as a MAT3 structure. Used by any function that needs a matrix-shaper
 static
 cmsBool ReadICCMatrixRGB2XYZ(cmsMAT3* r, cmsHPROFILE hProfile)
 {
@@ -343,7 +343,7 @@
     cmsTagSignature tagFloat;
     cmsContext ContextID = cmsGetProfileContextID(hProfile);
 
-    // On named color, take the appropriate tag
+    // On named color, take the appropiate tag
     if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
 
         cmsPipeline* Lut;
@@ -365,9 +365,9 @@
         return Lut;
     }
 
-    // This is an attempt to reuse this function to retrieve the matrix-shaper as pipeline no
+    // This is an attempt to reuse this funtion to retrieve the matrix-shaper as pipeline no
     // matter other LUT are present and have precedence. Intent = -1 means just this.
-    if (Intent >= INTENT_PERCEPTUAL && Intent <= INTENT_ABSOLUTE_COLORIMETRIC) {
+    if (Intent != -1) {
 
         tag16 = Device2PCS16[Intent];
         tagFloat = Device2PCSFloat[Intent];
@@ -423,7 +423,7 @@
     // Check if this is a grayscale profile.
     if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
 
-        // if so, build appropriate conversion tables.
+        // if so, build appropiate conversion tables.
         // The tables are the PCS iluminant, scaled across GrayTRC
         return BuildGrayInputMatrixPipeline(hProfile);
     }
@@ -578,7 +578,7 @@
     if (Lut == NULL) return NULL;
 
     // If PCS is Lab or XYZ, the floating point tag is accepting data in the space encoding,
-    // and since the formatter has already accommodated to 0..1.0, we should undo this change
+    // and since the formatter has already accomodated to 0..1.0, we should undo this change
     if ( PCS == cmsSigLabData)
     {
         if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageNormalizeToLabFloat(ContextID)))
@@ -619,7 +619,7 @@
     cmsContext ContextID  = cmsGetProfileContextID(hProfile);
 
 
-    if (Intent >= INTENT_PERCEPTUAL && Intent <= INTENT_ABSOLUTE_COLORIMETRIC) {
+    if (Intent != -1) {
 
         tag16 = PCS2Device16[Intent];
         tagFloat = PCS2DeviceFloat[Intent];
@@ -680,7 +680,7 @@
     // Check if this is a grayscale profile.
     if (cmsGetColorSpace(hProfile) == cmsSigGrayData) {
 
-        // if so, build appropriate conversion tables.
+        // if so, build appropiate conversion tables.
         // The tables are the PCS iluminant, scaled across GrayTRC
         return BuildGrayOutputPipeline(hProfile);
     }
@@ -738,21 +738,15 @@
 {
     cmsPipeline* Lut;
     cmsTagTypeSignature OriginalType;
-    cmsTagSignature tag16;
-    cmsTagSignature tagFloat;
+    cmsTagSignature tag16    = Device2PCS16[Intent];
+    cmsTagSignature tagFloat = Device2PCSFloat[Intent];
     cmsContext ContextID = cmsGetProfileContextID(hProfile);
 
 
-    if (Intent < INTENT_PERCEPTUAL || Intent > INTENT_ABSOLUTE_COLORIMETRIC)
-        return NULL;
-
-    tag16 = Device2PCS16[Intent];
-    tagFloat = Device2PCSFloat[Intent];
-
-    // On named color, take the appropriate tag
+    // On named color, take the appropiate tag
     if (cmsGetDeviceClass(hProfile) == cmsSigNamedColorClass) {
 
-        cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*)cmsReadTag(hProfile, cmsSigNamedColor2Tag);
+        cmsNAMEDCOLORLIST* nc = (cmsNAMEDCOLORLIST*) cmsReadTag(hProfile, cmsSigNamedColor2Tag);
 
         if (nc == NULL) return NULL;
 
@@ -768,13 +762,12 @@
                 goto Error;
 
         return Lut;
-    Error:
+Error:
         cmsPipelineFree(Lut);
         cmsFreeNamedColorList(nc);
         return NULL;
     }
 
-
     if (cmsIsTag(hProfile, tagFloat)) {  // Float tag takes precedence
 
         // Floating point LUT are always V
@@ -784,19 +777,19 @@
     tagFloat = Device2PCSFloat[0];
     if (cmsIsTag(hProfile, tagFloat)) {
 
-        return cmsPipelineDup((cmsPipeline*)cmsReadTag(hProfile, tagFloat));
+        return cmsPipelineDup((cmsPipeline*) cmsReadTag(hProfile, tagFloat));
     }
 
     if (!cmsIsTag(hProfile, tag16)) {  // Is there any LUT-Based table?
 
-        tag16 = Device2PCS16[0];
+        tag16    = Device2PCS16[0];
         if (!cmsIsTag(hProfile, tag16)) return NULL;
     }
 
     // Check profile version and LUT type. Do the necessary adjustments if needed
 
     // Read the tag
-    Lut = (cmsPipeline*)cmsReadTag(hProfile, tag16);
+    Lut = (cmsPipeline*) cmsReadTag(hProfile, tag16);
     if (Lut == NULL) return NULL;
 
     // The profile owns the Lut, so we need to copy it
@@ -809,7 +802,7 @@
         ChangeInterpolationToTrilinear(Lut);
 
     // After reading it, we have info about the original type
-    OriginalType = _cmsGetTagTrueType(hProfile, tag16);
+    OriginalType =  _cmsGetTagTrueType(hProfile, tag16);
 
     // We need to adjust data for Lab16 on output
     if (OriginalType != cmsSigLut16Type) return Lut;
@@ -817,12 +810,12 @@
     // Here it is possible to get Lab on both sides
 
     if (cmsGetColorSpace(hProfile) == cmsSigLabData) {
-        if (!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
+        if(!cmsPipelineInsertStage(Lut, cmsAT_BEGIN, _cmsStageAllocLabV4ToV2(ContextID)))
             goto Error2;
     }
 
     if (cmsGetPCS(hProfile) == cmsSigLabData) {
-        if (!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
+        if(!cmsPipelineInsertStage(Lut, cmsAT_END, _cmsStageAllocLabV2ToV4(ContextID)))
             goto Error2;
     }
 
@@ -957,7 +950,7 @@
 }
 
 
-// Auxiliary, read and duplicate a MLU if found.
+// Auxiliar, read and duplicate a MLU if found.
 static
 cmsMLU* GetMLUFromProfile(cmsHPROFILE h, cmsTagSignature sig)
 {
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c
index 6c4b8ce..4c04ee9 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmslut.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2012 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -534,7 +534,7 @@
                 goto Error;
         } else {
             NewElem ->Tab.T = (cmsUInt16Number*) _cmsDupMem(mpe ->ContextID, Data ->Tab.T, Data ->nEntries * sizeof (cmsUInt16Number));
-            if (NewElem ->Tab.T == NULL)
+            if (NewElem ->Tab.TFloat == NULL)
                 goto Error;
         }
     }
@@ -1482,8 +1482,7 @@
                  First = FALSE;
              }
              else {
-                if (Anterior != NULL)
-                    Anterior ->Next = NewMPE;
+                Anterior ->Next = NewMPE;
              }
 
             Anterior = NewMPE;
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c
index 619c94e..c238e41 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmd5.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2012 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmtrx.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmtrx.c
index 2bc6a49..ed9366c 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmtrx.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsmtrx.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2012 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -67,7 +67,7 @@
     r -> n[VZ] = z;
 }
 
-// Vector subtraction
+// Vector substraction
 void CMSEXPORT _cmsVEC3minus(cmsVEC3* r, const cmsVEC3* a, const cmsVEC3* b)
 {
   r -> n[VX] = a -> n[VX] - b -> n[VX];
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c
index 870936f..fd4e565 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsnamed.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2012 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -121,7 +121,7 @@
 static
 cmsBool GrowMLUtable(cmsMLU* mlu)
 {
-    cmsUInt32Number AllocatedEntries;
+    int AllocatedEntries;
     _cmsMLUentry *NewPtr;
 
     // Sanity check
@@ -147,7 +147,7 @@
 static
 int SearchMLUEntry(cmsMLU* mlu, cmsUInt16Number LanguageCode, cmsUInt16Number CountryCode)
 {
-    cmsUInt32Number i;
+    int i;
 
     // Sanity check
     if (mlu == NULL) return -1;
@@ -207,42 +207,15 @@
     return TRUE;
 }
 
-// Convert from a 3-char code to a cmsUInt16Number. It is done inthis way because some
-// compilers don't properly align beginning of strings
 
-static
-cmsUInt16Number strTo16(const char str[3])
-{
-    cmsUInt16Number n = ((cmsUInt16Number) str[0] << 8) | str[1];
-
-    return n;  // Always big endian in this case
-}
-
-static
-void strFrom16(char str[3], cmsUInt16Number n)
-{
-    // Assiming this would be aligned
-    union {
-
-       cmsUInt16Number n;
-       char str[2];
-
-    } c;
-
-    c.n = n;  // Always big endian in this case
-
-    str[0] = c.str[0]; str[1] = c.str[1]; str[2] = 0;
-
-}
-
-// Add an ASCII entry. Do not add any \0 termination (ICC1v43_2010-12.pdf page 61)
+// Add an ASCII entry.
 cmsBool CMSEXPORT cmsMLUsetASCII(cmsMLU* mlu, const char LanguageCode[3], const char CountryCode[3], const char* ASCIIString)
 {
-    cmsUInt32Number i, len = (cmsUInt32Number) strlen(ASCIIString);
+    cmsUInt32Number i, len = (cmsUInt32Number) strlen(ASCIIString)+1;
     wchar_t* WStr;
     cmsBool  rc;
-    cmsUInt16Number Lang  = strTo16(LanguageCode);
-    cmsUInt16Number Cntry = strTo16(CountryCode);
+    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
+    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);
 
     if (mlu == NULL) return FALSE;
 
@@ -272,17 +245,18 @@
     return (cmsUInt32Number)(p - s);
 }
 
-// Add a wide entry. Do not add any \0 terminator (ICC1v43_2010-12.pdf page 61)
+
+// Add a wide entry
 cmsBool  CMSEXPORT cmsMLUsetWide(cmsMLU* mlu, const char Language[3], const char Country[3], const wchar_t* WideString)
 {
-    cmsUInt16Number Lang  = strTo16(Language);
-    cmsUInt16Number Cntry = strTo16(Country);
+    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) Language);
+    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) Country);
     cmsUInt32Number len;
 
     if (mlu == NULL) return FALSE;
     if (WideString == NULL) return FALSE;
 
-    len = (cmsUInt32Number) (mywcslen(WideString)) * sizeof(wchar_t);
+    len = (cmsUInt32Number) (mywcslen(WideString) + 1) * sizeof(wchar_t);
     return AddMLUBlock(mlu, len, WideString, Lang, Cntry);
 }
 
@@ -353,8 +327,8 @@
                               cmsUInt16Number LanguageCode, cmsUInt16Number CountryCode,
                               cmsUInt16Number* UsedLanguageCode, cmsUInt16Number* UsedCountryCode)
 {
-    cmsUInt32Number i;
-    cmsInt32Number Best = -1;
+    int i;
+    int Best = -1;
     _cmsMLUentry* v;
 
     if (mlu == NULL) return NULL;
@@ -405,8 +379,8 @@
     cmsUInt32Number  StrLen = 0;
     cmsUInt32Number ASCIIlen, i;
 
-    cmsUInt16Number Lang  = strTo16(LanguageCode);
-    cmsUInt16Number Cntry = strTo16(CountryCode);
+    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
+    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);
 
     // Sanitize
     if (mlu == NULL) return 0;
@@ -449,8 +423,8 @@
     const wchar_t *Wide;
     cmsUInt32Number  StrLen = 0;
 
-    cmsUInt16Number Lang  = strTo16(LanguageCode);
-    cmsUInt16Number Cntry = strTo16(CountryCode);
+    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
+    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);
 
     // Sanitize
     if (mlu == NULL) return 0;
@@ -482,8 +456,8 @@
 {
     const wchar_t *Wide;
 
-    cmsUInt16Number Lang  = strTo16(LanguageCode);
-    cmsUInt16Number Cntry = strTo16(CountryCode);
+    cmsUInt16Number Lang  = _cmsAdjustEndianess16(*(cmsUInt16Number*) LanguageCode);
+    cmsUInt16Number Cntry = _cmsAdjustEndianess16(*(cmsUInt16Number*) CountryCode);
     cmsUInt16Number ObtLang, ObtCode;
 
     // Sanitize
@@ -493,9 +467,10 @@
     if (Wide == NULL) return FALSE;
 
     // Get used language and code
-    strFrom16(ObtainedLanguage, ObtLang);
-    strFrom16(ObtainedCountry, ObtCode);
+    *(cmsUInt16Number *)ObtainedLanguage = _cmsAdjustEndianess16(ObtLang);
+    *(cmsUInt16Number *)ObtainedCountry  = _cmsAdjustEndianess16(ObtCode);
 
+    ObtainedLanguage[2] = ObtainedCountry[2] = 0;
     return TRUE;
 }
 
@@ -518,12 +493,12 @@
 
     if (mlu == NULL) return FALSE;
 
-    if (idx >= mlu->UsedEntries) return FALSE;
+    if (idx >= (cmsUInt32Number) mlu->UsedEntries) return FALSE;
 
     entry = &mlu->Entries[idx];
 
-    strFrom16(LanguageCode, entry->Language);
-    strFrom16(CountryCode, entry->Country);
+    *(cmsUInt16Number *)LanguageCode = _cmsAdjustEndianess16(entry->Language);
+    *(cmsUInt16Number *)CountryCode  = _cmsAdjustEndianess16(entry->Country);
 
     return TRUE;
 }
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
index d40993b..0383b66 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsopt.c
@@ -27,10 +27,11 @@
 // However, the following notice accompanied the original version of this
 // file:
 //
+
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2011 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -257,10 +258,11 @@
 
                             // We can not get rid of full matrix
                             cmsStage* Multmat = cmsStageAllocMatrix(Lut->ContextID, 3, 3, (const cmsFloat64Number*) &res, NULL);
-                            if (Multmat == NULL) return FALSE;  // Should never happen
 
                             // Recover the chain
+                            if (Multmat != NULL) {
                             Multmat->Next = chain;
+                            }
                             *pt1 = Multmat;
                      }
 
@@ -558,7 +560,7 @@
             return TRUE;
 }
 
-// Auxiliary, to see if two values are equal or very different
+// Auxiliar, to see if two values are equal or very different
 static
 cmsBool WhitesAreEqual(int n, cmsUInt16Number White1[], cmsUInt16Number White2[] )
 {
@@ -566,7 +568,7 @@
 
     for (i=0; i < n; i++) {
 
-        if (abs(White1[i] - White2[i]) > 0xf000) return TRUE;  // Values are so extremely different that the fixup should be avoided
+        if (abs(White1[i] - White2[i]) > 0xf000) return TRUE;  // Values are so extremly different that the fixup should be avoided
         if (White1[i] != White2[i]) return FALSE;
     }
     return TRUE;
@@ -704,7 +706,7 @@
         cmsStage* PreLin = cmsPipelineGetPtrToFirstStage(Src);
 
         // Check if suitable
-        if (PreLin && PreLin ->Type == cmsSigCurveSetElemType) {
+        if (PreLin ->Type == cmsSigCurveSetElemType) {
 
             // Maybe this is a linear tram, so we can avoid the whole stuff
             if (!AllCurvesAreLinear(PreLin)) {
@@ -737,7 +739,7 @@
         cmsStage* PostLin = cmsPipelineGetPtrToLastStage(Src);
 
         // Check if suitable
-        if (PostLin && cmsStageType(PostLin) == cmsSigCurveSetElemType) {
+        if (cmsStageType(PostLin) == cmsSigCurveSetElemType) {
 
             // Maybe this is a linear tram, so we can avoid the whole stuff
             if (!AllCurvesAreLinear(PostLin)) {
@@ -1039,8 +1041,8 @@
     }
 
     if (Zeros == 1 && Poles == 1) return FALSE;  // For linear tables
-    if (Zeros > (nEntries / 20)) return TRUE;  // Degenerated, many zeros
-    if (Poles > (nEntries / 20)) return TRUE;  // Degenerated, many poles
+    if (Zeros > (nEntries / 4)) return TRUE;  // Degenerated, mostly zeros
+    if (Poles > (nEntries / 4)) return TRUE;  // Degenerated, mostly poles
 
     return FALSE;
 }
@@ -1062,19 +1064,17 @@
     cmsColorSpaceSignature ColorSpace, OutputColorSpace;
     cmsStage* OptimizedPrelinMpe;
     cmsStage* mpe;
-    cmsToneCurve** OptimizedPrelinCurves;
-    _cmsStageCLutData* OptimizedPrelinCLUT;
+    cmsToneCurve**   OptimizedPrelinCurves;
+    _cmsStageCLutData*     OptimizedPrelinCLUT;
 
 
     // This is a loosy optimization! does not apply in floating-point cases
     if (_cmsFormatterIsFloat(*InputFormat) || _cmsFormatterIsFloat(*OutputFormat)) return FALSE;
 
-    // Only on chunky RGB
+    // Only on RGB
     if (T_COLORSPACE(*InputFormat)  != PT_RGB) return FALSE;
-    if (T_PLANAR(*InputFormat)) return FALSE;
-
     if (T_COLORSPACE(*OutputFormat) != PT_RGB) return FALSE;
-    if (T_PLANAR(*OutputFormat)) return FALSE;
+
 
     // On 16 bits, user has to specify the feature
     if (!_cmsFormatterIs8bit(*InputFormat)) {
@@ -1098,22 +1098,6 @@
     memset(Trans, 0, sizeof(Trans));
     memset(TransReverse, 0, sizeof(TransReverse));
 
-    // If the last stage of the original lut are curves, and those curves are
-    // degenerated, it is likely the transform is squeezing and clipping
-    // the output from previous CLUT. We cannot optimize this case
-    {
-        cmsStage* last = cmsPipelineGetPtrToLastStage(OriginalLut);
-
-        if (cmsStageType(last) == cmsSigCurveSetElemType) {
-
-            _cmsStageToneCurvesData* Data = (_cmsStageToneCurvesData*)cmsStageData(last);
-            for (i = 0; i < Data->nCurves; i++) {
-                if (IsDegenerated(Data->TheCurves[i]))
-                    goto Error;
-            }
-        }
-    }
-
     for (t = 0; t < OriginalLut ->InputChannels; t++) {
         Trans[t] = cmsBuildTabulatedToneCurve16(OriginalLut ->ContextID, PRELINEARIZATION_POINTS, NULL);
         if (Trans[t] == NULL) goto Error;
@@ -1447,10 +1431,7 @@
         GammaTables[i] = NULL;
     }
 
-    if (GammaTables != NULL) {
-        _cmsFree(Src->ContextID, GammaTables);
-        GammaTables = NULL;
-    }
+    if (GammaTables != NULL) _cmsFree(Src ->ContextID, GammaTables);
 
     // Maybe the curves are linear at the end
     if (!AllCurvesAreLinear(ObtainedCurves)) {
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c
index a9087f6..e389c4e 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspack.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -110,7 +110,7 @@
 #define ANYFLAVOR       FLAVOR_SH(1)
 
 
-// Suppress waning about info never being used
+// Supress waning about info never being used
 
 #ifdef _MSC_VER
 #pragma warning(disable : 4100)
@@ -3188,8 +3188,6 @@
     cmsUInt32Number i;
     cmsFormatter fr;
 
-    // Optimization is only a hint
-    dwInput &= ~OPTIMIZED_SH(1);
 
     switch (dwFlags)
     {
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c
index f2ebf53..d4ef694 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmspcs.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -337,7 +337,7 @@
     wLab[2] = ab2Fix4(Lab.b);
 }
 
-// Auxiliary: convert to Radians
+// Auxiliar: convert to Radians
 static
 cmsFloat64Number RADIANS(cmsFloat64Number deg)
 {
@@ -345,7 +345,7 @@
 }
 
 
-// Auxiliary: atan2 but operating in degrees and returning 0 if a==b==0
+// Auxiliar: atan2 but operating in degrees and returning 0 if a==b==0
 static
 cmsFloat64Number atan2deg(cmsFloat64Number a, cmsFloat64Number b)
 {
@@ -368,7 +368,7 @@
 }
 
 
-// Auxiliary: Square
+// Auxiliar: Square
 static
 cmsFloat64Number Sqr(cmsFloat64Number v)
 {
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c
index 683c830..4443820 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsplugin.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2010 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -136,7 +136,7 @@
 #endif
 }
 
-// Auxiliary -- read 8, 16 and 32-bit numbers
+// Auxiliar -- read 8, 16 and 32-bit numbers
 cmsBool CMSEXPORT  _cmsReadUInt8Number(cmsIOHANDLER* io, cmsUInt8Number* n)
 {
     cmsUInt8Number tmp;
@@ -201,13 +201,13 @@
 
     _cmsAssert(io != NULL);
 
-    if (io -> Read(io, &tmp, sizeof(cmsUInt32Number), 1) != 1)
+    if (io -> Read(io, &tmp, sizeof(cmsFloat32Number), 1) != 1)
             return FALSE;
 
     if (n != NULL) {
 
         tmp = _cmsAdjustEndianess32(tmp);
-        *n = *(cmsFloat32Number*) (void*) &tmp;
+        *n = *(cmsFloat32Number*) &tmp;
     }
     return TRUE;
 }
@@ -244,6 +244,22 @@
 }
 
 
+// Jun-21-2000: Some profiles (those that comes with W2K) comes
+// with the media white (media black?) x 100. Add a sanity check
+
+static
+void NormalizeXYZ(cmsCIEXYZ* Dest)
+{
+    while (Dest -> X > 2. &&
+           Dest -> Y > 2. &&
+           Dest -> Z > 2.) {
+
+               Dest -> X /= 10.;
+               Dest -> Y /= 10.;
+               Dest -> Z /= 10.;
+       }
+}
+
 cmsBool CMSEXPORT  _cmsReadXYZNumber(cmsIOHANDLER* io, cmsCIEXYZ* XYZ)
 {
     cmsEncodedXYZNumber xyz;
@@ -257,6 +273,8 @@
         XYZ->X = _cms15Fixed16toDouble(_cmsAdjustEndianess32(xyz.X));
         XYZ->Y = _cms15Fixed16toDouble(_cmsAdjustEndianess32(xyz.Y));
         XYZ->Z = _cms15Fixed16toDouble(_cmsAdjustEndianess32(xyz.Z));
+
+        NormalizeXYZ(XYZ);
     }
     return TRUE;
 }
@@ -318,7 +336,7 @@
 
     _cmsAssert(io != NULL);
 
-    tmp = *(cmsUInt32Number*) (void*) &n;
+    tmp = *(cmsUInt32Number*) &n;
     tmp = _cmsAdjustEndianess32(tmp);
     if (io -> Write(io, sizeof(cmsUInt32Number), &tmp) != 1)
             return FALSE;
@@ -514,10 +532,7 @@
     va_start(args, frm);
 
     len = vsnprintf((char*) Buffer, 2047, frm, args);
-    if (len < 0) {
-        va_end(args);
-        return FALSE;   // Truncated, which is a fatal error for us
-    }
+    if (len < 0) return FALSE;   // Truncated, which is a fatal error for us
 
     rc = io ->Write(io, len, Buffer);
 
@@ -539,7 +554,6 @@
         if (ContextID == NULL) {
 
             ctx->MemPool = _cmsCreateSubAlloc(0, 2*1024);
-            if (ctx->MemPool == NULL) return NULL;
         }
         else {
             cmsSignalError(ContextID, cmsERROR_CORRUPTION_DETECTED, "NULL memory pool on context");
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c
index 03d476b..22089d0 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsps2.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2011 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -608,7 +608,7 @@
 //
 //  Each row contains Pipeline values for all but first component. So, I
 //  detect row changing by keeping a copy of last value of first
-//  component. -1 is used to mark beginning of whole block.
+//  component. -1 is used to mark begining of whole block.
 
 static
 int OutputValueSampler(register const cmsUInt16Number In[], register cmsUInt16Number Out[], register void* Cargo)
@@ -1422,15 +1422,14 @@
     if (nColorant > cmsMAXCHANNELS)
         nColorant = cmsMAXCHANNELS;
 
-    for (j = 0; j < nColorant; j++) {
+    for (j=0; j < nColorant; j++) {
 
-        snprintf(Buff, 31, "%.3f", Out[j] / 65535.0);
-        Buff[31] = 0;
-        strcat(Colorant, Buff);
-        if (j < nColorant - 1)
-            strcat(Colorant, " ");
+                sprintf(Buff, "%.3f", Out[j] / 65535.0);
+                strcat(Colorant, Buff);
+                if (j < nColorant -1)
+                        strcat(Colorant, " ");
 
-    }
+        }
 }
 
 
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c
index b22c427..bcd9d50 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmssamp.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2014 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmssm.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmssm.c
index 1923a02..783f3c3 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmssm.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmssm.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2011 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -247,8 +247,7 @@
 {
     cmsFloat64Number a, b, c, d, e, D;
     cmsFloat64Number sc, sN, sD;
-    //cmsFloat64Number tc; // left for future use
-    cmsFloat64Number tN, tD;
+    cmsFloat64Number tc, tN, tD;
     cmsVEC3 w0;
 
     _cmsVEC3minus(&w0, &line1 ->a, &line2 ->a);
@@ -316,7 +315,7 @@
     }
     // finally do the division to get sc and tc
     sc = (fabs(sN) < MATRIX_DET_TOLERANCE ? 0.0 : sN / sD);
-    //tc = (fabs(tN) < MATRIX_DET_TOLERANCE ? 0.0 : tN / tD); // left for future use.
+    tc = (fabs(tN) < MATRIX_DET_TOLERANCE ? 0.0 : tN / tD);
 
     GetPointOfLine(r, line1, sc);
     return TRUE;
@@ -347,7 +346,7 @@
 }
 
 
-// Auxiliary to retrieve a pointer to the segmentr containing the Lab value
+// Auxiliar to retrieve a pointer to the segmentr containing the Lab value
 static
 cmsGDBPoint* GetPoint(cmsGDB* gbd, const cmsCIELab* Lab, cmsSpherical* sp)
 {
@@ -359,7 +358,7 @@
     _cmsAssert(Lab != NULL);
     _cmsAssert(sp != NULL);
 
-    // Center L* by subtracting half of its domain, that's 50
+    // Center L* by substracting half of its domain, that's 50
     _cmsVEC3init(&v, Lab ->L - 50.0, Lab ->a, Lab ->b);
 
     // Convert to spherical coordinates
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmstypes.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmstypes.c
index 3f8999f..1e119b4 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmstypes.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmstypes.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2014 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -59,7 +59,7 @@
 // This file implements every single tag and tag type as described in the ICC spec. Some types
 // have been deprecated, like ncl and Data. There is no implementation for those types as there
 // are no profiles holding them. The programmer can also extend this list by defining his own types
-// by using the appropriate plug-in. There are three types of plug ins regarding that. First type
+// by using the appropiate plug-in. There are three types of plug ins regarding that. First type
 // allows to define new tags using any existing type. Next plug-in type allows to define new types
 // and the third one is very specific: allows to extend the number of elements in the multiprocessing
 // elements special type.
@@ -142,7 +142,7 @@
 }
 
 
-// Auxiliary to convert UTF-32 to UTF-16 in some cases
+// Auxiliar to convert UTF-32 to UTF-16 in some cases
 static
 cmsBool _cmsWriteWCharArray(cmsIOHANDLER* io, cmsUInt32Number n, const wchar_t* Array)
 {
@@ -158,7 +158,7 @@
     return TRUE;
 }
 
-// Auxiliary to read an array of wchar_t
+// Auxiliar to read an array of wchar_t
 static
 cmsBool _cmsReadWCharArray(cmsIOHANDLER* io, cmsUInt32Number n, wchar_t* Array)
 {
@@ -189,7 +189,7 @@
                                              cmsUInt32Number n,
                                              cmsUInt32Number SizeOfTag);
 
-// Helper function to deal with position tables as described in ICC spec 4.3
+// Helper function to deal with position tables as decribed in ICC spec 4.3
 // A table of n elements is readed, where first comes n records containing offsets and sizes and
 // then a block containing the data itself. This allows to reuse same data in more than one entry
 static
@@ -980,7 +980,7 @@
     cmsMLU* mlu = (cmsMLU*) Ptr;
     char *Text = NULL;
     wchar_t *Wide = NULL;
-    cmsUInt32Number len, len_text, len_tag_requirement, len_aligned;
+    cmsUInt32Number len, len_aligned, len_filler_alignment;
     cmsBool  rc = FALSE;
     char Filler[68];
 
@@ -990,18 +990,17 @@
     // Get the len of string
     len = cmsMLUgetASCII(mlu, cmsNoLanguage, cmsNoCountry, NULL, 0);
 
-    // Specification ICC.1:2001-04 (v2.4.0): It has been found that textDescriptionType can contain misaligned data
+    // From ICC3.4: It has been found that textDescriptionType can contain misaligned data
     //(see clause 4.1 for the definition of “aligned”). Because the Unicode language
     // code and Unicode count immediately follow the ASCII description, their
     // alignment is not correct if the ASCII count is not a multiple of four. The
     // ScriptCode code is misaligned when the ASCII count is odd. Profile reading and
     // writing software must be written carefully in order to handle these alignment
     // problems.
-    //
-    // The above last sentence suggest to handle alignment issues in the
-    // parser. The provided example (Table 69 on Page 60) makes this clear.
-    // The padding only in the ASCII count is not sufficient for a aligned tag
-    // size, with the same text size in ASCII and Unicode.
+
+    // Compute an aligned size
+    len_aligned = _cmsALIGNLONG(len);
+    len_filler_alignment = len_aligned - len;
 
     // Null strings
     if (len <= 0) {
@@ -1022,12 +1021,6 @@
         cmsMLUgetWide(mlu,  cmsNoLanguage, cmsNoCountry,  Wide, len * sizeof(wchar_t));
     }
 
-    // Tell the real text len including the null terminator and padding
-    len_text = (cmsUInt32Number) strlen(Text) + 1;
-    // Compute an total tag size requirement
-    len_tag_requirement = (8+4+len_text+4+4+2*len_text+2+1+67);
-    len_aligned = _cmsALIGNLONG(len_tag_requirement);
-
   // * cmsUInt32Number       count;          * Description length
   // * cmsInt8Number         desc[count]     * NULL terminated ascii string
   // * cmsUInt32Number       ucLangCode;     * UniCode language code
@@ -1037,14 +1030,20 @@
   // * cmsUInt8Number        scCount;        * ScriptCode count
   // * cmsInt8Number         scDesc[67];     * ScriptCode Description
 
-    if (!_cmsWriteUInt32Number(io, len_text)) goto Error;
-    if (!io ->Write(io, len_text, Text)) goto Error;
+    if (!_cmsWriteUInt32Number(io, len_aligned)) goto Error;
+    if (!io ->Write(io, len, Text)) goto Error;
+    if (!io ->Write(io, len_filler_alignment, Filler)) goto Error;
 
     if (!_cmsWriteUInt32Number(io, 0)) goto Error;  // ucLanguageCode
 
-    if (!_cmsWriteUInt32Number(io, len_text)) goto Error;
+    // This part is tricky: we need an aligned tag size, and the ScriptCode part
+    // takes 70 bytes, so we need 2 extra bytes to do the alignment
+
+    if (!_cmsWriteUInt32Number(io, len_aligned+1)) goto Error;
+
     // Note that in some compilers sizeof(cmsUInt16Number) != sizeof(wchar_t)
-    if (!_cmsWriteWCharArray(io, len_text, Wide)) goto Error;
+    if (!_cmsWriteWCharArray(io, len, Wide)) goto Error;
+    if (!_cmsWriteUInt16Array(io, len_filler_alignment+1, (cmsUInt16Number*) Filler)) goto Error;
 
     // ScriptCode Code & count (unused)
     if (!_cmsWriteUInt16Number(io, 0)) goto Error;
@@ -1052,10 +1051,6 @@
 
     if (!io ->Write(io, 67, Filler)) goto Error;
 
-    // possibly add pad at the end of tag
-    if(len_aligned - len_tag_requirement > 0)
-      if (!io ->Write(io, len_aligned - len_tag_requirement, Filler)) goto Error;
-
     rc = TRUE;
 
 Error:
@@ -1503,7 +1498,7 @@
             LargestPosition = EndOfThisString;
     }
 
-    // Now read the remaining of tag and fill all strings. Subtract the directory
+    // Now read the remaining of tag and fill all strings. Substract the directory
     SizeOfTag   = (LargestPosition * sizeof(wchar_t)) / sizeof(cmsUInt16Number);
     if (SizeOfTag == 0)
     {
@@ -1537,7 +1532,7 @@
     cmsMLU* mlu =(cmsMLU*) Ptr;
     cmsUInt32Number HeaderSize;
     cmsUInt32Number  Len, Offset;
-    cmsUInt32Number i;
+    int i;
 
     if (Ptr == NULL) {
 
@@ -3138,8 +3133,6 @@
 
         memset(Colorant, 0, sizeof(Colorant));
         if (io -> Read(io, Root, 32, 1) != 1) return NULL;
-        Root[32] = 0;  // To prevent exploits
-
         if (!_cmsReadUInt16Array(io, 3, PCS)) goto Error;
         if (!_cmsReadUInt16Array(io, nDeviceCoords, Colorant)) goto Error;
 
@@ -3162,8 +3155,8 @@
 cmsBool Type_NamedColor_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
 {
     cmsNAMEDCOLORLIST* NamedColorList = (cmsNAMEDCOLORLIST*) Ptr;
-    char                prefix[33];     // Prefix for each color name
-    char                suffix[33];     // Suffix for each color name
+    char                prefix[32];     // Prefix for each color name
+    char                suffix[32];     // Suffix for each color name
     int i, nColors;
 
     nColors = cmsNamedColorCount(NamedColorList);
@@ -3175,7 +3168,7 @@
     strncpy(prefix, (const char*) NamedColorList->Prefix, 32);
     strncpy(suffix, (const char*) NamedColorList->Suffix, 32);
 
-    suffix[32] = prefix[32] = 0;
+    suffix[31] = prefix[31] = 0;
 
     if (!io ->Write(io, 32, prefix)) return FALSE;
     if (!io ->Write(io, 32, suffix)) return FALSE;
@@ -3187,7 +3180,6 @@
        char Root[33];
 
         if (!cmsNamedColorInfo(NamedColorList, i, Root, NULL, NULL, PCS, Colorant)) return 0;
-        Root[32] = 0;
         if (!io ->Write(io, 32 , Root)) return FALSE;
         if (!_cmsWriteUInt16Array(io, 3, PCS)) return FALSE;
         if (!_cmsWriteUInt16Array(io, NamedColorList ->ColorantCount, Colorant)) return FALSE;
@@ -3638,7 +3630,7 @@
 
 
 
-// Auxiliary, read an string specified as count + string
+// Auxiliar, read an string specified as count + string
 static
 cmsBool  ReadCountAndSting(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, cmsMLU* mlu, cmsUInt32Number* SizeOfTag, const char* Section)
 {
@@ -3887,7 +3879,7 @@
 static
 void* Type_ViewingConditions_Dup(struct _cms_typehandler_struct* self, const void *Ptr, cmsUInt32Number n)
 {
-   return _cmsDupMem(self->ContextID, Ptr, sizeof(cmsICCViewingConditions));
+   return _cmsDupMem(self ->ContextID, Ptr, sizeof(cmsScreening));
 
    cmsUNUSED_PARAMETER(n);
 }
@@ -4344,13 +4336,13 @@
 static
 cmsBool  Type_MPEclut_Write(struct _cms_typehandler_struct* self, cmsIOHANDLER* io, void* Ptr, cmsUInt32Number nItems)
 {
-    cmsUInt8Number Dimensions8[16];  // 16 because the spec says 16 and not max number of channels
+    cmsUInt8Number Dimensions8[16];
     cmsUInt32Number i;
     cmsStage* mpe = (cmsStage*) Ptr;
     _cmsStageCLutData* clut = (_cmsStageCLutData*) mpe ->Data;
 
-    // Check for maximum number of channels supported by lcms
-    if (mpe -> InputChannels > MAX_INPUT_DIMENSIONS) return FALSE;
+    // Check for maximum number of channels
+    if (mpe -> InputChannels > 15) return FALSE;
 
     // Only floats are supported in MPE
     if (clut ->HasFloatValues == FALSE) return FALSE;
@@ -5488,9 +5480,8 @@
     { cmsSigScreeningTag,           { 1, 1, { cmsSigScreeningType},          NULL }, &SupportedTags[59]},
     { cmsSigVcgtTag,                { 1, 1, { cmsSigVcgtType},               NULL }, &SupportedTags[60]},
     { cmsSigMetaTag,                { 1, 1, { cmsSigDictType},               NULL }, &SupportedTags[61]},
-    { cmsSigProfileSequenceIdTag,   { 1, 1, { cmsSigProfileSequenceIdType},  NULL }, &SupportedTags[62]},
-    { cmsSigProfileDescriptionMLTag,{ 1, 1, { cmsSigMultiLocalizedUnicodeType}, NULL}, &SupportedTags[63]},
-    { cmsSigArgyllArtsTag,          { 9, 1, { cmsSigS15Fixed16ArrayType},    NULL}, NULL}
+    { cmsSigProfileSequenceIdTag,   { 1, 1, { cmsSigProfileSequenceIdType},  NULL },  &SupportedTags[62]},
+    { cmsSigProfileDescriptionMLTag,{ 1, 1, { cmsSigMultiLocalizedUnicodeType}, NULL}, NULL}
 
 
 };
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c
index 8d353b3..6c84f13 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsvirt.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2014 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -1167,20 +1167,15 @@
     // If no way, then force CLUT that for sure can be written
     if (AllowedLUT == NULL) {
 
-        cmsStage* FirstStage;
-        cmsStage* LastStage;
-
         dwFlags |= cmsFLAGS_FORCE_CLUT;
         _cmsOptimizePipeline(ContextID, &LUT, xform ->RenderingIntent, &FrmIn, &FrmOut, &dwFlags);
 
         // Put identity curves if needed
-        FirstStage = cmsPipelineGetPtrToFirstStage(LUT);
-        if (FirstStage != NULL && FirstStage ->Type != cmsSigCurveSetElemType)
+        if (cmsPipelineGetPtrToFirstStage(LUT) ->Type != cmsSigCurveSetElemType)
              if (!cmsPipelineInsertStage(LUT, cmsAT_BEGIN, _cmsStageAllocIdentityCurves(ContextID, ChansIn)))
                  goto Error;
 
-        LastStage = cmsPipelineGetPtrToLastStage(LUT);
-        if (LastStage != NULL && LastStage ->Type != cmsSigCurveSetElemType)
+        if (cmsPipelineGetPtrToLastStage(LUT) ->Type != cmsSigCurveSetElemType)
              if (!cmsPipelineInsertStage(LUT, cmsAT_END,   _cmsStageAllocIdentityCurves(ContextID, ChansOut)))
                  goto Error;
 
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c
index d23b29f..1eb9a87 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmswtpnt.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2014 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c
index dfedd7f..c0a0693 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/cmsxform.c
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2014 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -208,18 +208,12 @@
 
 {
     _cmsTRANSFORM* p = (_cmsTRANSFORM*) Transform;
-    cmsStride stride;
 
-    stride.BytesPerLineIn = 0;  // Not used
-    stride.BytesPerLineOut = 0;
-    stride.BytesPerPlaneIn = Size;
-    stride.BytesPerPlaneOut = Size;
-
-    p -> xform(p, InputBuffer, OutputBuffer, Size, 1, &stride);
+    p -> xform(p, InputBuffer, OutputBuffer, Size, Size);
 }
 
 
-// This is a legacy stride for planar
+// Apply transform.
 void CMSEXPORT cmsDoTransformStride(cmsHTRANSFORM  Transform,
                               const void* InputBuffer,
                               void* OutputBuffer,
@@ -227,40 +221,10 @@
 
 {
     _cmsTRANSFORM* p = (_cmsTRANSFORM*) Transform;
-    cmsStride stride;
 
-    stride.BytesPerLineIn = 0;
-    stride.BytesPerLineOut = 0;
-    stride.BytesPerPlaneIn = Stride;
-    stride.BytesPerPlaneOut = Stride;
-
-    p -> xform(p, InputBuffer, OutputBuffer, Size, 1, &stride);
+    p -> xform(p, InputBuffer, OutputBuffer, Size, Stride);
 }
 
-// This is the "fast" function for plugins
-void CMSEXPORT cmsDoTransformLineStride(cmsHTRANSFORM  Transform,
-                              const void* InputBuffer,
-                              void* OutputBuffer,
-                              cmsUInt32Number PixelsPerLine,
-                              cmsUInt32Number LineCount,
-                              cmsUInt32Number BytesPerLineIn,
-                              cmsUInt32Number BytesPerLineOut,
-                              cmsUInt32Number BytesPerPlaneIn,
-                              cmsUInt32Number BytesPerPlaneOut)
-
-{
-    _cmsTRANSFORM* p = (_cmsTRANSFORM*) Transform;
-    cmsStride stride;
-
-    stride.BytesPerLineIn = BytesPerLineIn;
-    stride.BytesPerLineOut = BytesPerLineOut;
-    stride.BytesPerPlaneIn = BytesPerPlaneIn;
-    stride.BytesPerPlaneOut = BytesPerPlaneOut;
-
-    p->xform(p, InputBuffer, OutputBuffer, PixelsPerLine, LineCount, &stride);
-}
-
-
 
 // Transform routines ----------------------------------------------------------------------------------------------------------
 
@@ -269,64 +233,49 @@
 static
 void FloatXFORM(_cmsTRANSFORM* p,
                 const void* in,
-                void* out,
-                cmsUInt32Number PixelsPerLine,
-                cmsUInt32Number LineCount,
-                const cmsStride* Stride)
+                void* out, cmsUInt32Number Size, cmsUInt32Number Stride)
 {
     cmsUInt8Number* accum;
     cmsUInt8Number* output;
     cmsFloat32Number fIn[cmsMAXCHANNELS], fOut[cmsMAXCHANNELS];
     cmsFloat32Number OutOfGamut;
-    cmsUInt32Number i, j, c, strideIn, strideOut;
+    cmsUInt32Number i, j;
 
-    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
+    accum  = (cmsUInt8Number*)  in;
+    output = (cmsUInt8Number*)  out;
 
-    strideIn = 0;
-    strideOut = 0;
+    for (i=0; i < Size; i++) {
 
-    for (i = 0; i < LineCount; i++) {
+        accum = p -> FromInputFloat(p, fIn, accum, Stride);
 
-        accum = (cmsUInt8Number*)in + strideIn;
-        output = (cmsUInt8Number*)out + strideOut;
+        // Any gamut chack to do?
+        if (p ->GamutCheck != NULL) {
 
-        for (j = 0; j < PixelsPerLine; j++) {
+            // Evaluate gamut marker.
+            cmsPipelineEvalFloat( fIn, &OutOfGamut, p ->GamutCheck);
 
-            accum = p->FromInputFloat(p, fIn, accum, Stride->BytesPerPlaneIn);
+            // Is current color out of gamut?
+            if (OutOfGamut > 0.0) {
 
-            // Any gamut chack to do?
-            if (p->GamutCheck != NULL) {
+                // Certainly, out of gamut
+                for (j=0; j < cmsMAXCHANNELS; j++)
+                    fOut[j] = -1.0;
 
-                // Evaluate gamut marker.
-                cmsPipelineEvalFloat(fIn, &OutOfGamut, p->GamutCheck);
-
-                // Is current color out of gamut?
-                if (OutOfGamut > 0.0) {
-
-                    // Certainly, out of gamut
-                    for (c = 0; c < cmsMAXCHANNELS; c++)
-                        fOut[c] = -1.0;
-
-                }
-                else {
-                    // No, proceed normally
-                    cmsPipelineEvalFloat(fIn, fOut, p->Lut);
-                }
             }
             else {
-
-                // No gamut check at all
-                cmsPipelineEvalFloat(fIn, fOut, p->Lut);
+                // No, proceed normally
+                cmsPipelineEvalFloat(fIn, fOut, p -> Lut);
             }
+        }
+        else {
 
-
-            output = p->ToOutputFloat(p, fOut, output, Stride->BytesPerPlaneOut);
+            // No gamut check at all
+            cmsPipelineEvalFloat(fIn, fOut, p -> Lut);
         }
 
-        strideIn += Stride->BytesPerLineIn;
-        strideOut += Stride->BytesPerLineOut;
+        // Back to asked representation
+        output = p -> ToOutputFloat(p, fOut, output, Stride);
     }
-
 }
 
 
@@ -334,34 +283,22 @@
 void NullFloatXFORM(_cmsTRANSFORM* p,
                     const void* in,
                     void* out,
-                    cmsUInt32Number PixelsPerLine,
-                    cmsUInt32Number LineCount,
-                    const cmsStride* Stride)
-
+                    cmsUInt32Number Size,
+                    cmsUInt32Number Stride)
 {
     cmsUInt8Number* accum;
     cmsUInt8Number* output;
     cmsFloat32Number fIn[cmsMAXCHANNELS];
-    cmsUInt32Number i, j, strideIn, strideOut;
+    cmsUInt32Number i, n;
 
-    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
+    accum  = (cmsUInt8Number*)  in;
+    output = (cmsUInt8Number*)  out;
+    n = Size;
 
-    strideIn = 0;
-    strideOut = 0;
+    for (i=0; i < n; i++) {
 
-    for (i = 0; i < LineCount; i++) {
-
-           accum = (cmsUInt8Number*) in + strideIn;
-           output = (cmsUInt8Number*) out + strideOut;
-
-           for (j = 0; j < PixelsPerLine; j++) {
-
-                  accum = p->FromInputFloat(p, fIn, accum, Stride ->BytesPerPlaneIn);
-                  output = p->ToOutputFloat(p, fIn, output, Stride->BytesPerPlaneOut);
-           }
-
-           strideIn += Stride->BytesPerLineIn;
-           strideOut += Stride->BytesPerLineOut;
+        accum  = p -> FromInputFloat(p, fIn, accum, Stride);
+        output = p -> ToOutputFloat(p, fIn, output, Stride);
     }
 }
 
@@ -371,36 +308,23 @@
 static
 void NullXFORM(_cmsTRANSFORM* p,
                const void* in,
-               void* out,
-               cmsUInt32Number PixelsPerLine,
-               cmsUInt32Number LineCount,
-               const cmsStride* Stride)
+               void* out, cmsUInt32Number Size,
+               cmsUInt32Number Stride)
 {
     cmsUInt8Number* accum;
     cmsUInt8Number* output;
     cmsUInt16Number wIn[cmsMAXCHANNELS];
-    cmsUInt32Number i, j, strideIn, strideOut;
+    cmsUInt32Number i, n;
 
-    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
+    accum  = (cmsUInt8Number*)  in;
+    output = (cmsUInt8Number*)  out;
+    n = Size;                    // Buffer len
 
-    strideIn = 0;
-    strideOut = 0;
+    for (i=0; i < n; i++) {
 
-    for (i = 0; i < LineCount; i++) {
-
-           accum = (cmsUInt8Number*)in + strideIn;
-           output = (cmsUInt8Number*)out + strideOut;
-
-           for (j = 0; j < PixelsPerLine; j++) {
-
-                  accum = p->FromInput(p, wIn, accum, Stride->BytesPerPlaneIn);
-                  output = p->ToOutput(p, wIn, output, Stride->BytesPerPlaneOut);
+        accum  = p -> FromInput(p, wIn, accum, Stride);
+        output = p -> ToOutput(p, wIn, output, Stride);
     }
-
-           strideIn += Stride->BytesPerLineIn;
-           strideOut += Stride->BytesPerLineOut;
-    }
-
 }
 
 
@@ -408,41 +332,27 @@
 static
 void PrecalculatedXFORM(_cmsTRANSFORM* p,
                         const void* in,
-                        void* out,
-                        cmsUInt32Number PixelsPerLine,
-                        cmsUInt32Number LineCount,
-                        const cmsStride* Stride)
+                        void* out, cmsUInt32Number Size, cmsUInt32Number Stride)
 {
     register cmsUInt8Number* accum;
     register cmsUInt8Number* output;
     cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
-    cmsUInt32Number i, j, strideIn, strideOut;
+    cmsUInt32Number i, n;
 
-    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
+    accum  = (cmsUInt8Number*)  in;
+    output = (cmsUInt8Number*)  out;
+    n = Size;
 
-    strideIn = 0;
-    strideOut = 0;
+    for (i=0; i < n; i++) {
 
-    for (i = 0; i < LineCount; i++) {
-
-        accum = (cmsUInt8Number*)in + strideIn;
-        output = (cmsUInt8Number*)out + strideOut;
-
-        for (j = 0; j < PixelsPerLine; j++) {
-
-            accum = p->FromInput(p, wIn, accum, Stride->BytesPerPlaneIn);
-            p->Lut->Eval16Fn(wIn, wOut, p->Lut->Data);
-            output = p->ToOutput(p, wOut, output, Stride->BytesPerPlaneOut);
-        }
-
-        strideIn += Stride->BytesPerLineIn;
-        strideOut += Stride->BytesPerLineOut;
+        accum = p -> FromInput(p, wIn, accum, Stride);
+        p ->Lut ->Eval16Fn(wIn, wOut, p -> Lut->Data);
+        output = p -> ToOutput(p, wOut, output, Stride);
     }
-
 }
 
 
-// Auxiliary: Handle precalculated gamut check. The retrieval of context may be alittle bit slow, but this function is not critical.
+// Auxiliar: Handle precalculated gamut check. The retrieval of context may be alittle bit slow, but this function is not critical.
 static
 void TransformOnePixelWithGamutCheck(_cmsTRANSFORM* p,
                                      const cmsUInt16Number wIn[],
@@ -469,35 +379,22 @@
 static
 void PrecalculatedXFORMGamutCheck(_cmsTRANSFORM* p,
                                   const void* in,
-                                  void* out,
-                                  cmsUInt32Number PixelsPerLine,
-                                  cmsUInt32Number LineCount,
-                                  const cmsStride* Stride)
+                                  void* out, cmsUInt32Number Size, cmsUInt32Number Stride)
 {
     cmsUInt8Number* accum;
     cmsUInt8Number* output;
     cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
-    cmsUInt32Number i, j, strideIn, strideOut;
+    cmsUInt32Number i, n;
 
-    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
+    accum  = (cmsUInt8Number*)  in;
+    output = (cmsUInt8Number*)  out;
+    n = Size;                    // Buffer len
 
-    strideIn = 0;
-    strideOut = 0;
+    for (i=0; i < n; i++) {
 
-    for (i = 0; i < LineCount; i++) {
-
-           accum = (cmsUInt8Number*)in + strideIn;
-           output = (cmsUInt8Number*)out + strideOut;
-
-           for (j = 0; j < PixelsPerLine; j++) {
-
-                  accum = p->FromInput(p, wIn, accum, Stride->BytesPerPlaneIn);
-                  TransformOnePixelWithGamutCheck(p, wIn, wOut);
-                  output = p->ToOutput(p, wOut, output, Stride->BytesPerPlaneOut);
-           }
-
-           strideIn += Stride->BytesPerLineIn;
-           strideOut += Stride->BytesPerLineOut;
+        accum = p -> FromInput(p, wIn, accum, Stride);
+        TransformOnePixelWithGamutCheck(p, wIn, wOut);
+        output = p -> ToOutput(p, wOut, output, Stride);
     }
 }
 
@@ -506,120 +403,94 @@
 static
 void CachedXFORM(_cmsTRANSFORM* p,
                  const void* in,
-                 void* out,
-                 cmsUInt32Number PixelsPerLine,
-                 cmsUInt32Number LineCount,
-                 const cmsStride* Stride)
+                 void* out, cmsUInt32Number Size, cmsUInt32Number Stride)
 {
     cmsUInt8Number* accum;
     cmsUInt8Number* output;
     cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
+    cmsUInt32Number i, n;
     _cmsCACHE Cache;
-    cmsUInt32Number i, j, strideIn, strideOut;
 
-    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
+    accum  = (cmsUInt8Number*)  in;
+    output = (cmsUInt8Number*)  out;
+    n = Size;                    // Buffer len
 
     // Empty buffers for quick memcmp
-    memset(wIn, 0, sizeof(wIn));
+    memset(wIn,  0, sizeof(wIn));
     memset(wOut, 0, sizeof(wOut));
 
     // Get copy of zero cache
-    memcpy(&Cache, &p->Cache, sizeof(Cache));
+    memcpy(&Cache, &p ->Cache, sizeof(Cache));
 
-    strideIn = 0;
-    strideOut = 0;
+    for (i=0; i < n; i++) {
 
-    for (i = 0; i < LineCount; i++) {
+        accum = p -> FromInput(p, wIn, accum, Stride);
 
-        accum = (cmsUInt8Number*)in + strideIn;
-        output = (cmsUInt8Number*)out + strideOut;
+        if (memcmp(wIn, Cache.CacheIn, sizeof(Cache.CacheIn)) == 0) {
 
-        for (j = 0; j < PixelsPerLine; j++) {
+            memcpy(wOut, Cache.CacheOut, sizeof(Cache.CacheOut));
+        }
+        else {
 
-            accum = p->FromInput(p, wIn, accum, Stride->BytesPerPlaneIn);
+            p ->Lut ->Eval16Fn(wIn, wOut, p -> Lut->Data);
 
-            if (memcmp(wIn, Cache.CacheIn, sizeof(Cache.CacheIn)) == 0) {
-
-                memcpy(wOut, Cache.CacheOut, sizeof(Cache.CacheOut));
-            }
-            else {
-                p->Lut->Eval16Fn(wIn, wOut, p->Lut->Data);
-
-                memcpy(Cache.CacheIn, wIn, sizeof(Cache.CacheIn));
-                memcpy(Cache.CacheOut, wOut, sizeof(Cache.CacheOut));
-            }
-
-            output = p->ToOutput(p, wOut, output, Stride->BytesPerPlaneOut);
+            memcpy(Cache.CacheIn,  wIn,  sizeof(Cache.CacheIn));
+            memcpy(Cache.CacheOut, wOut, sizeof(Cache.CacheOut));
         }
 
-        strideIn += Stride->BytesPerLineIn;
-        strideOut += Stride->BytesPerLineOut;
+        output = p -> ToOutput(p, wOut, output, Stride);
     }
+
 }
 
+
 // All those nice features together
 static
 void CachedXFORMGamutCheck(_cmsTRANSFORM* p,
                            const void* in,
-                           void* out,
-                           cmsUInt32Number PixelsPerLine,
-                           cmsUInt32Number LineCount,
-                           const cmsStride* Stride)
+                           void* out, cmsUInt32Number Size, cmsUInt32Number Stride)
 {
-    cmsUInt8Number* accum;
-    cmsUInt8Number* output;
-    cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
-    _cmsCACHE Cache;
-    cmsUInt32Number i, j, strideIn, strideOut;
+       cmsUInt8Number* accum;
+       cmsUInt8Number* output;
+       cmsUInt16Number wIn[cmsMAXCHANNELS], wOut[cmsMAXCHANNELS];
+       cmsUInt32Number i, n;
+       _cmsCACHE Cache;
 
-    _cmsHandleExtraChannels(p, in, out, PixelsPerLine, LineCount, Stride);
+       accum  = (cmsUInt8Number*)  in;
+       output = (cmsUInt8Number*)  out;
+       n = Size;                    // Buffer len
 
-    // Empty buffers for quick memcmp
-    memset(wIn, 0, sizeof(wIn));
-    memset(wOut, 0, sizeof(wOut));
+       // Empty buffers for quick memcmp
+       memset(wIn,  0, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
+       memset(wOut, 0, sizeof(cmsUInt16Number) * cmsMAXCHANNELS);
 
-    // Get copy of zero cache
-    memcpy(&Cache, &p->Cache, sizeof(Cache));
+       // Get copy of zero cache
+       memcpy(&Cache, &p ->Cache, sizeof(Cache));
 
-    strideIn = 0;
-    strideOut = 0;
+       for (i=0; i < n; i++) {
 
-    for (i = 0; i < LineCount; i++) {
-
-        accum = (cmsUInt8Number*)in + strideIn;
-        output = (cmsUInt8Number*)out + strideOut;
-
-        for (j = 0; j < PixelsPerLine; j++) {
-
-            accum = p->FromInput(p, wIn, accum, Stride->BytesPerPlaneIn);
+            accum = p -> FromInput(p, wIn, accum, Stride);
 
             if (memcmp(wIn, Cache.CacheIn, sizeof(Cache.CacheIn)) == 0) {
-
-                memcpy(wOut, Cache.CacheOut, sizeof(Cache.CacheOut));
+                    memcpy(wOut, Cache.CacheOut, sizeof(Cache.CacheOut));
             }
             else {
-                TransformOnePixelWithGamutCheck(p, wIn, wOut);
-
-                memcpy(Cache.CacheIn, wIn, sizeof(Cache.CacheIn));
-                memcpy(Cache.CacheOut, wOut, sizeof(Cache.CacheOut));
+                    TransformOnePixelWithGamutCheck(p, wIn, wOut);
+                    memcpy(Cache.CacheIn, wIn, sizeof(Cache.CacheIn));
+                    memcpy(Cache.CacheOut, wOut, sizeof(Cache.CacheOut));
             }
 
-            output = p->ToOutput(p, wOut, output, Stride->BytesPerPlaneOut);
-        }
+            output = p -> ToOutput(p, wOut, output, Stride);
+       }
 
-        strideIn += Stride->BytesPerLineIn;
-        strideOut += Stride->BytesPerLineOut;
-    }
 }
 
-// Transform plug-ins ----------------------------------------------------------------------------------------------------
+// -------------------------------------------------------------------------------------------------------------
 
 // List of used-defined transform factories
 typedef struct _cmsTransformCollection_st {
 
-    _cmsTransform2Factory  Factory;
-    cmsBool                OldXform;   // Factory returns xform function in the old style
-
+    _cmsTransformFactory  Factory;
     struct _cmsTransformCollection_st *Next;
 
 } _cmsTransformCollection;
@@ -662,7 +533,6 @@
   ctx ->chunks[TransformPlugin] = _cmsSubAllocDup(ctx->MemPool, &newHead, sizeof(_cmsTransformPluginChunkType));
 }
 
-// Allocates memory for transform plugin factory
 void _cmsAllocTransformPluginChunk(struct _cmsContext_struct* ctx,
                                         const struct _cmsContext_struct* src)
 {
@@ -677,35 +547,6 @@
     }
 }
 
-// Adaptor for old versions of plug-in
-static
-void _cmsTransform2toTransformAdaptor(struct _cmstransform_struct *CMMcargo,
-                                      const void* InputBuffer,
-                                      void* OutputBuffer,
-                                      cmsUInt32Number PixelsPerLine,
-                                      cmsUInt32Number LineCount,
-                                      const cmsStride* Stride)
-{
-
-       cmsUInt32Number i, strideIn, strideOut;
-
-       _cmsHandleExtraChannels(CMMcargo, InputBuffer, OutputBuffer, PixelsPerLine, LineCount, Stride);
-
-       strideIn = 0;
-       strideOut = 0;
-
-       for (i = 0; i < LineCount; i++) {
-
-              void *accum = (cmsUInt8Number*)InputBuffer + strideIn;
-              void *output = (cmsUInt8Number*)OutputBuffer + strideOut;
-
-              CMMcargo->OldXform(CMMcargo, accum, output, PixelsPerLine, Stride->BytesPerPlaneIn);
-
-              strideIn += Stride->BytesPerLineIn;
-              strideOut += Stride->BytesPerLineOut;
-       }
-}
-
 
 
 // Register new ways to transform
@@ -723,22 +564,14 @@
     }
 
     // Factory callback is required
-    if (Plugin->factories.xform == NULL) return FALSE;
+    if (Plugin ->Factory == NULL) return FALSE;
 
 
     fl = (_cmsTransformCollection*) _cmsPluginMalloc(ContextID, sizeof(_cmsTransformCollection));
     if (fl == NULL) return FALSE;
 
-    // Check for full xform plug-ins previous to 2.8, we would need an adapter in that case
-    if (Plugin->base.ExpectedVersion < 2080) {
-
-           fl->OldXform = TRUE;
-    }
-    else
-           fl->OldXform = FALSE;
-
     // Copy the parameters
-    fl->Factory = Plugin->factories.xform;
+    fl ->Factory = Plugin ->Factory;
 
     // Keep linked list
     fl ->Next = ctx->TransformCollection;
@@ -823,12 +656,6 @@
                             p->FromInputFloat = _cmsGetFormatter(ContextID, *InputFormat, cmsFormatterInput, CMS_PACK_FLAGS_FLOAT).FmtFloat;
                             p->ToOutputFloat = _cmsGetFormatter(ContextID, *OutputFormat, cmsFormatterOutput, CMS_PACK_FLAGS_FLOAT).FmtFloat;
 
-                            // Save the day?
-                            if (Plugin->OldXform) {
-                                   p->OldXform = (_cmsTransformFn) p->xform;
-                                   p->xform = _cmsTransform2toTransformAdaptor;
-                            }
-
                             return p;
                      }
               }
@@ -989,22 +816,6 @@
 
 // ----------------------------------------------------------------------------------------------------------------
 
-// Jun-21-2000: Some profiles (those that comes with W2K) comes
-// with the media white (media black?) x 100. Add a sanity check
-
-static
-void NormalizeXYZ(cmsCIEXYZ* Dest)
-{
-    while (Dest -> X > 2. &&
-           Dest -> Y > 2. &&
-           Dest -> Z > 2.) {
-
-               Dest -> X /= 10.;
-               Dest -> Y /= 10.;
-               Dest -> Z /= 10.;
-       }
-}
-
 static
 void SetWhitePoint(cmsCIEXYZ* wtPt, const cmsCIEXYZ* src)
 {
@@ -1017,8 +828,6 @@
         wtPt ->X = src->X;
         wtPt ->Y = src->Y;
         wtPt ->Z = src->Z;
-
-        NormalizeXYZ(wtPt);
     }
 
 }
@@ -1329,6 +1138,7 @@
                                          cmsUInt32Number InputFormat,
                                          cmsUInt32Number OutputFormat)
 {
+
     _cmsTRANSFORM* xform = (_cmsTRANSFORM*) hTransform;
     cmsFormatter16 FromInput, ToOutput;
 
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2.h b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2.h
index 9f148e5..0d66b26 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2.h
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2.h
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2014 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -52,7 +52,7 @@
 //
 //---------------------------------------------------------------------------------
 //
-// Version 2.8
+// Version 2.7
 //
 
 #ifndef _lcms2_H
@@ -104,7 +104,7 @@
 #endif
 
 // Version/release
-#define LCMS_VERSION        2080
+#define LCMS_VERSION        2070
 
 // I will give the chance of redefining basic types for compilers that are not fully C99 compliant
 #ifndef CMS_BASIC_TYPES_ALREADY_DEFINED
@@ -202,44 +202,43 @@
 #  define CMS_IS_WINDOWS_ 1
 #endif
 
-// Try to detect big endian platforms. This list can be endless, so primarily rely on the configure script
-// on Unix-like systems, and allow it to be set on the compiler command line using
-// -DCMS_USE_BIG_ENDIAN or something similar
-#ifdef CMS_USE_BIG_ENDIAN // set at compiler command line takes overall precedence
+// Try to detect big endian platforms. This list can be endless, so only some checks are performed over here.
+// you can pass this toggle to the compiler by using -DCMS_USE_BIG_ENDIAN or something similar
 
-#  if CMS_USE_BIG_ENDIAN == 0
-#    undef CMS_USE_BIG_ENDIAN
-#  endif
+#if defined(__sgi__) || defined(__sgi) || defined(sparc)
+#   define CMS_USE_BIG_ENDIAN      1
+#endif
 
-#else // CMS_USE_BIG_ENDIAN
+#if defined(__s390__) || defined(__s390x__)
+#   define CMS_USE_BIG_ENDIAN   1
+#endif
 
-#  ifdef WORDS_BIGENDIAN // set by configure (or explicitly on compiler command line)
-#    define CMS_USE_BIG_ENDIAN 1
-#  else // WORDS_BIGENDIAN
-// Fall back to platform/compiler specific tests
-#    if defined(__sgi__) || defined(__sgi) || defined(sparc)
-#      define CMS_USE_BIG_ENDIAN      1
-#    endif
 
-#    if defined(__s390__) || defined(__s390x__)
-#      define CMS_USE_BIG_ENDIAN   1
-#    endif
+#if defined(__powerpc__) || defined(__ppc__) || defined(TARGET_CPU_PPC)
+#  if __powerpc__ || __ppc__ || TARGET_CPU_PPC
+#   define CMS_USE_BIG_ENDIAN   1
+#   if defined (__GNUC__) && defined(__BYTE_ORDER__) && defined(__ORDER_LITTLE_ENDIAN__)
+#       if __BYTE_ORDER__  == __ORDER_LITTLE_ENDIAN__
+                // Don't use big endian for PowerPC little endian mode
+#                undef CMS_USE_BIG_ENDIAN
+#       endif
+#     endif
+#   endif
+#endif
 
-#    ifdef macintosh
-#      ifdef __BIG_ENDIAN__
-#        define CMS_USE_BIG_ENDIAN      1
-#      endif
-#      ifdef __LITTLE_ENDIAN__
-#        undef CMS_USE_BIG_ENDIAN
-#      endif
-#    endif
-#  endif  // WORDS_BIGENDIAN
+#ifdef macintosh
+# ifdef __BIG_ENDIAN__
+#   define CMS_USE_BIG_ENDIAN      1
+# endif
+# ifdef __LITTLE_ENDIAN__
+#   undef CMS_USE_BIG_ENDIAN
+# endif
+#endif
 
-#  if defined(_HOST_BIG_ENDIAN) || defined(__BIG_ENDIAN__)
-#    define CMS_USE_BIG_ENDIAN      1
-#  endif
-
-#endif  // CMS_USE_BIG_ENDIAN
+// WORDS_BIGENDIAN takes precedence
+#if defined(_HOST_BIG_ENDIAN) || defined(__BIG_ENDIAN__) || defined(WORDS_BIGENDIAN)
+#   define CMS_USE_BIG_ENDIAN      1
+#endif
 
 
 // Calling convention -- this is hardly platform and compiler dependent
@@ -249,7 +248,7 @@
 #        define CMSEXPORT       __stdcall _export
 #        define CMSAPI
 #     else
-#        define CMSEXPORT      __stdcall
+#        define CMSEXPORT      _stdcall
 #        ifdef CMS_DLL_BUILD
 #            define CMSAPI    __declspec(dllexport)
 #        else
@@ -411,8 +410,7 @@
     cmsSigViewingCondDescTag                = 0x76756564,  // 'vued'
     cmsSigViewingConditionsTag              = 0x76696577,  // 'view'
     cmsSigVcgtTag                           = 0x76636774,  // 'vcgt'
-    cmsSigMetaTag                           = 0x6D657461,  // 'meta'
-    cmsSigArgyllArtsTag                     = 0x61727473   // 'arts'
+    cmsSigMetaTag                           = 0x6D657461   // 'meta'
 
 } cmsTagSignature;
 
@@ -685,7 +683,7 @@
 //            T: Pixeltype
 //            F: Flavor  0=MinIsBlack(Chocolate) 1=MinIsWhite(Vanilla)
 //            P: Planar? 0=Chunky, 1=Planar
-//            X: swap 16 bps endianness?
+//            X: swap 16 bps endianess?
 //            S: Do swap? ie, BGR, KYMC
 //            E: Extra samples
 //            C: Channels (Samples per pixel)
@@ -928,7 +926,7 @@
 #define TYPE_ARGB_FLT         (FLOAT_SH(1)|COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(4)|SWAPFIRST_SH(1))
 #define TYPE_BGR_FLT          (FLOAT_SH(1)|COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(4)|DOSWAP_SH(1))
 #define TYPE_BGRA_FLT         (FLOAT_SH(1)|COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(4)|DOSWAP_SH(1)|SWAPFIRST_SH(1))
-#define TYPE_ABGR_FLT         (FLOAT_SH(1)|COLORSPACE_SH(PT_RGB)|EXTRA_SH(1)|CHANNELS_SH(3)|BYTES_SH(4)|DOSWAP_SH(1))
+#define TYPE_ABGR_FLT         (FLOAT_SH(1)|COLORSPACE_SH(PT_RGB)|CHANNELS_SH(3)|BYTES_SH(4)|DOSWAP_SH(1))
 
 #define TYPE_CMYK_FLT         (FLOAT_SH(1)|COLORSPACE_SH(PT_CMYK)|CHANNELS_SH(4)|BYTES_SH(4))
 
@@ -1045,7 +1043,7 @@
 // Context handling --------------------------------------------------------------------------------------------------------
 
 // Each context holds its owns globals and its own plug-ins. There is a global context with the id = 0 for lecacy compatibility
-// though using the global context is not recommended. Proper context handling makes lcms more thread-safe.
+// though using the global context is not recomended. Proper context handling makes lcms more thread-safe.
 
 typedef struct _cmsContext_struct* cmsContext;
 
@@ -1414,7 +1412,7 @@
 typedef struct {
 
     cmsUInt32Number n;
-    cmsContext      ContextID;
+    cmsContext     ContextID;
     cmsPSEQDESC*    seq;
 
 } cmsSEQ;
@@ -1681,8 +1679,6 @@
 // Specific to unbounded mode
 #define cmsFLAGS_NONEGATIVES              0x8000    // Prevent negative numbers in floating point transforms
 
-// Copy alpha channels when transforming
-#define cmsFLAGS_COPY_ALPHA               0x04000000 // Alpha channels are copied on cmsDoTransform()
 
 // Fine-tune control over number of gridpoints
 #define cmsFLAGS_GRIDPOINTS(n)           (((n) & 0xFF) << 16)
@@ -1761,22 +1757,12 @@
                                                  void * OutputBuffer,
                                                  cmsUInt32Number Size);
 
-CMSAPI void             CMSEXPORT cmsDoTransformStride(cmsHTRANSFORM Transform,   // Deprecated
+CMSAPI void             CMSEXPORT cmsDoTransformStride(cmsHTRANSFORM Transform,
                                                  const void * InputBuffer,
                                                  void * OutputBuffer,
                                                  cmsUInt32Number Size,
                                                  cmsUInt32Number Stride);
 
-CMSAPI void             CMSEXPORT cmsDoTransformLineStride(cmsHTRANSFORM  Transform,
-                                                 const void* InputBuffer,
-                                                 void* OutputBuffer,
-                                                 cmsUInt32Number PixelsPerLine,
-                                                 cmsUInt32Number LineCount,
-                                                 cmsUInt32Number BytesPerLineIn,
-                                                 cmsUInt32Number BytesPerLineOut,
-                                                 cmsUInt32Number BytesPerPlaneIn,
-                                                 cmsUInt32Number BytesPerPlaneOut);
-
 
 CMSAPI void             CMSEXPORT cmsSetAlarmCodes(const cmsUInt16Number NewAlarm[cmsMAXCHANNELS]);
 CMSAPI void             CMSEXPORT cmsGetAlarmCodes(cmsUInt16Number NewAlarm[cmsMAXCHANNELS]);
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h
index 9009472..c6cfbd6 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_internal.h
@@ -30,7 +30,7 @@
 
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2014 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -86,15 +86,7 @@
 #define _cmsALIGNLONG(x) (((x)+(sizeof(cmsUInt32Number)-1)) & ~(sizeof(cmsUInt32Number)-1))
 
 // Alignment to memory pointer
-
-// (Ultra)SPARC with gcc requires ptr alignment of 8 bytes
-// even though sizeof(void *) is only four: for greatest flexibility
-// allow the build to specify ptr alignment.
-#ifndef CMS_PTR_ALIGNMENT
-# define CMS_PTR_ALIGNMENT sizeof(void *)
-#endif
-
-#define _cmsALIGNMEM(x)  (((x)+(CMS_PTR_ALIGNMENT - 1)) & ~(CMS_PTR_ALIGNMENT - 1))
+#define _cmsALIGNMEM(x)  (((x)+(sizeof(void *) - 1)) & ~(sizeof(void *) - 1))
 
 // Maximum encodeable values in floating point
 #define MAX_ENCODEABLE_XYZ  (1.0 + 32767.0/32768.0)
@@ -130,7 +122,7 @@
 
 // A fast way to convert from/to 16 <-> 8 bits
 #define FROM_8_TO_16(rgb) (cmsUInt16Number) ((((cmsUInt16Number) (rgb)) << 8)|(rgb))
-#define FROM_16_TO_8(rgb) (cmsUInt8Number) ((((cmsUInt32Number)(rgb) * 65281U + 8388608U) >> 24) & 0xFFU)
+#define FROM_16_TO_8(rgb) (cmsUInt8Number) ((((rgb) * 65281 + 8388608) >> 24) & 0xFF)
 
 // Code analysis is broken on asserts
 #ifdef _MSC_VER
@@ -699,8 +691,8 @@
     cmsContext ContextID;
 
     // The directory
-    cmsUInt32Number  AllocatedEntries;
-    cmsUInt32Number  UsedEntries;
+    int AllocatedEntries;
+    int UsedEntries;
     _cmsMLUentry* Entries;     // Array of pointers to strings allocated in MemPool
 
     // The Pool
@@ -768,7 +760,7 @@
     // Dictionary
     cmsUInt32Number          TagCount;
     cmsTagSignature          TagNames[MAX_TABLE_TAG];
-    cmsTagSignature          TagLinked[MAX_TABLE_TAG];           // The tag to which is linked (0=none)
+    cmsTagSignature          TagLinked[MAX_TABLE_TAG];           // The tag to wich is linked (0=none)
     cmsUInt32Number          TagSizes[MAX_TABLE_TAG];            // Size on disk
     cmsUInt32Number          TagOffsets[MAX_TABLE_TAG];
     cmsBool                  TagSaveAsRaw[MAX_TABLE_TAG];        // True to write uncooked
@@ -996,7 +988,7 @@
     cmsUInt32Number InputFormat, OutputFormat; // Keep formats for further reference
 
     // Points to transform code
-    _cmsTransform2Fn xform;
+    _cmsTransformFn xform;
 
     // Formatters, cannot be embedded into LUT because cache
     cmsFormatter16 FromInput;
@@ -1042,20 +1034,9 @@
     void* UserData;
     _cmsFreeUserDataFn FreeUserData;
 
-    // A way to provide backwards compatibility with full xform plugins
-    _cmsTransformFn OldXform;
-
 } _cmsTRANSFORM;
 
-// Copies extra channels from input to output if the original flags in the transform structure
-// instructs to do so. This function is called on all standard transform functions.
-void _cmsHandleExtraChannels(_cmsTRANSFORM* p, const void* in,
-                             void* out,
-                             cmsUInt32Number PixelsPerLine,
-                             cmsUInt32Number LineCount,
-                             const cmsStride* Stride);
-
-// -----------------------------------------------------------------------------------------------------------------------
+// --------------------------------------------------------------------------------------------------
 
 cmsHTRANSFORM _cmsChain2Lab(cmsContext             ContextID,
                             cmsUInt32Number        nProfiles,
diff --git a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_plugin.h b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_plugin.h
index aff3b48..77ff228 100644
--- a/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_plugin.h
+++ b/jdk/src/share/native/sun/java2d/cmm/lcms/lcms2_plugin.h
@@ -30,7 +30,7 @@
 //---------------------------------------------------------------------------------
 //
 //  Little Color Management System
-//  Copyright (c) 1998-2016 Marti Maria Saguer
+//  Copyright (c) 1998-2011 Marti Maria Saguer
 //
 // Permission is hereby granted, free of charge, to any person obtaining
 // a copy of this software and associated documentation files (the "Software"),
@@ -157,7 +157,7 @@
                                                                    const void* Buffer);
 };
 
-// Endianness adjust functions
+// Endianess adjust functions
 CMSAPI cmsUInt16Number   CMSEXPORT  _cmsAdjustEndianess16(cmsUInt16Number Word);
 CMSAPI cmsUInt32Number   CMSEXPORT  _cmsAdjustEndianess32(cmsUInt32Number Value);
 CMSAPI void              CMSEXPORT  _cmsAdjustEndianess64(cmsUInt64Number* Result, cmsUInt64Number* QWord);
@@ -371,8 +371,8 @@
 
 typedef cmsUInt8Number* (* cmsFormatter16)(register struct _cmstransform_struct* CMMcargo,
                                            register cmsUInt16Number Values[],
-                                           register cmsUInt8Number* Buffer,
-                                           register cmsUInt32Number Stride);
+                                           register cmsUInt8Number*  Buffer,
+                                           register cmsUInt32Number  Stride);
 
 typedef cmsUInt8Number* (* cmsFormatterFloat)(struct _cmstransform_struct* CMMcargo,
                                               cmsFloat32Number Values[],
@@ -600,28 +600,11 @@
 
 //----------------------------------------------------------------------------------------------------------
 // Full xform
-
-typedef struct {
-       cmsUInt32Number BytesPerLineIn;
-       cmsUInt32Number BytesPerLineOut;
-       cmsUInt32Number BytesPerPlaneIn;
-       cmsUInt32Number BytesPerPlaneOut;
-
-} cmsStride;
-
-typedef void     (* _cmsTransformFn)(struct _cmstransform_struct *CMMcargo,   // Legacy function, handles just ONE scanline.
+typedef void     (* _cmsTransformFn)(struct _cmstransform_struct *CMMcargo,
                                      const void* InputBuffer,
                                      void* OutputBuffer,
                                      cmsUInt32Number Size,
-                                     cmsUInt32Number Stride);                 // Stride in bytes to the next plana in planar formats
-
-
-typedef void     (*_cmsTransform2Fn)(struct _cmstransform_struct *CMMcargo,
-                                     const void* InputBuffer,
-                                     void* OutputBuffer,
-                                     cmsUInt32Number PixelsPerLine,
-                                     cmsUInt32Number LineCount,
-                                     const cmsStride* Stride);
+                                     cmsUInt32Number Stride);
 
 typedef cmsBool  (* _cmsTransformFactory)(_cmsTransformFn* xform,
                                          void** UserData,
@@ -631,14 +614,6 @@
                                          cmsUInt32Number* OutputFormat,
                                          cmsUInt32Number* dwFlags);
 
-typedef cmsBool  (* _cmsTransform2Factory)(_cmsTransform2Fn* xform,
-                                         void** UserData,
-                                         _cmsFreeUserDataFn* FreePrivateDataFn,
-                                         cmsPipeline** Lut,
-                                         cmsUInt32Number* InputFormat,
-                                         cmsUInt32Number* OutputFormat,
-                                         cmsUInt32Number* dwFlags);
-
 
 // Retrieve user data as specified by the factory
 CMSAPI void   CMSEXPORT _cmsSetTransformUserData(struct _cmstransform_struct *CMMcargo, void* ptr, _cmsFreeUserDataFn FreePrivateDataFn);
@@ -653,10 +628,7 @@
       cmsPluginBase     base;
 
       // Transform entry point
-      union {
-             _cmsTransformFactory        legacy_xform;
-             _cmsTransform2Factory       xform;
-      } factories;
+      _cmsTransformFactory  Factory;
 
 }  cmsPluginTransform;
 
diff --git a/jdk/src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.c b/jdk/src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.c
index 6a70d40..742dfeb 100644
--- a/jdk/src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.c
+++ b/jdk/src/share/native/sun/java2d/loops/GraphicsPrimitiveMgr.c
@@ -104,47 +104,40 @@
     {
         return;
     }
-    CHECK_NULL(RegisterID =
-        (*env)->GetStaticMethodID(env, GPMgr, RegisterName, RegisterSig));
-    CHECK_NULL(pNativePrimID = (*env)->GetFieldID(env, GP, "pNativePrim", "J"));
-    CHECK_NULL(pixelID = (*env)->GetFieldID(env, SG2D, "pixel", "I"));
-    CHECK_NULL(eargbID = (*env)->GetFieldID(env, SG2D, "eargb", "I"));
-    CHECK_NULL(clipRegionID =
-        (*env)->GetFieldID(env, SG2D, "clipRegion", "Lsun/java2d/pipe/Region;"));
-    CHECK_NULL(compositeID =
-        (*env)->GetFieldID(env, SG2D, "composite", "Ljava/awt/Composite;"));
-    CHECK_NULL(lcdTextContrastID =
-        (*env)->GetFieldID(env, SG2D, "lcdTextContrast", "I"));
-    CHECK_NULL(getRgbID = (*env)->GetMethodID(env, Color, "getRGB", "()I"));
-    CHECK_NULL(xorPixelID = (*env)->GetFieldID(env, XORComp, "xorPixel", "I"));
-    CHECK_NULL(xorColorID =
-        (*env)->GetFieldID(env, XORComp, "xorColor", "Ljava/awt/Color;"));
-    CHECK_NULL(alphaMaskID =
-        (*env)->GetFieldID(env, XORComp, "alphaMask", "I"));
-    CHECK_NULL(ruleID = (*env)->GetFieldID(env, AlphaComp, "rule", "I"));
-    CHECK_NULL(extraAlphaID =
-        (*env)->GetFieldID(env, AlphaComp, "extraAlpha", "F"));
+    RegisterID = (*env)->GetStaticMethodID(env, GPMgr,
+                                           RegisterName, RegisterSig);
+    pNativePrimID = (*env)->GetFieldID(env, GP, "pNativePrim", "J");
+    pixelID = (*env)->GetFieldID(env, SG2D, "pixel", "I");
+    eargbID = (*env)->GetFieldID(env, SG2D, "eargb", "I");
+    clipRegionID = (*env)->GetFieldID(env, SG2D, "clipRegion",
+                                      "Lsun/java2d/pipe/Region;");
+    compositeID = (*env)->GetFieldID(env, SG2D, "composite",
+                                     "Ljava/awt/Composite;");
+    lcdTextContrastID =
+        (*env)->GetFieldID(env, SG2D, "lcdTextContrast", "I");
+    getRgbID = (*env)->GetMethodID(env, Color, "getRGB", "()I");
+    xorPixelID = (*env)->GetFieldID(env, XORComp, "xorPixel", "I");
+    xorColorID = (*env)->GetFieldID(env, XORComp, "xorColor",
+                                    "Ljava/awt/Color;");
+    alphaMaskID = (*env)->GetFieldID(env, XORComp, "alphaMask", "I");
+    ruleID = (*env)->GetFieldID(env, AlphaComp, "rule", "I");
+    extraAlphaID = (*env)->GetFieldID(env, AlphaComp, "extraAlpha", "F");
 
 
-    CHECK_NULL(m00ID = (*env)->GetFieldID(env, AT, "m00", "D"));
-    CHECK_NULL(m01ID = (*env)->GetFieldID(env, AT, "m01", "D"));
-    CHECK_NULL(m02ID = (*env)->GetFieldID(env, AT, "m02", "D"));
-    CHECK_NULL(m10ID = (*env)->GetFieldID(env, AT, "m10", "D"));
-    CHECK_NULL(m11ID = (*env)->GetFieldID(env, AT, "m11", "D"));
-    CHECK_NULL(m12ID = (*env)->GetFieldID(env, AT, "m12", "D"));
+    m00ID = (*env)->GetFieldID(env, AT, "m00", "D");
+    m01ID = (*env)->GetFieldID(env, AT, "m01", "D");
+    m02ID = (*env)->GetFieldID(env, AT, "m02", "D");
+    m10ID = (*env)->GetFieldID(env, AT, "m10", "D");
+    m11ID = (*env)->GetFieldID(env, AT, "m11", "D");
+    m12ID = (*env)->GetFieldID(env, AT, "m12", "D");
 
-    CHECK_NULL(path2DTypesID =
-        (*env)->GetFieldID(env, Path2D, "pointTypes", "[B"));
-    CHECK_NULL(path2DNumTypesID =
-        (*env)->GetFieldID(env, Path2D, "numTypes", "I"));
-    CHECK_NULL(path2DWindingRuleID =
-        (*env)->GetFieldID(env, Path2D, "windingRule", "I"));
-    CHECK_NULL(path2DFloatCoordsID =
-        (*env)->GetFieldID(env, Path2DFloat, "floatCoords", "[F"));
-    CHECK_NULL(sg2dStrokeHintID =
-        (*env)->GetFieldID(env, SG2D, "strokeHint", "I"));
-    CHECK_NULL(fid =
-        (*env)->GetStaticFieldID(env, SHints, "INTVAL_STROKE_PURE", "I"));
+    path2DTypesID = (*env)->GetFieldID(env, Path2D, "pointTypes", "[B");
+    path2DNumTypesID = (*env)->GetFieldID(env, Path2D, "numTypes", "I");
+    path2DWindingRuleID = (*env)->GetFieldID(env, Path2D, "windingRule", "I");
+    path2DFloatCoordsID = (*env)->GetFieldID(env, Path2DFloat,
+                                             "floatCoords", "[F");
+    sg2dStrokeHintID = (*env)->GetFieldID(env, SG2D, "strokeHint", "I");
+    fid = (*env)->GetStaticFieldID(env, SHints, "INTVAL_STROKE_PURE", "I");
     sunHints_INTVAL_STROKE_PURE = (*env)->GetStaticIntField(env, SHints, fid);
 }
 
diff --git a/jdk/src/share/native/sun/misc/VMSupport.c b/jdk/src/share/native/sun/misc/VMSupport.c
index eb4ab4b..35c9933 100644
--- a/jdk/src/share/native/sun/misc/VMSupport.c
+++ b/jdk/src/share/native/sun/misc/VMSupport.c
@@ -42,7 +42,6 @@
         if (!JDK_InitJvmHandle()) {
             JNU_ThrowInternalError(env,
                  "Handle for JVM not found for symbol lookup");
-            return NULL;
         }
         InitAgentProperties_fp = (INIT_AGENT_PROPERTIES_FN)
             JDK_FindJvmEntry("JVM_InitAgentProperties");
diff --git a/jdk/src/solaris/bin/jexec.c b/jdk/src/solaris/bin/jexec.c
index 13220cb..a30617d 100644
--- a/jdk/src/solaris/bin/jexec.c
+++ b/jdk/src/solaris/bin/jexec.c
@@ -331,7 +331,6 @@
                 off_t end   = start  + xlen;
 
                 if (end <= count) {
-                    end -= 4; // make sure there are 4 bytes to read at start
                     while (start < end) {
                         off_t xhid  = SH(buf, start);
                         off_t xdlen = SH(buf, start + 2);
diff --git a/jdk/src/solaris/classes/sun/java2d/xr/XRRenderer.java b/jdk/src/solaris/classes/sun/java2d/xr/XRRenderer.java
index 9040018..5eb84ed 100644
--- a/jdk/src/solaris/classes/sun/java2d/xr/XRRenderer.java
+++ b/jdk/src/solaris/classes/sun/java2d/xr/XRRenderer.java
@@ -28,7 +28,6 @@
 import java.awt.*;
 import java.awt.geom.*;
 import sun.awt.SunToolkit;
-import sun.java2d.InvalidPipeException;
 import sun.java2d.SunGraphics2D;
 import sun.java2d.loops.*;
 import sun.java2d.pipe.Region;
@@ -70,12 +69,7 @@
      * destination context.
      */
     private final void validateSurface(SunGraphics2D sg2d) {
-        XRSurfaceData xrsd;
-        try {
-            xrsd = (XRSurfaceData) sg2d.surfaceData;
-        } catch (ClassCastException e) {
-            throw new InvalidPipeException("wrong surface data type: " + sg2d.surfaceData);
-        }
+        XRSurfaceData xrsd = (XRSurfaceData) sg2d.surfaceData;
         xrsd.validateAsDestination(sg2d, sg2d.getCompClip());
         xrsd.maskBuffer.validateCompositeState(sg2d.composite, sg2d.transform,
                                                sg2d.paint, sg2d);
diff --git a/jdk/src/solaris/classes/sun/nio/fs/LinuxWatchService.java b/jdk/src/solaris/classes/sun/nio/fs/LinuxWatchService.java
index b40ee9c..123fab5 100644
--- a/jdk/src/solaris/classes/sun/nio/fs/LinuxWatchService.java
+++ b/jdk/src/solaris/classes/sun/nio/fs/LinuxWatchService.java
@@ -322,6 +322,19 @@
                         bytesRead = 0;
                     }
 
+                    // process any pending requests
+                    if ((nReady > 1) || (nReady == 1 && bytesRead == 0)) {
+                        try {
+                            read(socketpair[0], address, BUFFER_SIZE);
+                            boolean shutdown = processRequests();
+                            if (shutdown)
+                                break;
+                        } catch (UnixException x) {
+                            if (x.errno() != UnixConstants.EAGAIN)
+                                throw x;
+                        }
+                    }
+
                     // iterate over buffer to decode events
                     int offset = 0;
                     while (offset < bytesRead) {
@@ -356,19 +369,6 @@
 
                         offset += (SIZEOF_INOTIFY_EVENT + len);
                     }
-
-                    // process any pending requests
-                    if ((nReady > 1) || (nReady == 1 && bytesRead == 0)) {
-                        try {
-                            read(socketpair[0], address, BUFFER_SIZE);
-                            boolean shutdown = processRequests();
-                            if (shutdown)
-                                break;
-                        } catch (UnixException x) {
-                            if (x.errno() != UnixConstants.EAGAIN)
-                                throw x;
-                        }
-                    }
                 }
             } catch (UnixException x) {
                 x.printStackTrace();
diff --git a/jdk/src/solaris/classes/sun/security/provider/NativePRNG.java b/jdk/src/solaris/classes/sun/security/provider/NativePRNG.java
index bbb48c4..1d275f0 100644
--- a/jdk/src/solaris/classes/sun/security/provider/NativePRNG.java
+++ b/jdk/src/solaris/classes/sun/security/provider/NativePRNG.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
@@ -28,8 +28,6 @@
 import java.io.*;
 import java.net.*;
 import java.security.*;
-import java.util.Arrays;
-
 import sun.security.util.Debug;
 
 /**
@@ -336,9 +334,7 @@
         private final static long MAX_BUFFER_TIME = 100;
 
         // size of the "next" buffer
-        private static final int MAX_BUFFER_SIZE = 65536;
-        private static final int MIN_BUFFER_SIZE = 32;
-        private int bufferSize = 256;
+        private final static int BUFFER_SIZE = 32;
 
         // Holder for the seedFile.  Used if we ever add seed material.
         File seedFile;
@@ -355,7 +351,7 @@
         private volatile sun.security.provider.SecureRandom mixRandom;
 
         // buffer for next bits
-        private byte[] nextBuffer;
+        private final byte[] nextBuffer;
 
         // number of bytes left in nextBuffer
         private int buffered;
@@ -363,16 +359,6 @@
         // time we read the data into the nextBuffer
         private long lastRead;
 
-        // Count for the number of buffer size changes requests
-        // Positive value in increase size, negative to lower it.
-        private int change_buffer = 0;
-
-        // Request limit to trigger an increase in nextBuffer size
-        private static final int REQ_LIMIT_INC = 1000;
-
-        // Request limit to trigger a decrease in nextBuffer size
-        private static final int REQ_LIMIT_DEC = -100;
-
         // mutex lock for nextBytes()
         private final Object LOCK_GET_BYTES = new Object();
 
@@ -387,7 +373,7 @@
             this.seedFile = seedFile;
             seedIn = new FileInputStream(seedFile);
             nextIn = new FileInputStream(nextFile);
-            nextBuffer = new byte[bufferSize];
+            nextBuffer = new byte[BUFFER_SIZE];
         }
 
         // get the SHA1PRNG for mixing
@@ -480,47 +466,9 @@
         // if not, read new bytes
         private void ensureBufferValid() throws IOException {
             long time = System.currentTimeMillis();
-            int new_buffer_size = 0;
-
-            // Check if buffer has bytes available that are not too old
-            if (buffered > 0) {
-                if (time - lastRead < MAX_BUFFER_TIME) {
-                    return;
-                } else {
-                    // byte is old, so subtract from counter to shrink buffer
-                    change_buffer--;
-                }
-            } else {
-                // No bytes available, so add to count to increase buffer
-                change_buffer++;
+            if ((buffered > 0) && (time - lastRead < MAX_BUFFER_TIME)) {
+                return;
             }
-
-            // If counter has it a limit, increase or decrease size
-            if (change_buffer > REQ_LIMIT_INC) {
-                new_buffer_size = nextBuffer.length * 2;
-            } else if (change_buffer < REQ_LIMIT_DEC) {
-                new_buffer_size = nextBuffer.length / 2;
-            }
-
-            // If buffer size is to be changed, replace nextBuffer.
-            if (new_buffer_size > 0) {
-                if (new_buffer_size <= MAX_BUFFER_SIZE &&
-                        new_buffer_size >= MIN_BUFFER_SIZE) {
-                    nextBuffer = new byte[new_buffer_size];
-                    if (debug != null) {
-                        debug.println("Buffer size changed to " +
-                                new_buffer_size);
-                    }
-                } else {
-                    if (debug != null) {
-                        debug.println("Buffer reached limit: " +
-                                nextBuffer.length);
-                    }
-                }
-                change_buffer = 0;
-            }
-
-            // Load fresh random bytes into nextBuffer
             lastRead = time;
             readFully(nextIn, nextBuffer);
             buffered = nextBuffer.length;
@@ -530,40 +478,24 @@
         // read from "next" and XOR with bytes generated by the
         // mixing SHA1PRNG
         private void implNextBytes(byte[] data) {
+            synchronized (LOCK_GET_BYTES) {
                 try {
                     getMixRandom().engineNextBytes(data);
-                    int data_len = data.length;
+                    int len = data.length;
                     int ofs = 0;
-                    int len;
-                    int buf_pos;
-                    int localofs;
-                    byte[] localBuffer;
-
-                    while (data_len > 0) {
-                        synchronized (LOCK_GET_BYTES) {
-                            ensureBufferValid();
-                            buf_pos = nextBuffer.length - buffered;
-                            if (data_len > buffered) {
-                                len = buffered;
-                                buffered = 0;
-                            } else {
-                                len = data_len;
-                                buffered -= len;
-                            }
-                            localBuffer = Arrays.copyOfRange(nextBuffer, buf_pos,
-                                    buf_pos + len);
+                    while (len > 0) {
+                        ensureBufferValid();
+                        int bufferOfs = nextBuffer.length - buffered;
+                        while ((len > 0) && (buffered > 0)) {
+                            data[ofs++] ^= nextBuffer[bufferOfs++];
+                            len--;
+                            buffered--;
                         }
-                        localofs = 0;
-                        while (len > localofs) {
-                            data[ofs] ^= localBuffer[localofs];
-                            ofs++;
-                            localofs++;
-                        }
-                    data_len -= len;
                     }
-                } catch (IOException e){
+                } catch (IOException e) {
                     throw new ProviderException("nextBytes() failed", e);
                 }
+            }
         }
-        }
+    }
 }
diff --git a/jdk/src/solaris/native/com/sun/security/auth/module/Solaris.c b/jdk/src/solaris/native/com/sun/security/auth/module/Solaris.c
index d94edc6..12a7074 100644
--- a/jdk/src/solaris/native/com/sun/security/auth/module/Solaris.c
+++ b/jdk/src/solaris/native/com/sun/security/auth/module/Solaris.c
@@ -32,12 +32,6 @@
 #include <string.h>
 #include <pwd.h>
 
-static void throwIllegalArgumentException(JNIEnv *env, const char *msg) {
-    jclass clazz = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
-    if (clazz != NULL)
-        (*env)->ThrowNew(env, clazz, msg);
-}
-
 JNIEXPORT void JNICALL
 Java_com_sun_security_auth_module_SolarisSystem_getSolarisInfo
                                                 (JNIEnv *env, jobject obj) {
@@ -57,7 +51,7 @@
 
     if (groups == NULL) {
         jclass cls = (*env)->FindClass(env,"java/lang/OutOfMemoryError");
-        if (cls != NULL)
+        if(cls != 0)
             (*env)->ThrowNew(env, cls, NULL);
         return;
     }
@@ -73,13 +67,15 @@
          */
         fid = (*env)->GetFieldID(env, cls, "username", "Ljava/lang/String;");
         if (fid == 0) {
-            (*env)->ExceptionClear(env);
-            throwIllegalArgumentException(env, "invalid field: username");
-            return;
+            jclass newExcCls =
+                (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+            if (newExcCls == 0) {
+                /* Unable to find the new exception class, give up. */
+                return;
+            }
+            (*env)->ThrowNew(env, newExcCls, "invalid field: username");
         }
         jstr = (*env)->NewStringUTF(env, pwd.pw_name);
-        if (jstr == NULL)
-            return;
         (*env)->SetObjectField(env, obj, fid, jstr);
 
         /*
@@ -87,9 +83,13 @@
          */
         fid = (*env)->GetFieldID(env, cls, "uid", "J");
         if (fid == 0) {
-            (*env)->ExceptionClear(env);
-            throwIllegalArgumentException(env, "invalid field: uid");
-            return;
+            jclass newExcCls =
+                (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+            if (newExcCls == 0) {
+                /* Unable to find the new exception class, give up. */
+                return;
+            }
+            (*env)->ThrowNew(env, newExcCls, "invalid field: username");
         }
         (*env)->SetLongField(env, obj, fid, pwd.pw_uid);
 
@@ -98,9 +98,13 @@
          */
         fid = (*env)->GetFieldID(env, cls, "gid", "J");
         if (fid == 0) {
-            (*env)->ExceptionClear(env);
-            throwIllegalArgumentException(env, "invalid field: gid");
-            return;
+            jclass newExcCls =
+                (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+            if (newExcCls == 0) {
+                /* Unable to find the new exception class, give up. */
+                return;
+            }
+            (*env)->ThrowNew(env, newExcCls, "invalid field: username");
         }
         (*env)->SetLongField(env, obj, fid, pwd.pw_gid);
 
@@ -109,17 +113,17 @@
          */
         fid = (*env)->GetFieldID(env, cls, "groups", "[J");
         if (fid == 0) {
-            (*env)->ExceptionClear(env);
-            throwIllegalArgumentException(env, "invalid field: groups");
-            return;
+            jclass newExcCls =
+                (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+            if (newExcCls == 0) {
+                /* Unable to find the new exception class, give up. */
+                return;
+            }
+            (*env)->ThrowNew(env, newExcCls, "invalid field: username");
         }
 
         jgroups = (*env)->NewLongArray(env, numSuppGroups);
-        if (jgroups == NULL)
-            return;
         jgroupsAsArray = (*env)->GetLongArrayElements(env, jgroups, 0);
-        if (jgroupsAsArray == NULL)
-            return;
         for (i = 0; i < numSuppGroups; i++)
             jgroupsAsArray[i] = groups[i];
         (*env)->ReleaseLongArrayElements(env, jgroups, jgroupsAsArray, 0);
diff --git a/jdk/src/solaris/native/com/sun/security/auth/module/Unix.c b/jdk/src/solaris/native/com/sun/security/auth/module/Unix.c
index e4db557..394ef7c 100644
--- a/jdk/src/solaris/native/com/sun/security/auth/module/Unix.c
+++ b/jdk/src/solaris/native/com/sun/security/auth/module/Unix.c
@@ -60,7 +60,7 @@
     groups = (gid_t *)calloc(numSuppGroups, sizeof(gid_t));
     if (groups == NULL) {
         jclass cls = (*env)->FindClass(env,"java/lang/OutOfMemoryError");
-        if (cls != NULL)
+        if(cls != 0)
             (*env)->ThrowNew(env, cls, NULL);
         return;
     }
@@ -90,8 +90,6 @@
             goto cleanUpAndReturn;
 
         jstr = (*env)->NewStringUTF(env, pwd->pw_name);
-        if (jstr == NULL)
-            goto cleanUpAndReturn;
         (*env)->SetObjectField(env, obj, userNameID, jstr);
 
         (*env)->SetLongField(env, obj, userID, pwd->pw_uid);
@@ -99,11 +97,7 @@
         (*env)->SetLongField(env, obj, groupID, pwd->pw_gid);
 
         jgroups = (*env)->NewLongArray(env, numSuppGroups);
-        if (jgroups == NULL)
-            goto cleanUpAndReturn;
         jgroupsAsArray = (*env)->GetLongArrayElements(env, jgroups, 0);
-        if (jgroupsAsArray == NULL)
-            goto cleanUpAndReturn;
         for (i = 0; i < numSuppGroups; i++)
             jgroupsAsArray[i] = groups[i];
         (*env)->ReleaseLongArrayElements(env, jgroups, jgroupsAsArray, 0);
diff --git a/jdk/src/solaris/native/java/io/FileDescriptor_md.c b/jdk/src/solaris/native/java/io/FileDescriptor_md.c
index ba353cb..7147a14 100644
--- a/jdk/src/solaris/native/java/io/FileDescriptor_md.c
+++ b/jdk/src/solaris/native/java/io/FileDescriptor_md.c
@@ -23,11 +23,9 @@
  * questions.
  */
 
-#include "jni.h"
-#include "jni_util.h"
 #include "jvm.h"
-
 #include "io_util_md.h"
+
 #include "java_io_FileDescriptor.h"
 
 /*******************************************************************/
@@ -43,7 +41,7 @@
 
 JNIEXPORT void JNICALL
 Java_java_io_FileDescriptor_initIDs(JNIEnv *env, jclass fdClass) {
-    CHECK_NULL(IO_fd_fdID = (*env)->GetFieldID(env, fdClass, "fd", "I"));
+    IO_fd_fdID = (*env)->GetFieldID(env, fdClass, "fd", "I");
 }
 
 /**************************************************************
diff --git a/jdk/src/solaris/native/java/lang/ProcessEnvironment_md.c b/jdk/src/solaris/native/java/lang/ProcessEnvironment_md.c
index 46ccc5d..d692d38 100644
--- a/jdk/src/solaris/native/java/lang/ProcessEnvironment_md.c
+++ b/jdk/src/solaris/native/java/lang/ProcessEnvironment_md.c
@@ -53,7 +53,6 @@
     jsize i, j;
     jobjectArray result;
     jclass byteArrCls = (*env)->FindClass(env, "[B");
-    CHECK_NULL_RETURN(byteArrCls, NULL);
 
     for (i = 0; environ[i]; i++) {
         /* Ignore corrupted environment variables */
@@ -62,7 +61,7 @@
     }
 
     result = (*env)->NewObjectArray(env, 2*count, byteArrCls, 0);
-    CHECK_NULL_RETURN(result, NULL);
+    if (result == NULL) return NULL;
 
     for (i = 0, j = 0; environ[i]; i++) {
         const char * varEnd = strchr(environ[i], '=');
@@ -73,9 +72,9 @@
             jsize varLength = varEnd - environ[i];
             jsize valLength = strlen(valBeg);
             var = (*env)->NewByteArray(env, varLength);
-            CHECK_NULL_RETURN(var, NULL);
+            if (var == NULL) return NULL;
             val = (*env)->NewByteArray(env, valLength);
-            CHECK_NULL_RETURN(val, NULL);
+            if (val == NULL) return NULL;
             (*env)->SetByteArrayRegion(env, var, 0, varLength,
                                        (jbyte*) environ[i]);
             (*env)->SetByteArrayRegion(env, val, 0, valLength,
diff --git a/jdk/src/solaris/native/java/lang/UNIXProcess_md.c b/jdk/src/solaris/native/java/lang/UNIXProcess_md.c
index 9b510ad..7df5d59 100644
--- a/jdk/src/solaris/native/java/lang/UNIXProcess_md.c
+++ b/jdk/src/solaris/native/java/lang/UNIXProcess_md.c
@@ -206,7 +206,6 @@
 Java_java_lang_UNIXProcess_init(JNIEnv *env, jclass clazz)
 {
     parentPathv = effectivePathv(env);
-    CHECK_NULL(parentPathv);
     setSIGCHLDHandler(env);
 }
 
diff --git a/jdk/src/solaris/native/java/lang/java_props_md.c b/jdk/src/solaris/native/java/lang/java_props_md.c
index df55fd3..1830b20 100644
--- a/jdk/src/solaris/native/java/lang/java_props_md.c
+++ b/jdk/src/solaris/native/java/lang/java_props_md.c
@@ -546,9 +546,6 @@
     sprops.display_country = sprops.country;
     sprops.display_variant = sprops.variant;
 
-    /* ParseLocale failed with OOME */
-    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
-
 #ifdef MACOSX
     sprops.sun_jnu_encoding = "UTF-8";
 #else
diff --git a/jdk/src/solaris/native/java/net/ExtendedOptionsImpl.c b/jdk/src/solaris/native/java/net/ExtendedOptionsImpl.c
index 0e0e3a0..8b43e3d 100644
--- a/jdk/src/solaris/native/java/net/ExtendedOptionsImpl.c
+++ b/jdk/src/solaris/native/java/net/ExtendedOptionsImpl.c
@@ -88,7 +88,6 @@
     /* SocketFlow fields */
 
     c = (*env)->FindClass(env, "jdk/net/SocketFlow");
-    CHECK_NULL(c);
 
     /* status */
 
diff --git a/jdk/src/solaris/native/java/net/Inet4AddressImpl.c b/jdk/src/solaris/native/java/net/Inet4AddressImpl.c
index ec4f97d..c8fb987 100644
--- a/jdk/src/solaris/native/java/net/Inet4AddressImpl.c
+++ b/jdk/src/solaris/native/java/net/Inet4AddressImpl.c
@@ -51,6 +51,29 @@
 #define HAS_GLIBC_GETHOSTBY_R   1
 #endif
 
+static jclass ni_iacls;
+static jclass ni_ia4cls;
+static jmethodID ni_ia4ctrID;
+
+static jboolean initializeInetClasses(JNIEnv *env)
+{
+    static int initialized = 0;
+    if (!initialized) {
+        ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
+        CHECK_NULL_RETURN(ni_iacls, JNI_FALSE);
+        ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
+        CHECK_NULL_RETURN(ni_iacls, JNI_FALSE);
+        ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
+        CHECK_NULL_RETURN(ni_ia4cls, JNI_FALSE);
+        ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
+        CHECK_NULL_RETURN(ni_ia4cls, JNI_FALSE);
+        ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
+        CHECK_NULL_RETURN(ni_ia4ctrID, JNI_FALSE);
+        initialized = 1;
+    }
+    return JNI_TRUE;
+}
+
 
 #if defined(_ALLBSD_SOURCE) && !defined(HAS_GLIBC_GETHOSTBY_R)
 extern jobjectArray lookupIfLocalhost(JNIEnv *env, const char *hostname, jboolean includeV6);
@@ -124,8 +147,8 @@
     int getaddrinfo_error=0;
     struct addrinfo hints, *res, *resNew = NULL;
 
-    initInetAddressIDs(env);
-    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+    if (!initializeInetClasses(env))
+        return NULL;
 
     if (IS_NULL(host)) {
         JNU_ThrowNullPointerException(env, "host is null");
@@ -219,7 +242,7 @@
           goto cleanupAndReturn;
         }
 
-        ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);
+        ret = (*env)->NewObjectArray(env, retLen, ni_iacls, NULL);
         if (IS_NULL(ret)) {
             /* we may have memory to free at the end of this */
             goto cleanupAndReturn;
@@ -229,7 +252,7 @@
             /* We need 4 bytes to store ipv4 address; */
             int len = 4;
 
-            jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+            jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
             if (IS_NULL(iaObj)) {
                 /* we may have memory to free at the end of this */
                 ret = NULL;
@@ -385,8 +408,8 @@
     int error = 0;
     struct addrinfo hints, *res, *resNew = NULL;
 
-    initInetAddressIDs(env);
-    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+    if (!initializeInetClasses(env))
+        return NULL;
 
     if (IS_NULL(host)) {
         JNU_ThrowNullPointerException(env, "host is null");
@@ -464,7 +487,7 @@
         retLen = i;
         iterator = resNew;
 
-        ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);
+        ret = (*env)->NewObjectArray(env, retLen, ni_iacls, NULL);
 
         if (IS_NULL(ret)) {
             /* we may have memory to free at the end of this */
@@ -473,7 +496,7 @@
 
         i = 0;
         while (iterator != NULL) {
-            jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+            jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
             if (IS_NULL(iaObj)) {
                 ret = NULL;
                 goto cleanupAndReturn;
diff --git a/jdk/src/solaris/native/java/net/Inet6AddressImpl.c b/jdk/src/solaris/native/java/net/Inet6AddressImpl.c
index e67e25a..9850bb3 100644
--- a/jdk/src/solaris/native/java/net/Inet6AddressImpl.c
+++ b/jdk/src/solaris/native/java/net/Inet6AddressImpl.c
@@ -117,6 +117,44 @@
     return (*env)->NewStringUTF(env, hostname);
 }
 
+static jclass ni_iacls;
+static jclass ni_ia4cls;
+static jclass ni_ia6cls;
+static jmethodID ni_ia4ctrID;
+static jmethodID ni_ia6ctrID;
+static jboolean preferIPv6Address;
+
+static jboolean initializeInetClasses(JNIEnv *env)
+{
+    jfieldID ni_preferIPv6AddressID;
+    static int initialized = 0;
+    if (!initialized) {
+        ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
+        CHECK_NULL_RETURN(ni_iacls, JNI_FALSE);
+        ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
+        CHECK_NULL_RETURN(ni_iacls, JNI_FALSE);
+        ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
+        CHECK_NULL_RETURN(ni_ia4cls, JNI_FALSE);
+        ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
+        CHECK_NULL_RETURN(ni_ia4cls, JNI_FALSE);
+        ni_ia6cls = (*env)->FindClass(env, "java/net/Inet6Address");
+        CHECK_NULL_RETURN(ni_ia6cls, JNI_FALSE);
+        ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
+        CHECK_NULL_RETURN(ni_ia6cls, JNI_FALSE);
+        ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
+        CHECK_NULL_RETURN(ni_ia4ctrID, JNI_FALSE);
+        ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
+        CHECK_NULL_RETURN(ni_ia6ctrID, JNI_FALSE);
+        ni_preferIPv6AddressID =
+            (*env)->GetStaticFieldID(env, ni_iacls, "preferIPv6Address", "Z");
+        CHECK_NULL_RETURN(ni_preferIPv6AddressID, JNI_FALSE);
+        preferIPv6Address =
+            (*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID);
+        initialized = 1;
+    }
+    return JNI_TRUE;
+}
+
 #ifdef MACOSX
 /* also called from Inet4AddressImpl.c */
 __private_extern__ jobjectArray
@@ -131,8 +169,9 @@
     jboolean includeLoopback = JNI_FALSE;
     jobject name;
 
-    initInetAddressIDs(env);
-    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+    // Make sure static variables we need are set.
+    if (!initializeInetClasses(env))
+        return NULL;
 
     /* If the requested name matches this host's hostname, return IP addresses
      * from all attached interfaces. (#2844683 et al) This prevents undesired
@@ -195,10 +234,10 @@
     /* Create and fill the Java array. */
     int arraySize = addrs4 + addrs6 -
         (includeLoopback ? 0 : (numV4Loopbacks + numV6Loopbacks));
-    result = (*env)->NewObjectArray(env, arraySize, ia_class, NULL);
+    result = (*env)->NewObjectArray(env, arraySize, ni_iacls, NULL);
     if (!result) goto done;
 
-    if ((*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID)) {
+    if (preferIPv6Address) {
         i = includeLoopback ? addrs6 : (addrs6 - numV6Loopbacks);
         j = 0;
     } else {
@@ -262,8 +301,8 @@
     struct addrinfo hints, *res, *resNew = NULL;
 #endif /* AF_INET6 */
 
-    initInetAddressIDs(env);
-    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+    if (!initializeInetClasses(env))
+        return NULL;
 
     if (IS_NULL(host)) {
         JNU_ThrowNullPointerException(env, "host is null");
@@ -390,14 +429,14 @@
         retLen = i;
         iterator = resNew;
 
-        ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);
+        ret = (*env)->NewObjectArray(env, retLen, ni_iacls, NULL);
 
         if (IS_NULL(ret)) {
             /* we may have memory to free at the end of this */
             goto cleanupAndReturn;
         }
 
-        if ((*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID)) {
+        if (preferIPv6Address) {
             /* AF_INET addresses will be offset by inet6Count */
             inetIndex = inet6Count;
             inet6Index = 0;
@@ -410,7 +449,7 @@
         while (iterator != NULL) {
             int ret1;
             if (iterator->ai_family == AF_INET) {
-                jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+                jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
                 if (IS_NULL(iaObj)) {
                     ret = NULL;
                     goto cleanupAndReturn;
@@ -422,7 +461,7 @@
             } else if (iterator->ai_family == AF_INET6) {
                 jint scope = 0;
 
-                jobject iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
+                jobject iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
                 if (IS_NULL(iaObj)) {
                     ret = NULL;
                     goto cleanupAndReturn;
@@ -516,7 +555,6 @@
 
     if (!error) {
         ret = (*env)->NewStringUTF(env, host);
-        CHECK_NULL_RETURN(ret, NULL);
     }
 #endif /* AF_INET6 */
 
diff --git a/jdk/src/solaris/native/java/net/NetworkInterface.c b/jdk/src/solaris/native/java/net/NetworkInterface.c
index 89a4e4f..1788944 100644
--- a/jdk/src/solaris/native/java/net/NetworkInterface.c
+++ b/jdk/src/solaris/native/java/net/NetworkInterface.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2000, 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
@@ -23,8 +23,12 @@
  * questions.
  */
 
+
 #include <errno.h>
 #include <strings.h>
+#if defined(_ALLBSD_SOURCE) && defined(__OpenBSD__)
+#include <sys/types.h>
+#endif
 #include <netinet/in.h>
 #include <stdlib.h>
 #include <string.h>
@@ -34,15 +38,16 @@
 #include <net/if.h>
 #include <net/if_arp.h>
 
-#if defined(__solaris__)
+#ifdef __solaris__
 #include <sys/dlpi.h>
 #include <fcntl.h>
 #include <stropts.h>
 #include <sys/sockio.h>
 #endif
 
-#if defined(__linux__)
+#ifdef __linux__
 #include <sys/ioctl.h>
+#include <bits/ioctls.h>
 #include <sys/utsname.h>
 #include <stdio.h>
 #endif
@@ -54,6 +59,10 @@
 #include <sys/kinfo.h>
 #endif
 
+#ifdef __linux__
+#define _PATH_PROCNET_IFINET6           "/proc/net/if_inet6"
+#endif
+
 #if defined(_ALLBSD_SOURCE)
 #include <sys/param.h>
 #include <sys/ioctl.h>
@@ -71,30 +80,6 @@
 #include "jni_util.h"
 #include "net_util.h"
 
-#if defined(__linux__)
-    #define _PATH_PROCNET_IFINET6 "/proc/net/if_inet6"
-#elif defined(__solaris__)
-    #ifndef SIOCGLIFHWADDR
-        #define SIOCGLIFHWADDR _IOWR('i', 192, struct lifreq)
-    #endif
-    #define DEV_PREFIX "/dev/"
-#endif
-
-#ifdef LIFNAMSIZ
-    #define IFNAMESIZE LIFNAMSIZ
-#else
-    #define IFNAMESIZE IFNAMSIZ
-#endif
-
-#define CHECKED_MALLOC3(_pointer, _type, _size) \
-    do { \
-        _pointer = (_type)malloc(_size); \
-        if (_pointer == NULL) { \
-            JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed"); \
-            return ifs; /* return untouched list */ \
-        } \
-    } while(0)
-
 typedef struct _netaddr  {
     struct sockaddr *addr;
     struct sockaddr *brdcast;
@@ -133,7 +118,12 @@
 jfieldID ni_defaultIndexID;
 jmethodID ni_ctrID;
 
+static jclass ni_iacls;
+static jclass ni_ia4cls;
+static jclass ni_ia6cls;
 static jclass ni_ibcls;
+static jmethodID ni_ia4ctrID;
+static jmethodID ni_ia6ctrID;
 static jmethodID ni_ibctrID;
 static jfieldID ni_ibaddressID;
 static jfieldID ni_ib4broadcastID;
@@ -146,31 +136,35 @@
 static netif  *enumInterfaces(JNIEnv *env);
 static netif  *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs);
 
-#if defined(AF_INET6)
+#ifdef AF_INET6
 static netif  *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs);
 #endif
 
-static netif  *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
-                     struct sockaddr *ifr_addrP,
-                     struct sockaddr *ifr_broadaddrP,
-                     int family, short prefix);
+static netif  *addif(JNIEnv *env, int sock, const char * if_name, netif *ifs, struct sockaddr* ifr_addrP, int family, short prefix);
 static void    freeif(netif *ifs);
 
 static int     openSocket(JNIEnv *env, int proto);
 static int     openSocketWithFallback(JNIEnv *env, const char *ifname);
 
-static short   translateIPv4AddressToPrefix(struct sockaddr_in *addr);
-static short   translateIPv6AddressToPrefix(struct sockaddr_in6 *addr);
 
+static struct  sockaddr *getBroadcast(JNIEnv *env, int sock, const char *name, struct sockaddr *brdcast_store);
+static short   getSubnet(JNIEnv *env, int sock, const char *ifname);
 static int     getIndex(int sock, const char *ifname);
+
 static int     getFlags(int sock, const char *ifname, int *flags);
-static int     getMacAddress(JNIEnv *env, const char *ifname,
-                             const struct in_addr *addr, unsigned char *buf);
+static int     getMacAddress(JNIEnv *env, int sock,  const char* ifname, const struct in_addr* addr, unsigned char *buf);
 static int     getMTU(JNIEnv *env, int sock, const char *ifname);
 
-#if defined(__solaris__)
-static int     getMacFromDevice(JNIEnv *env, const char *ifname,
-                                unsigned char *retbuf);
+
+
+#ifdef __solaris__
+static netif *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family);
+static int    getMacFromDevice(JNIEnv *env, const char* ifname, unsigned char* retbuf);
+
+#ifndef SIOCGLIFHWADDR
+#define SIOCGLIFHWADDR  _IOWR('i', 192, struct lifreq)
+#endif
+
 #endif
 
 /******************* Java entry points *****************************/
@@ -180,89 +174,91 @@
  * Method:    init
  * Signature: ()V
  */
-JNIEXPORT void JNICALL Java_java_net_NetworkInterface_init
-  (JNIEnv *env, jclass cls)
-{
-    ni_class = (*env)->FindClass(env, "java/net/NetworkInterface");
+JNIEXPORT void JNICALL
+Java_java_net_NetworkInterface_init(JNIEnv *env, jclass cls) {
+    ni_class = (*env)->FindClass(env,"java/net/NetworkInterface");
     CHECK_NULL(ni_class);
     ni_class = (*env)->NewGlobalRef(env, ni_class);
     CHECK_NULL(ni_class);
-    ni_nameID = (*env)->GetFieldID(env, ni_class, "name", "Ljava/lang/String;");
+    ni_nameID = (*env)->GetFieldID(env, ni_class,"name", "Ljava/lang/String;");
     CHECK_NULL(ni_nameID);
     ni_indexID = (*env)->GetFieldID(env, ni_class, "index", "I");
     CHECK_NULL(ni_indexID);
-    ni_addrsID = (*env)->GetFieldID(env, ni_class, "addrs",
-                                    "[Ljava/net/InetAddress;");
+    ni_addrsID = (*env)->GetFieldID(env, ni_class, "addrs", "[Ljava/net/InetAddress;");
     CHECK_NULL(ni_addrsID);
-    ni_bindsID = (*env)->GetFieldID(env, ni_class, "bindings",
-                                    "[Ljava/net/InterfaceAddress;");
+    ni_bindsID = (*env)->GetFieldID(env, ni_class, "bindings", "[Ljava/net/InterfaceAddress;");
     CHECK_NULL(ni_bindsID);
-    ni_descID = (*env)->GetFieldID(env, ni_class, "displayName",
-                                   "Ljava/lang/String;");
+    ni_descID = (*env)->GetFieldID(env, ni_class, "displayName", "Ljava/lang/String;");
     CHECK_NULL(ni_descID);
     ni_virutalID = (*env)->GetFieldID(env, ni_class, "virtual", "Z");
     CHECK_NULL(ni_virutalID);
-    ni_childsID = (*env)->GetFieldID(env, ni_class, "childs",
-                                     "[Ljava/net/NetworkInterface;");
+    ni_childsID = (*env)->GetFieldID(env, ni_class, "childs", "[Ljava/net/NetworkInterface;");
     CHECK_NULL(ni_childsID);
-    ni_parentID = (*env)->GetFieldID(env, ni_class, "parent",
-                                     "Ljava/net/NetworkInterface;");
+    ni_parentID = (*env)->GetFieldID(env, ni_class, "parent", "Ljava/net/NetworkInterface;");
     CHECK_NULL(ni_parentID);
     ni_ctrID = (*env)->GetMethodID(env, ni_class, "<init>", "()V");
     CHECK_NULL(ni_ctrID);
+
+    ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
+    CHECK_NULL(ni_iacls);
+    ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
+    CHECK_NULL(ni_iacls);
+    ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
+    CHECK_NULL(ni_ia4cls);
+    ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
+    CHECK_NULL(ni_ia4cls);
+    ni_ia6cls = (*env)->FindClass(env, "java/net/Inet6Address");
+    CHECK_NULL(ni_ia6cls);
+    ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
+    CHECK_NULL(ni_ia6cls);
     ni_ibcls = (*env)->FindClass(env, "java/net/InterfaceAddress");
     CHECK_NULL(ni_ibcls);
     ni_ibcls = (*env)->NewGlobalRef(env, ni_ibcls);
     CHECK_NULL(ni_ibcls);
+    ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
+    CHECK_NULL(ni_ia4ctrID);
+    ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
+    CHECK_NULL(ni_ia6ctrID);
     ni_ibctrID = (*env)->GetMethodID(env, ni_ibcls, "<init>", "()V");
     CHECK_NULL(ni_ibctrID);
-    ni_ibaddressID = (*env)->GetFieldID(env, ni_ibcls, "address",
-                                        "Ljava/net/InetAddress;");
+    ni_ibaddressID = (*env)->GetFieldID(env, ni_ibcls, "address", "Ljava/net/InetAddress;");
     CHECK_NULL(ni_ibaddressID);
-    ni_ib4broadcastID = (*env)->GetFieldID(env, ni_ibcls, "broadcast",
-                                           "Ljava/net/Inet4Address;");
+    ni_ib4broadcastID = (*env)->GetFieldID(env, ni_ibcls, "broadcast", "Ljava/net/Inet4Address;");
     CHECK_NULL(ni_ib4broadcastID);
     ni_ib4maskID = (*env)->GetFieldID(env, ni_ibcls, "maskLength", "S");
     CHECK_NULL(ni_ib4maskID);
-    ni_defaultIndexID = (*env)->GetStaticFieldID(env, ni_class, "defaultIndex",
-                                                 "I");
-    CHECK_NULL(ni_defaultIndexID);
-
-    initInetAddressIDs(env);
+    ni_defaultIndexID = (*env)->GetStaticFieldID(env, ni_class, "defaultIndex", "I");
 }
 
+
 /*
  * Class:     java_net_NetworkInterface
  * Method:    getByName0
  * Signature: (Ljava/lang/String;)Ljava/net/NetworkInterface;
  */
 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByName0
-  (JNIEnv *env, jclass cls, jstring name)
-{
+    (JNIEnv *env, jclass cls, jstring name) {
+
     netif *ifs, *curr;
     jboolean isCopy;
     const char* name_utf;
     jobject obj = NULL;
 
-    if (name != NULL) {
-        name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
-    } else {
-        JNU_ThrowNullPointerException(env, "network interface name is NULL");
-        return NULL;
-    }
-
-    if (name_utf == NULL) {
-        if (!(*env)->ExceptionCheck(env))
-            JNU_ThrowOutOfMemoryError(env, NULL);
-        return NULL;
-    }
-
     ifs = enumInterfaces(env);
     if (ifs == NULL) {
         return NULL;
     }
 
-    // search the list of interfaces based on name
+    name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
+    if (name_utf == NULL) {
+       if (!(*env)->ExceptionCheck(env))
+           JNU_ThrowOutOfMemoryError(env, NULL);
+       freeif(ifs);
+       return NULL;
+    }
+    /*
+     * Search the list of interface based on name
+     */
     curr = ifs;
     while (curr != NULL) {
         if (strcmp(name_utf, curr->name) == 0) {
@@ -271,26 +267,27 @@
         curr = curr->next;
     }
 
-    // if found create a NetworkInterface
-    if (curr != NULL) {
+    /* if found create a NetworkInterface */
+    if (curr != NULL) {;
         obj = createNetworkInterface(env, curr);
     }
 
-    // release the UTF string and interface list
+    /* release the UTF string and interface list */
     (*env)->ReleaseStringUTFChars(env, name, name_utf);
     freeif(ifs);
 
     return obj;
 }
 
+
 /*
  * Class:     java_net_NetworkInterface
  * Method:    getByIndex0
  * Signature: (Ljava/lang/String;)Ljava/net/NetworkInterface;
  */
 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByIndex0
-  (JNIEnv *env, jclass cls, jint index)
-{
+    (JNIEnv *env, jclass cls, jint index) {
+
     netif *ifs, *curr;
     jobject obj = NULL;
 
@@ -303,7 +300,9 @@
         return NULL;
     }
 
-    // search the list of interfaces based on index
+    /*
+     * Search the list of interface based on index
+     */
     curr = ifs;
     while (curr != NULL) {
         if (index == curr->index) {
@@ -312,14 +311,12 @@
         curr = curr->next;
     }
 
-    // if found create a NetworkInterface
-    if (curr != NULL) {
+    /* if found create a NetworkInterface */
+    if (curr != NULL) {;
         obj = createNetworkInterface(env, curr);
     }
 
-    // release the interface list
     freeif(ifs);
-
     return obj;
 }
 
@@ -329,14 +326,16 @@
  * Signature: (Ljava/net/InetAddress;)Ljava/net/NetworkInterface;
  */
 JNIEXPORT jobject JNICALL Java_java_net_NetworkInterface_getByInetAddress0
-  (JNIEnv *env, jclass cls, jobject iaObj)
-{
+    (JNIEnv *env, jclass cls, jobject iaObj) {
+
     netif *ifs, *curr;
-#if defined(AF_INET6)
+
+#ifdef AF_INET6
     int family = (getInetAddress_family(env, iaObj) == IPv4) ? AF_INET : AF_INET6;
 #else
     int family =  AF_INET;
 #endif
+
     jobject obj = NULL;
     jboolean match = JNI_FALSE;
 
@@ -349,13 +348,14 @@
     while (curr != NULL) {
         netaddr *addrP = curr->addr;
 
-        // iterate through each address on the interface
+        /*
+         * Iterate through each address on the interface
+         */
         while (addrP != NULL) {
 
             if (family == addrP->family) {
                 if (family == AF_INET) {
-                    int address1 = htonl(
-                        ((struct sockaddr_in *)addrP->addr)->sin_addr.s_addr);
+                    int address1 = htonl(((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr);
                     int address2 = getInetAddress_addr(env, iaObj);
 
                     if (address1 == address2) {
@@ -363,10 +363,10 @@
                         break;
                     }
                 }
-#if defined(AF_INET6)
+
+#ifdef AF_INET6
                 if (family == AF_INET6) {
-                    jbyte *bytes = (jbyte *)&(
-                        ((struct sockaddr_in6*)addrP->addr)->sin6_addr);
+                    jbyte *bytes = (jbyte *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr);
                     jbyte caddr[16];
                     int i;
                     getInet6Address_ipaddress(env, iaObj, (char *)caddr);
@@ -383,6 +383,7 @@
                     }
                 }
 #endif
+
             }
 
             if (match) {
@@ -397,25 +398,24 @@
         curr = curr->next;
     }
 
-    // if found create a NetworkInterface
-    if (match) {
+    /* if found create a NetworkInterface */
+    if (match) {;
         obj = createNetworkInterface(env, curr);
     }
 
-    // release the interface list
     freeif(ifs);
-
     return obj;
 }
 
+
 /*
  * Class:     java_net_NetworkInterface
  * Method:    getAll
  * Signature: ()[Ljava/net/NetworkInterface;
  */
 JNIEXPORT jobjectArray JNICALL Java_java_net_NetworkInterface_getAll
-  (JNIEnv *env, jclass cls)
-{
+    (JNIEnv *env, jclass cls) {
+
     netif *ifs, *curr;
     jobjectArray netIFArr;
     jint arr_index, ifCount;
@@ -425,7 +425,7 @@
         return NULL;
     }
 
-    // count the interfaces
+    /* count the interface */
     ifCount = 0;
     curr = ifs;
     while (curr != NULL) {
@@ -433,15 +433,17 @@
         curr = curr->next;
     }
 
-    // allocate a NetworkInterface array
+    /* allocate a NetworkInterface array */
     netIFArr = (*env)->NewObjectArray(env, ifCount, cls, NULL);
     if (netIFArr == NULL) {
         freeif(ifs);
         return NULL;
     }
 
-    // iterate through the interfaces, create a NetworkInterface instance
-    // for each array element and populate the object
+    /*
+     * Iterate through the interfaces, create a NetworkInterface instance
+     * for each array element and populate the object.
+     */
     curr = ifs;
     arr_index = 0;
     while (curr != NULL) {
@@ -453,26 +455,23 @@
             return NULL;
         }
 
-        // put the NetworkInterface into the array
+        /* put the NetworkInterface into the array */
         (*env)->SetObjectArrayElement(env, netIFArr, arr_index++, netifObj);
 
         curr = curr->next;
     }
 
-    // release the interface list
     freeif(ifs);
-
     return netIFArr;
 }
 
+
 /*
  * Class:     java_net_NetworkInterface
  * Method:    isUp0
  * Signature: (Ljava/lang/String;I)Z
  */
-JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isUp0
-  (JNIEnv *env, jclass cls, jstring name, jint index)
-{
+JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isUp0(JNIEnv *env, jclass cls, jstring name, jint index) {
     int ret = getFlags0(env, name);
     return ((ret & IFF_UP) && (ret & IFF_RUNNING)) ? JNI_TRUE :  JNI_FALSE;
 }
@@ -482,9 +481,7 @@
  * Method:    isP2P0
  * Signature: (Ljava/lang/String;I)Z
  */
-JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isP2P0
-  (JNIEnv *env, jclass cls, jstring name, jint index)
-{
+JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isP2P0(JNIEnv *env, jclass cls, jstring name, jint index) {
     int ret = getFlags0(env, name);
     return (ret & IFF_POINTOPOINT) ? JNI_TRUE :  JNI_FALSE;
 }
@@ -494,9 +491,7 @@
  * Method:    isLoopback0
  * Signature: (Ljava/lang/String;I)Z
  */
-JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isLoopback0
-  (JNIEnv *env, jclass cls, jstring name, jint index)
-{
+JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_isLoopback0(JNIEnv *env, jclass cls, jstring name, jint index) {
     int ret = getFlags0(env, name);
     return (ret & IFF_LOOPBACK) ? JNI_TRUE :  JNI_FALSE;
 }
@@ -506,9 +501,7 @@
  * Method:    supportsMulticast0
  * Signature: (Ljava/lang/String;I)Z
  */
-JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_supportsMulticast0
-  (JNIEnv *env, jclass cls, jstring name, jint index)
-{
+JNIEXPORT jboolean JNICALL Java_java_net_NetworkInterface_supportsMulticast0(JNIEnv *env, jclass cls, jstring name, jint index) {
     int ret = getFlags0(env, name);
     return (ret & IFF_MULTICAST) ? JNI_TRUE :  JNI_FALSE;
 }
@@ -518,54 +511,54 @@
  * Method:    getMacAddr0
  * Signature: ([bLjava/lang/String;I)[b
  */
-JNIEXPORT jbyteArray JNICALL Java_java_net_NetworkInterface_getMacAddr0
-  (JNIEnv *env, jclass cls, jbyteArray addrArray, jstring name, jint index)
-{
+JNIEXPORT jbyteArray JNICALL Java_java_net_NetworkInterface_getMacAddr0(JNIEnv *env, jclass class, jbyteArray addrArray, jstring name, jint index) {
     jint addr;
     jbyte caddr[4];
     struct in_addr iaddr;
     jbyteArray ret = NULL;
     unsigned char mac[16];
     int len;
+    int sock;
     jboolean isCopy;
-    const char *name_utf;
+    const char* name_utf;
 
-    if (name != NULL) {
-        name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
-    } else {
-        JNU_ThrowNullPointerException(env, "network interface name is NULL");
-        return NULL;
-    }
-
+    name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
     if (name_utf == NULL) {
-        if (!(*env)->ExceptionCheck(env))
-            JNU_ThrowOutOfMemoryError(env, NULL);
-        return NULL;
+       if (!(*env)->ExceptionCheck(env))
+           JNU_ThrowOutOfMemoryError(env, NULL);
+       return NULL;
     }
+    if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
+       (*env)->ReleaseStringUTFChars(env, name, name_utf);
+       return NULL;
+    }
+
 
     if (!IS_NULL(addrArray)) {
-        (*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);
-        iaddr.s_addr = htonl(addr);
-        len = getMacAddress(env, name_utf, &iaddr, mac);
+       (*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);
+       iaddr.s_addr = htonl(addr);
+       len = getMacAddress(env, sock, name_utf, &iaddr, mac);
     } else {
-        len = getMacAddress(env, name_utf, NULL, mac);
+       len = getMacAddress(env, sock, name_utf,NULL, mac);
     }
-
     if (len > 0) {
-        ret = (*env)->NewByteArray(env, len);
-        if (!IS_NULL(ret)) {
-            (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *)(mac));
-        }
+       ret = (*env)->NewByteArray(env, len);
+       if (IS_NULL(ret)) {
+          /* we may have memory to free at the end of this */
+          goto fexit;
+       }
+       (*env)->SetByteArrayRegion(env, ret, 0, len, (jbyte *) (mac));
     }
+ fexit:
+   /* release the UTF string and interface list */
+   (*env)->ReleaseStringUTFChars(env, name, name_utf);
 
-    // release the UTF string and interface list
-    (*env)->ReleaseStringUTFChars(env, name, name_utf);
-
-    return ret;
+   close(sock);
+   return ret;
 }
 
 /*
@@ -573,11 +566,11 @@
  * Method:      getMTU0
  * Signature:   ([bLjava/lang/String;I)I
  */
-JNIEXPORT jint JNICALL Java_java_net_NetworkInterface_getMTU0
-  (JNIEnv *env, jclass cls, jstring name, jint index)
-{
+
+JNIEXPORT jint JNICALL Java_java_net_NetworkInterface_getMTU0(JNIEnv *env, jclass class, jstring name, jint index) {
     jboolean isCopy;
-    int sock, ret = -1;
+    int ret = -1;
+    int sock;
     const char* name_utf = NULL;
 
     if (name != NULL) {
@@ -586,16 +579,15 @@
         JNU_ThrowNullPointerException(env, "network interface name is NULL");
         return ret;
     }
-
     if (name_utf == NULL) {
-        if (!(*env)->ExceptionCheck(env))
-            JNU_ThrowOutOfMemoryError(env, NULL);
-        return ret;
+       if (!(*env)->ExceptionCheck(env))
+           JNU_ThrowOutOfMemoryError(env, NULL);
+       return ret;
     }
 
-    if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
-        (*env)->ReleaseStringUTFChars(env, name, name_utf);
-        return JNI_FALSE;
+    if ((sock =openSocketWithFallback(env, name_utf)) < 0) {
+       (*env)->ReleaseStringUTFChars(env, name, name_utf);
+       return JNI_FALSE;
     }
 
     ret = getMTU(env, sock, name_utf);
@@ -610,8 +602,9 @@
 
 static int getFlags0(JNIEnv *env, jstring name) {
     jboolean isCopy;
-    int ret, sock, flags = 0;
-    const char *name_utf;
+    int ret, sock;
+    const char* name_utf;
+    int flags = 0;
 
     if (name != NULL) {
         name_utf = (*env)->GetStringUTFChars(env, name, &isCopy);
@@ -619,11 +612,10 @@
         JNU_ThrowNullPointerException(env, "network interface name is NULL");
         return -1;
     }
-
     if (name_utf == NULL) {
-        if (!(*env)->ExceptionCheck(env))
-            JNU_ThrowOutOfMemoryError(env, NULL);
-        return -1;
+       if (!(*env)->ExceptionCheck(env))
+           JNU_ThrowOutOfMemoryError(env, NULL);
+       return -1;
     }
     if ((sock = openSocketWithFallback(env, name_utf)) < 0) {
         (*env)->ReleaseStringUTFChars(env, name, name_utf);
@@ -636,20 +628,22 @@
     (*env)->ReleaseStringUTFChars(env, name, name_utf);
 
     if (ret < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "getFlags() failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL  SIOCGLIFFLAGS failed");
         return -1;
     }
 
     return flags;
 }
 
+
+
+
 /*
- * Creates a NetworkInterface object, populates the name, the index, and
- * populates the InetAddress array based on the IP addresses for this
+ * Create a NetworkInterface object, populate the name and index, and
+ * populate the InetAddress array based on the IP addresses for this
  * interface.
  */
-static jobject createNetworkInterface(JNIEnv *env, netif *ifs) {
+jobject createNetworkInterface(JNIEnv *env, netif *ifs) {
     jobject netifObj;
     jobject name;
     jobjectArray addrArr;
@@ -662,7 +656,9 @@
     netif *childP;
     jobject tmp;
 
-    // create a NetworkInterface object and populate it
+    /*
+     * Create a NetworkInterface object and populate it
+     */
     netifObj = (*env)->NewObject(env, ni_class, ni_ctrID);
     CHECK_NULL_RETURN(netifObj, NULL);
     name = (*env)->NewStringUTF(env, ifs->name);
@@ -670,10 +666,11 @@
     (*env)->SetObjectField(env, netifObj, ni_nameID, name);
     (*env)->SetObjectField(env, netifObj, ni_descID, name);
     (*env)->SetIntField(env, netifObj, ni_indexID, ifs->index);
-    (*env)->SetBooleanField(env, netifObj, ni_virutalID,
-                            ifs->virtual ? JNI_TRUE : JNI_FALSE);
+    (*env)->SetBooleanField(env, netifObj, ni_virutalID, ifs->virtual ? JNI_TRUE : JNI_FALSE);
 
-    // count the number of addresses on this interface
+    /*
+     * Count the number of address on this interface
+     */
     addr_count = 0;
     addrP = ifs->addr;
     while (addrP != NULL) {
@@ -681,8 +678,10 @@
         addrP = addrP->next;
     }
 
-    // create the array of InetAddresses
-    addrArr = (*env)->NewObjectArray(env, addr_count,  ia_class, NULL);
+    /*
+     * Create the array of InetAddresses
+     */
+    addrArr = (*env)->NewObjectArray(env, addr_count,  ni_iacls, NULL);
     if (addrArr == NULL) {
         return NULL;
     }
@@ -699,40 +698,38 @@
         jobject ibObj = NULL;
 
         if (addrP->family == AF_INET) {
-            iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+            iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
             if (iaObj) {
-                setInetAddress_addr(env, iaObj, htonl(
-                    ((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr));
+                 setInetAddress_addr(env, iaObj, htonl(((struct sockaddr_in*)addrP->addr)->sin_addr.s_addr));
             } else {
                 return NULL;
             }
             ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
             if (ibObj) {
-                (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
-                if (addrP->brdcast) {
+                 (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
+                 if (addrP->brdcast) {
                     jobject ia2Obj = NULL;
-                    ia2Obj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+                    ia2Obj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
                     if (ia2Obj) {
-                        setInetAddress_addr(env, ia2Obj, htonl(
-                            ((struct sockaddr_in*)addrP->brdcast)->sin_addr.s_addr));
-                        (*env)->SetObjectField(env, ibObj, ni_ib4broadcastID, ia2Obj);
+                       setInetAddress_addr(env, ia2Obj, htonl(((struct sockaddr_in*)addrP->brdcast)->sin_addr.s_addr));
+                       (*env)->SetObjectField(env, ibObj, ni_ib4broadcastID, ia2Obj);
                     } else {
                         return NULL;
                     }
-                }
-                (*env)->SetShortField(env, ibObj, ni_ib4maskID, addrP->mask);
-                (*env)->SetObjectArrayElement(env, bindArr, bind_index++, ibObj);
+                 }
+                 (*env)->SetShortField(env, ibObj, ni_ib4maskID, addrP->mask);
+                 (*env)->SetObjectArrayElement(env, bindArr, bind_index++, ibObj);
             } else {
                 return NULL;
             }
         }
-#if defined(AF_INET6)
+
+#ifdef AF_INET6
         if (addrP->family == AF_INET6) {
             int scope=0;
-            iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
+            iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
             if (iaObj) {
-                jboolean ret = setInet6Address_ipaddress(env, iaObj,
-                    (char *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr));
+                int ret = setInet6Address_ipaddress(env, iaObj, (char *)&(((struct sockaddr_in6*)addrP->addr)->sin6_addr));
                 if (ret == JNI_FALSE) {
                     return NULL;
                 }
@@ -761,7 +758,9 @@
         addrP = addrP->next;
     }
 
-    // see if there is any virtual interface attached to this one.
+    /*
+     * See if there is any virtual interface attached to this one.
+     */
     child_count = 0;
     childP = ifs->childs;
     while (childP) {
@@ -774,23 +773,26 @@
         return NULL;
     }
 
-    // create the NetworkInterface instances for the sub-interfaces as well
+    /*
+     * Create the NetworkInterface instances for the sub-interfaces as
+     * well.
+     */
     child_index = 0;
     childP = ifs->childs;
     while(childP) {
-        tmp = createNetworkInterface(env, childP);
-        if (tmp == NULL) {
-            return NULL;
-        }
-        (*env)->SetObjectField(env, tmp, ni_parentID, netifObj);
-        (*env)->SetObjectArrayElement(env, childArr, child_index++, tmp);
-        childP = childP->next;
+      tmp = createNetworkInterface(env, childP);
+      if (tmp == NULL) {
+         return NULL;
+      }
+      (*env)->SetObjectField(env, tmp, ni_parentID, netifObj);
+      (*env)->SetObjectArrayElement(env, childArr, child_index++, tmp);
+      childP = childP->next;
     }
     (*env)->SetObjectField(env, netifObj, ni_addrsID, addrArr);
     (*env)->SetObjectField(env, netifObj, ni_bindsID, bindArr);
     (*env)->SetObjectField(env, netifObj, ni_childsID, childArr);
 
-    // return the NetworkInterface
+    /* return the NetworkInterface */
     return netifObj;
 }
 
@@ -798,51 +800,71 @@
  * Enumerates all interfaces
  */
 static netif *enumInterfaces(JNIEnv *env) {
-    netif *ifs = NULL;
+    netif *ifs;
     int sock;
 
+    /*
+     * Enumerate IPv4 addresses
+     */
+
     sock = openSocket(env, AF_INET);
     if (sock < 0 && (*env)->ExceptionOccurred(env)) {
         return NULL;
     }
 
-    // enumerate IPv4 addresses
     ifs = enumIPv4Interfaces(env, sock, NULL);
     close(sock);
 
-    // return partial list if an exception occurs in the middle of process ???
     if (ifs == NULL && (*env)->ExceptionOccurred(env)) {
         return NULL;
     }
 
-    // If IPv6 is available then enumerate IPv6 addresses.
-#if defined(AF_INET6)
-        // User can disable ipv6 explicitly by -Djava.net.preferIPv4Stack=true,
-        // so we have to call ipv6_available()
+    /* return partial list if an exception occurs in the middle of process ???*/
+
+    /*
+     * If IPv6 is available then enumerate IPv6 addresses.
+     */
+#ifdef AF_INET6
+
+        /* User can disable ipv6 explicitly by -Djava.net.preferIPv4Stack=true,
+         * so we have to call ipv6_available()
+         */
         if (ipv6_available()) {
-            sock = openSocket(env, AF_INET6);
-            if (sock < 0 && (*env)->ExceptionOccurred(env)) {
-                freeif(ifs);
-                return NULL;
-            }
 
-            ifs = enumIPv6Interfaces(env, sock, ifs);
-            close(sock);
+           sock =  openSocket(env, AF_INET6);
+           if (sock < 0 && (*env)->ExceptionOccurred(env)) {
+               freeif(ifs);
+               return NULL;
+           }
 
-            if ((*env)->ExceptionOccurred(env)) {
-                freeif(ifs);
-                return NULL;
-            }
-        }
+           ifs = enumIPv6Interfaces(env, sock, ifs);
+           close(sock);
+
+           if ((*env)->ExceptionOccurred(env)) {
+              freeif(ifs);
+              return NULL;
+           }
+
+       }
 #endif
 
     return ifs;
 }
 
+#define CHECKED_MALLOC3(_pointer,_type,_size) \
+       do{ \
+        _pointer = (_type)malloc( _size ); \
+        if (_pointer == NULL) { \
+            JNU_ThrowOutOfMemoryError(env, "Native heap allocation failed"); \
+            return ifs; /* return untouched list */ \
+        } \
+       } while(0)
+
+
 /*
- * Frees an interface list (including any attached addresses).
+ * Free an interface list (including any attached addresses)
  */
-static void freeif(netif *ifs) {
+void freeif(netif *ifs) {
     netif *currif = ifs;
     netif *child = NULL;
 
@@ -852,91 +874,117 @@
             netaddr *next = addrP->next;
             free(addrP);
             addrP = next;
-        }
+         }
 
-        // don't forget to free the sub-interfaces
-        if (currif->childs != NULL) {
-            freeif(currif->childs);
-        }
+            /*
+            * Don't forget to free the sub-interfaces.
+            */
+          if (currif->childs != NULL) {
+                freeif(currif->childs);
+          }
 
-        ifs = currif->next;
-        free(currif);
-        currif = ifs;
+          ifs = currif->next;
+          free(currif);
+          currif = ifs;
     }
 }
 
-static netif *addif(JNIEnv *env, int sock, const char *if_name, netif *ifs,
-                    struct sockaddr *ifr_addrP,
-                    struct sockaddr *ifr_broadaddrP,
-                    int family, short prefix)
+netif *addif(JNIEnv *env, int sock, const char * if_name,
+             netif *ifs, struct sockaddr* ifr_addrP, int family,
+             short prefix)
 {
     netif *currif = ifs, *parent;
     netaddr *addrP;
-    char name[IFNAMESIZE], vname[IFNAMESIZE];
-    char *name_colonP;
+
+#ifdef LIFNAMSIZ
+    int ifnam_size = LIFNAMSIZ;
+    char name[LIFNAMSIZ], vname[LIFNAMSIZ];
+#else
+    int ifnam_size = IFNAMSIZ;
+    char name[IFNAMSIZ], vname[IFNAMSIZ];
+#endif
+
+    char  *name_colonP;
+    int mask;
     int isVirtual = 0;
     int addr_size;
+    int flags = 0;
 
-    // If the interface name is a logical interface then we remove the unit
-    // number so that we have the physical interface (eg: hme0:1 -> hme0).
-    // NetworkInterface currently doesn't have any concept of physical vs.
-    // logical interfaces.
-    strncpy(name, if_name, IFNAMESIZE);
-    name[IFNAMESIZE - 1] = '\0';
+    /*
+     * If the interface name is a logical interface then we
+     * remove the unit number so that we have the physical
+     * interface (eg: hme0:1 -> hme0). NetworkInterface
+     * currently doesn't have any concept of physical vs.
+     * logical interfaces.
+     */
+    strncpy(name, if_name, ifnam_size);
+    name[ifnam_size - 1] = '\0';
     *vname = 0;
 
-    // Create and populate the netaddr node. If allocation fails
-    // return an un-updated list.
+    /*
+     * Create and populate the netaddr node. If allocation fails
+     * return an un-updated list.
+     */
+    /*Allocate for addr and brdcast at once*/
 
-    // Allocate for addr and brdcast at once
-
-#if defined(AF_INET6)
-    addr_size = (family == AF_INET) ? sizeof(struct sockaddr_in)
-                                    : sizeof(struct sockaddr_in6);
+#ifdef AF_INET6
+    addr_size = (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6);
 #else
     addr_size = sizeof(struct sockaddr_in);
 #endif
 
-    CHECKED_MALLOC3(addrP, netaddr *, sizeof(netaddr) + 2 * addr_size);
-    addrP->addr = (struct sockaddr *)((char *)addrP + sizeof(netaddr));
+    CHECKED_MALLOC3(addrP, netaddr *, sizeof(netaddr)+2*addr_size);
+    addrP->addr = (struct sockaddr *)( (char *) addrP+sizeof(netaddr) );
     memcpy(addrP->addr, ifr_addrP, addr_size);
 
     addrP->family = family;
+    addrP->brdcast = NULL;
     addrP->mask = prefix;
     addrP->next = 0;
+    if (family == AF_INET) {
+       // Deal with broadcast addr & subnet mask
+       struct sockaddr * brdcast_to = (struct sockaddr *) ((char *) addrP + sizeof(netaddr) + addr_size);
+       addrP->brdcast = getBroadcast(env, sock, name,  brdcast_to );
+       if ((*env)->ExceptionCheck(env) == JNI_TRUE) {
+           return ifs;
+       }
+       if ((mask = getSubnet(env, sock, name)) != -1) {
+           addrP->mask = mask;
+       } else if((*env)->ExceptionCheck(env)) {
+           return ifs;
+       }
+     }
 
-    // for IPv4 add broadcast address
-    if (family == AF_INET && ifr_broadaddrP != NULL) {
-        addrP->brdcast = (struct sockaddr *)
-                             ((char *)addrP + sizeof(netaddr) + addr_size);
-        memcpy(addrP->brdcast, ifr_broadaddrP, addr_size);
-    } else {
-        addrP->brdcast = NULL;
-    }
-
-    // Deal with virtual interface with colon notation e.g. eth0:1
+    /**
+     * Deal with virtual interface with colon notation e.g. eth0:1
+     */
     name_colonP = strchr(name, ':');
     if (name_colonP != NULL) {
-        int flags = 0;
-        // This is a virtual interface. If we are able to access the parent
-        // we need to create a new entry if it doesn't exist yet *and* update
-        // the 'parent' interface with the new records.
+      /**
+       * This is a virtual interface. If we are able to access the parent
+       * we need to create a new entry if it doesn't exist yet *and* update
+       * the 'parent' interface with the new records.
+       */
         *name_colonP = 0;
         if (getFlags(sock, name, &flags) < 0 || flags < 0) {
             // failed to access parent interface do not create parent.
             // We are a virtual interface with no parent.
             isVirtual = 1;
             *name_colonP = ':';
-        } else {
-            // Got access to parent, so create it if necessary.
-            // Save original name to vname and truncate name by ':'
-            memcpy(vname, name, sizeof(vname));
+        }
+        else{
+           // Got access to parent, so create it if necessary.
+           // Save original name to vname and truncate name by ':'
+            memcpy(vname, name, sizeof(vname) );
             vname[name_colonP - name] = ':';
         }
     }
 
-    // Check if this is a "new" interface. Use the interface name for
-    // matching because index isn't supported on Solaris 2.6 & 7.
+    /*
+     * Check if this is a "new" interface. Use the interface
+     * name for matching because index isn't supported on
+     * Solaris 2.6 & 7.
+     */
     while (currif != NULL) {
         if (strcmp(name, currif->name) == 0) {
             break;
@@ -944,12 +992,15 @@
         currif = currif->next;
     }
 
-    // If "new" then create a netif structure and insert it into the list.
+    /*
+     * If "new" then create an netif structure and
+     * insert it onto the list.
+     */
     if (currif == NULL) {
-         CHECKED_MALLOC3(currif, netif *, sizeof(netif) + IFNAMESIZE);
-         currif->name = (char *)currif + sizeof(netif);
-         strncpy(currif->name, name, IFNAMESIZE);
-         currif->name[IFNAMESIZE - 1] = '\0';
+         CHECKED_MALLOC3(currif, netif *, sizeof(netif) + ifnam_size);
+         currif->name = (char *) currif+sizeof(netif);
+         strncpy(currif->name, name, ifnam_size);
+         currif->name[ifnam_size - 1] = '\0';
          currif->index = getIndex(sock, name);
          currif->addr = NULL;
          currif->childs = NULL;
@@ -958,13 +1009,17 @@
          ifs = currif;
     }
 
-    // Finally insert the address on the interface
+    /*
+     * Finally insert the address on the interface
+     */
     addrP->next = currif->addr;
     currif->addr = addrP;
 
     parent = currif;
 
-    // Deal with the virtual interface now.
+    /**
+     * Let's deal with the virtual interface now.
+     */
     if (vname[0]) {
         netaddr *tmpaddr;
 
@@ -978,29 +1033,28 @@
         }
 
         if (currif == NULL) {
-            CHECKED_MALLOC3(currif, netif *, sizeof(netif) + IFNAMESIZE);
-            currif->name = (char *)currif + sizeof(netif);
-            strncpy(currif->name, vname, IFNAMESIZE);
-            currif->name[IFNAMESIZE - 1] = '\0';
+            CHECKED_MALLOC3(currif, netif *, sizeof(netif) + ifnam_size);
+            currif->name = (char *) currif + sizeof(netif);
+            strncpy(currif->name, vname, ifnam_size);
+            currif->name[ifnam_size - 1] = '\0';
             currif->index = getIndex(sock, vname);
-            currif->addr = NULL; // Need to duplicate the addr entry?
+            currif->addr = NULL;
+           /* Need to duplicate the addr entry? */
             currif->virtual = 1;
             currif->childs = NULL;
             currif->next = parent->childs;
             parent->childs = currif;
         }
 
-        CHECKED_MALLOC3(tmpaddr, netaddr *, sizeof(netaddr) + 2 * addr_size);
+        CHECKED_MALLOC3(tmpaddr, netaddr *, sizeof(netaddr)+2*addr_size);
         memcpy(tmpaddr, addrP, sizeof(netaddr));
         if (addrP->addr != NULL) {
-            tmpaddr->addr = (struct sockaddr *)
-                ((char*)tmpaddr + sizeof(netaddr));
+            tmpaddr->addr = (struct sockaddr *) ( (char*)tmpaddr + sizeof(netaddr) ) ;
             memcpy(tmpaddr->addr, addrP->addr, addr_size);
         }
 
         if (addrP->brdcast != NULL) {
-            tmpaddr->brdcast = (struct sockaddr *)
-                ((char *)tmpaddr + sizeof(netaddr) + addr_size);
+            tmpaddr->brdcast = (struct sockaddr *) ((char *) tmpaddr + sizeof(netaddr)+addr_size);
             memcpy(tmpaddr->brdcast, addrP->brdcast, addr_size);
         }
 
@@ -1011,69 +1065,19 @@
     return ifs;
 }
 
-/*
- * Determines the prefix value for an AF_INET subnet address.
+/* Open socket for further ioct calls
+ * proto is AF_INET/AF_INET6
  */
-static short translateIPv4AddressToPrefix(struct sockaddr_in *addr) {
-    short prefix = 0;
-    unsigned int mask = ntohl(addr->sin_addr.s_addr);
-    while (mask) {
-        mask <<= 1;
-        prefix++;
-    }
-    return prefix;
-}
-
-/*
- * Determines the prefix value for an AF_INET6 subnet address.
- */
-static short translateIPv6AddressToPrefix(struct sockaddr_in6 *addr) {
-    short prefix = 0;
-    u_char *addrBytes = (u_char *)&(addr->sin6_addr);
-    unsigned int byte, bit;
-
-    for (byte = 0; byte < sizeof(struct in6_addr); byte++, prefix += 8) {
-        if (addrBytes[byte] != 0xff) {
-            break;
-        }
-    }
-    if (byte != sizeof(struct in6_addr)) {
-        for (bit = 7; bit != 0; bit--, prefix++) {
-            if (!(addrBytes[byte] & (1 << bit))) {
-                break;
-            }
-        }
-        for (; bit != 0; bit--) {
-            if (addrBytes[byte] & (1 << bit)) {
-                prefix = 0;
-                break;
-            }
-        }
-        if (prefix > 0) {
-            byte++;
-            for (; byte < sizeof(struct in6_addr); byte++) {
-                if (addrBytes[byte]) {
-                    prefix = 0;
-                }
-            }
-        }
-    }
-
-    return prefix;
-}
-
-/*
- * Opens a socket for further ioct calls. proto is one of AF_INET or AF_INET6.
- */
-static int openSocket(JNIEnv *env, int proto) {
+static int  openSocket(JNIEnv *env, int proto){
     int sock;
 
     if ((sock = JVM_Socket(proto, SOCK_DGRAM, 0)) < 0) {
-        // If EPROTONOSUPPORT is returned it means we don't have
-        // support for this proto so don't throw an exception.
+        /*
+         * If EPROTONOSUPPORT is returned it means we don't have
+         * support  for this proto so don't throw an exception.
+         */
         if (errno != EPROTONOSUPPORT) {
-            NET_ThrowByNameWithLastError
-                (env, JNU_JAVANETPKG "SocketException", "Socket creation failed");
+            NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "Socket creation failed");
         }
         return -1;
     }
@@ -1081,111 +1085,97 @@
     return sock;
 }
 
-/** Linux **/
-#if defined(__linux__)
 
-#if defined(AF_INET6)
-/*
- * Opens a socket for further ioctl calls. Tries AF_INET socket first and
- * if it fails return AF_INET6 socket.
+/** Linux, AIX **/
+#if defined(__linux__) || defined(_AIX)
+/* Open socket for further ioct calls, try v4 socket first and
+ * if it falls return v6 socket
  */
-static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
+
+#ifdef AF_INET6
+static int openSocketWithFallback(JNIEnv *env, const char *ifname){
     int sock;
+    struct ifreq if2;
 
-    if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-        if (errno == EPROTONOSUPPORT) {
-            if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
-                NET_ThrowByNameWithLastError
-                    (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
-                return -1;
-            }
-        } else { // errno is not NOSUPPORT
-            NET_ThrowByNameWithLastError
-                (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
-            return -1;
-        }
-    }
+     if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
+         if (errno == EPROTONOSUPPORT){
+              if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
+                 NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
+                 return -1;
+              }
+         }
+         else{ // errno is not NOSUPPORT
+             NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
+             return -1;
+         }
+   }
 
-    // Linux starting from 2.6.? kernel allows ioctl call with either IPv4 or
-    // IPv6 socket regardless of type of address of an interface.
-    return sock;
+     /* Linux starting from 2.6.? kernel allows ioctl call with either IPv4 or IPv6 socket regardless of type
+        of address of an interface */
+
+       return sock;
 }
+
 #else
-static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
-    return openSocket(env, AF_INET);
+static int openSocketWithFallback(JNIEnv *env, const char *ifname){
+    return openSocket(env,AF_INET);
 }
 #endif
 
-/*
- * Enumerates and returns all IPv4 interfaces on Linux.
- */
 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
     struct ifconf ifc;
     struct ifreq *ifreqP;
     char *buf = NULL;
+    int numifs;
     unsigned i;
+    int siocgifconfRequest = SIOCGIFCONF;
 
-    // do a dummy SIOCGIFCONF to determine the buffer size
-    // SIOCGIFCOUNT doesn't work
+
+#if defined(__linux__)
+    /* need to do a dummy SIOCGIFCONF to determine the buffer size.
+     * SIOCGIFCOUNT doesn't work
+     */
     ifc.ifc_buf = NULL;
     if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFCONF) failed");
+        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGIFCONF failed");
         return ifs;
     }
+#elif defined(_AIX)
+    ifc.ifc_buf = NULL;
+    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
+        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGSIZIFCONF failed");
+        return ifs;
+    }
+#endif /* __linux__ */
 
-    // call SIOCGIFCONF to enumerate the interfaces
-    CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
+    CHECKED_MALLOC3(buf,char *, ifc.ifc_len);
+
     ifc.ifc_buf = buf;
-    if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFCONF) failed");
-        free(buf);
+#if defined(_AIX)
+    siocgifconfRequest = CSIOCGIFCONF;
+#endif
+    if (ioctl(sock, siocgifconfRequest, (char *)&ifc) < 0) {
+        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGIFCONF failed");
+        (void) free(buf);
         return ifs;
     }
 
-    // iterate through each interface
+    /*
+     * Iterate through each interface
+     */
     ifreqP = ifc.ifc_req;
-    for (i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++, ifreqP++) {
-        struct sockaddr addr, broadaddr, *broadaddrP = NULL;
-        short prefix = 0;
+    for (i=0; i<ifc.ifc_len/sizeof (struct ifreq); i++, ifreqP++) {
+#if defined(_AIX)
+        if (ifreqP->ifr_addr.sa_family != AF_INET) continue;
+#endif
+        /*
+         * Add to the list
+         */
+        ifs = addif(env, sock, ifreqP->ifr_name, ifs, (struct sockaddr *) & (ifreqP->ifr_addr), AF_INET, 0);
 
-        // ignore non IPv4 addresses
-        if (ifreqP->ifr_addr.sa_family != AF_INET) {
-            continue;
-        }
-
-        // save socket address
-        memcpy(&addr, &(ifreqP->ifr_addr), sizeof(struct sockaddr));
-
-        // determine broadcast address, if applicable
-        if ((ioctl(sock, SIOCGIFFLAGS, ifreqP) == 0) &&
-            ifreqP->ifr_flags & IFF_BROADCAST) {
-
-            // restore socket address to ifreqP
-            memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
-
-            if (ioctl(sock, SIOCGIFBRDADDR, ifreqP) == 0) {
-                memcpy(&broadaddr, &(ifreqP->ifr_broadaddr),
-                       sizeof(struct sockaddr));
-                broadaddrP = &broadaddr;
-            }
-        }
-
-        // restore socket address to ifreqP
-        memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
-
-        // determine netmask
-        if (ioctl(sock, SIOCGIFNETMASK, ifreqP) == 0) {
-            prefix = translateIPv4AddressToPrefix(
-                         (struct sockaddr_in *)&(ifreqP->ifr_netmask));
-        }
-
-        // add interface to the list
-        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
-                    &addr, broadaddrP, AF_INET, prefix);
-
-        // in case of exception, free interface list and buffer and return NULL
+        /*
+         * If an exception occurred then free the list
+         */
         if ((*env)->ExceptionOccurred(env)) {
             free(buf);
             freeif(ifs);
@@ -1193,351 +1183,240 @@
         }
     }
 
-    // free buffer
+    /*
+     * Free socket and buffer
+     */
     free(buf);
     return ifs;
 }
 
-#if defined(AF_INET6)
 
 /*
- * Enumerates and returns all IPv6 interfaces on Linux.
+ * Enumerates and returns all IPv6 interfaces on Linux
  */
+
+#if defined(AF_INET6) && defined(__linux__)
 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
     FILE *f;
-    char devname[21], addr6p[8][5];
-    int prefix, scope, dad_status, if_idx;
+    char addr6[40], devname[21];
+    char addr6p[8][5];
+    int plen, scope, dad_status, if_idx;
+    uint8_t ipv6addr[16];
 
     if ((f = fopen(_PATH_PROCNET_IFINET6, "r")) != NULL) {
         while (fscanf(f, "%4s%4s%4s%4s%4s%4s%4s%4s %08x %02x %02x %02x %20s\n",
-                      addr6p[0], addr6p[1], addr6p[2], addr6p[3],
-                      addr6p[4], addr6p[5], addr6p[6], addr6p[7],
-                      &if_idx, &prefix, &scope, &dad_status, devname) != EOF) {
+                         addr6p[0], addr6p[1], addr6p[2], addr6p[3], addr6p[4], addr6p[5], addr6p[6], addr6p[7],
+                         &if_idx, &plen, &scope, &dad_status, devname) != EOF) {
 
-            char addr6[40];
+            struct netif *ifs_ptr = NULL;
+            struct netif *last_ptr = NULL;
             struct sockaddr_in6 addr;
 
             sprintf(addr6, "%s:%s:%s:%s:%s:%s:%s:%s",
-                    addr6p[0], addr6p[1], addr6p[2], addr6p[3],
-                    addr6p[4], addr6p[5], addr6p[6], addr6p[7]);
+                           addr6p[0], addr6p[1], addr6p[2], addr6p[3], addr6p[4], addr6p[5], addr6p[6], addr6p[7]);
+            inet_pton(AF_INET6, addr6, ipv6addr);
 
             memset(&addr, 0, sizeof(struct sockaddr_in6));
-            inet_pton(AF_INET6, addr6, (void*)addr.sin6_addr.s6_addr);
+            memcpy((void*)addr.sin6_addr.s6_addr, (const void*)ipv6addr, 16);
 
-            // set scope ID to interface index
             addr.sin6_scope_id = if_idx;
 
-            // add interface to the list
-            ifs = addif(env, sock, devname, ifs, (struct sockaddr *)&addr,
-                        NULL, AF_INET6, (short)prefix);
+            ifs = addif(env, sock, devname, ifs, (struct sockaddr *)&addr, AF_INET6, plen);
 
-            // if an exception occurred then return the list as is
+
+            /*
+             * If an exception occurred then return the list as is.
+             */
             if ((*env)->ExceptionOccurred(env)) {
-                break;
+                fclose(f);
+                return ifs;
             }
        }
        fclose(f);
     }
     return ifs;
 }
+#endif
 
-#endif /* AF_INET6 */
 
 /*
- * Try to get the interface index.
+ * Enumerates and returns all IPv6 interfaces on AIX
  */
-static int getIndex(int sock, const char *name) {
+
+#if defined(AF_INET6) && defined(_AIX)
+static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
+    struct ifconf ifc;
+    struct ifreq *ifreqP;
+    char *buf;
+    int numifs;
+    unsigned i;
+    unsigned bufsize;
+    char *cp, *cplimit;
+
+    /* use SIOCGSIZIFCONF to get size for  SIOCGIFCONF */
+
+    ifc.ifc_buf = NULL;
+    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
+        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
+                        "ioctl SIOCGSIZIFCONF failed");
+        return ifs;
+    }
+    bufsize = ifc.ifc_len;
+
+    buf = (char *)malloc(bufsize);
+    if (!buf) {
+        JNU_ThrowOutOfMemoryError(env, "Network interface native buffer allocation failed");
+        return ifs;
+    }
+    ifc.ifc_len = bufsize;
+    ifc.ifc_buf = buf;
+    if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
+        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
+                       "ioctl CSIOCGIFCONF failed");
+        free(buf);
+        return ifs;
+    }
+
+    /*
+     * Iterate through each interface
+     */
+    ifreqP = ifc.ifc_req;
+    cp = (char *)ifc.ifc_req;
+    cplimit = cp + ifc.ifc_len;
+
+    for ( ; cp < cplimit; cp += (sizeof(ifreqP->ifr_name) + MAX((ifreqP->ifr_addr).sa_len, sizeof(ifreqP->ifr_addr)))) {
+        ifreqP = (struct ifreq *)cp;
+        struct ifreq if2;
+
+        memset((char *)&if2, 0, sizeof(if2));
+        strcpy(if2.ifr_name, ifreqP->ifr_name);
+
+        /*
+         * Skip interface that aren't UP
+         */
+        if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) >= 0) {
+            if (!(if2.ifr_flags & IFF_UP)) {
+                continue;
+            }
+        }
+
+        if (ifreqP->ifr_addr.sa_family != AF_INET6)
+            continue;
+
+        if (ioctl(sock, SIOCGIFSITE6, (char *)&if2) >= 0) {
+            struct sockaddr_in6 *s6= (struct sockaddr_in6 *)&(ifreqP->ifr_addr);
+            s6->sin6_scope_id = if2.ifr_site6;
+        }
+
+        /*
+         * Add to the list
+         */
+        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
+                    (struct sockaddr *)&(ifreqP->ifr_addr),
+                    AF_INET6, 0);
+
+        /*
+         * If an exception occurred then free the list
+         */
+        if ((*env)->ExceptionOccurred(env)) {
+            free(buf);
+            freeif(ifs);
+            return NULL;
+        }
+    }
+
+    /*
+     * Free socket and buffer
+     */
+    free(buf);
+    return ifs;
+}
+#endif
+
+
+static int getIndex(int sock, const char *name){
+     /*
+      * Try to get the interface index
+      */
+#if defined(_AIX)
+    return if_nametoindex(name);
+#else
     struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, name, sizeof(if2.ifr_name) - 1);
+    strcpy(if2.ifr_name, name);
 
     if (ioctl(sock, SIOCGIFINDEX, (char *)&if2) < 0) {
         return -1;
     }
 
     return if2.ifr_ifindex;
-}
-
-/*
- * Gets the Hardware address (usually MAC address) for the named interface.
- * On return puts the data in buf, and returns the length, in byte, of the
- * MAC address. Returns -1 if there is no hardware address on that interface.
- */
-static int getMacAddress
-  (JNIEnv *env, const char *ifname, const struct in_addr *addr,
-   unsigned char *buf)
-{
-    static struct ifreq ifr;
-    int i, sock;
-
-    if ((sock = openSocketWithFallback(env, ifname)) < 0) {
-        return -1;
-    }
-
-    memset((char *)&ifr, 0, sizeof(ifr));
-    strncpy(ifr.ifr_name, ifname, sizeof(ifr.ifr_name) - 1);
-    if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFHWADDR) failed");
-        close(sock);
-        return -1;
-    }
-
-    close(sock);
-    memcpy(buf, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
-
-    // all bytes to 0 means no hardware address
-    for (i = 0; i < IFHWADDRLEN; i++) {
-        if (buf[i] != 0)
-            return IFHWADDRLEN;
-    }
-
-    return -1;
-}
-
-static int getMTU(JNIEnv *env, int sock, const char *ifname) {
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
-
-    if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFMTU) failed");
-        return -1;
-    }
-
-    return if2.ifr_mtu;
-}
-
-static int getFlags(int sock, const char *ifname, int *flags) {
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
-
-    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
-        return -1;
-    }
-
-    if (sizeof(if2.ifr_flags) == sizeof(short)) {
-        *flags = (if2.ifr_flags & 0xffff);
-    } else {
-        *flags = if2.ifr_flags;
-    }
-    return 0;
-}
-
-#endif /* __linux__ */
-
-/** AIX **/
-#if defined(_AIX)
-
-#if defined(AF_INET6)
-/*
- * Opens a socket for further ioctl calls. Tries AF_INET socket first and
- * if it fails return AF_INET6 socket.
- */
-static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
-    int sock;
-
-    if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-        if (errno == EPROTONOSUPPORT) {
-            if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
-                NET_ThrowByNameWithLastError
-                    (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
-                return -1;
-            }
-        } else { // errno is not NOSUPPORT
-            NET_ThrowByNameWithLastError
-                (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
-            return -1;
-        }
-    }
-
-    return sock;
-}
-#else
-static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
-    return openSocket(env, AF_INET);
-}
 #endif
-
-/*
- * Enumerates and returns all IPv4 interfaces on AIX.
- */
-static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
-    struct ifconf ifc;
-    struct ifreq *ifreqP;
-    char *buf = NULL;
-    unsigned i;
-
-    // call SIOCGSIZIFCONF to get the size of SIOCGIFCONF buffer
-    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGSIZIFCONF) failed");
-        return ifs;
-    }
-
-    // call CSIOCGIFCONF instead of SIOCGIFCONF where interface
-    // records will always have sizeof(struct ifreq) length.
-    // Be aware that only IPv4 data is complete this way.
-    CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
-    ifc.ifc_buf = buf;
-    if (ioctl(sock, CSIOCGIFCONF, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(CSIOCGIFCONF) failed");
-        free(buf);
-        return ifs;
-    }
-
-    // iterate through each interface
-    ifreqP = ifc.ifc_req;
-    for (i = 0; i < ifc.ifc_len / sizeof(struct ifreq); i++, ifreqP++) {
-        struct sockaddr addr, broadaddr, *broadaddrP = NULL;
-        short prefix = 0;
-
-        // ignore non IPv4 addresses
-        if (ifreqP->ifr_addr.sa_family != AF_INET) {
-            continue;
-        }
-
-        // save socket address
-        memcpy(&addr, &(ifreqP->ifr_addr), sizeof(struct sockaddr));
-
-        // determine broadcast address, if applicable
-        if ((ioctl(sock, SIOCGIFFLAGS, ifreqP) == 0) &&
-            ifreqP->ifr_flags & IFF_BROADCAST) {
-
-            // restore socket address to ifreqP
-            memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
-
-            if (ioctl(sock, SIOCGIFBRDADDR, ifreqP) == 0) {
-                memcpy(&broadaddr, &(ifreqP->ifr_broadaddr),
-                       sizeof(struct sockaddr));
-                broadaddrP = &broadaddr;
-            }
-        }
-
-        // restore socket address to ifreqP
-        memcpy(&(ifreqP->ifr_addr), &addr, sizeof(struct sockaddr));
-
-        // determine netmask
-        if (ioctl(sock, SIOCGIFNETMASK, ifreqP) == 0) {
-            prefix = translateIPv4AddressToPrefix(
-                         (struct sockaddr_in *)&(ifreqP->ifr_addr));
-        }
-
-        // add interface to the list
-        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
-                    &addr, broadaddrP, AF_INET, prefix);
-
-        // in case of exception, free interface list and buffer and return NULL
-        if ((*env)->ExceptionOccurred(env)) {
-            free(buf);
-            freeif(ifs);
-            return NULL;
-        }
-    }
-
-    // free buffer
-    free(buf);
-    return ifs;
 }
 
-#if defined(AF_INET6)
-
-/*
- * Enumerates and returns all IPv6 interfaces on AIX.
+/**
+ * Returns the IPv4 broadcast address of a named interface, if it exists.
+ * Returns 0 if it doesn't have one.
  */
-static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
-    struct ifconf ifc;
-    struct ifreq *ifreqP;
-    char *buf, *cp, *cplimit;
+static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store) {
+  struct sockaddr *ret = NULL;
+  struct ifreq if2;
 
-    // call SIOCGSIZIFCONF to get size for SIOCGIFCONF buffer
-    if (ioctl(sock, SIOCGSIZIFCONF, &(ifc.ifc_len)) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGSIZIFCONF) failed");
-        return ifs;
-    }
+  memset((char *) &if2, 0, sizeof(if2));
+  strcpy(if2.ifr_name, ifname);
 
-    // call SIOCGIFCONF to enumerate the interfaces
-    CHECKED_MALLOC3(buf, char *, ifc.ifc_len);
-    ifc.ifc_buf = buf;
-    if (ioctl(sock, SIOCGIFCONF, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFCONF) failed");
-        free(buf);
-        return ifs;
-    }
+  /* Let's make sure the interface does have a broadcast address */
+  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2)  < 0) {
+      NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL  SIOCGIFFLAGS failed");
+      return ret;
+  }
 
-    // iterate through each interface
-    ifreqP = ifc.ifc_req;
-    cp = (char *)ifc.ifc_req;
-    cplimit = cp + ifc.ifc_len;
+  if (if2.ifr_flags & IFF_BROADCAST) {
+      /* It does, let's retrieve it*/
+      if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
+          NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFBRDADDR failed");
+          return ret;
+      }
 
-    for (; cp < cplimit;
-         cp += (sizeof(ifreqP->ifr_name) +
-                MAX((ifreqP->ifr_addr).sa_len, sizeof(ifreqP->ifr_addr))))
-    {
-        ifreqP = (struct ifreq *)cp;
-        short prefix = 0;
+      ret = brdcast_store;
+      memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
+  }
 
-        // ignore non IPv6 addresses
-        if (ifreqP->ifr_addr.sa_family != AF_INET6) {
-            continue;
-        }
-
-        // determine netmask
-        struct in6_ifreq if6;
-        memset((char *)&if6, 0, sizeof(if6));
-        strncpy(if6.ifr_name, ifreqP->ifr_name, sizeof(if6.ifr_name) - 1);
-        memcpy(&(if6.ifr_Addr), &(ifreqP->ifr_addr),
-               sizeof(struct sockaddr_in6));
-        if (ioctl(sock, SIOCGIFNETMASK6, (char *)&if6) >= 0) {
-            prefix = translateIPv6AddressToPrefix(&(if6.ifr_Addr));
-        }
-
-        // set scope ID to interface index
-        ((struct sockaddr_in6 *)&(ifreqP->ifr_addr))->sin6_scope_id =
-            getIndex(sock, ifreqP->ifr_name);
-
-        // add interface to the list
-        ifs = addif(env, sock, ifreqP->ifr_name, ifs,
-                    (struct sockaddr *)&(ifreqP->ifr_addr),
-                    NULL, AF_INET6, prefix);
-
-        // if an exception occurred then free the list
-        if ((*env)->ExceptionOccurred(env)) {
-            free(buf);
-            freeif(ifs);
-            return NULL;
-        }
-    }
-
-    // free buffer
-    free(buf);
-    return ifs;
+  return ret;
 }
 
-#endif /* AF_INET6 */
-
-/*
- * Try to get the interface index.
+/**
+ * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
+ * interface, if it has one, otherwise return -1.
  */
-static int getIndex(int sock, const char *name) {
-    int index = if_nametoindex(name);
-    return (index == 0) ? -1 : index;
+static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
+    unsigned int mask;
+    short ret;
+    struct ifreq if2;
+
+    memset((char *) &if2, 0, sizeof(if2));
+    strcpy(if2.ifr_name, ifname);
+
+    if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFNETMASK failed");
+        return -1;
+    }
+
+    mask = ntohl(((struct sockaddr_in*)&(if2.ifr_addr))->sin_addr.s_addr);
+    ret = 0;
+    while (mask) {
+       mask <<= 1;
+       ret++;
+    }
+
+    return ret;
 }
 
-/*
- * Gets the Hardware address (usually MAC address) for the named interface.
- * On return puts the data in buf, and returns the length, in byte, of the
+/**
+ * Get the Hardware address (usually MAC address) for the named interface.
+ * return puts the data in buf, and returns the length, in byte, of the
  * MAC address. Returns -1 if there is no hardware address on that interface.
  */
-static int getMacAddress
-  (JNIEnv *env, const char *ifname, const struct in_addr *addr,
-   unsigned char *buf)
-{
+static int getMacAddress(JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr, unsigned char *buf) {
+#if defined (_AIX)
     int size;
     struct kinfo_ndd *nddp;
     void *end;
@@ -1555,8 +1434,7 @@
     nddp = (struct kinfo_ndd *)malloc(size);
 
     if (!nddp) {
-        JNU_ThrowOutOfMemoryError(env,
-            "Network interface getMacAddress native buffer allocation failed");
+        JNU_ThrowOutOfMemoryError(env, "Network interface getMacAddress native buffer allocation failed");
         return -1;
     }
 
@@ -1577,243 +1455,227 @@
     }
 
     return -1;
-}
 
-static int getMTU(JNIEnv *env, int sock, const char *ifname) {
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
+#elif defined(__linux__)
+    static struct ifreq ifr;
+    int i;
 
-    if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFMTU) failed");
+    strcpy(ifr.ifr_name, ifname);
+    if (ioctl(sock, SIOCGIFHWADDR, &ifr) < 0) {
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFHWADDR failed");
         return -1;
     }
 
-    return if2.ifr_mtu;
+    memcpy(buf, &ifr.ifr_hwaddr.sa_data, IFHWADDRLEN);
+
+   /*
+    * All bytes to 0 means no hardware address.
+    */
+
+    for (i = 0; i < IFHWADDRLEN; i++) {
+        if (buf[i] != 0)
+            return IFHWADDRLEN;
+    }
+
+    return -1;
+#endif
+}
+
+static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
+    struct ifreq if2;
+
+    memset((char *) &if2, 0, sizeof(if2));
+    if (ifname != NULL) {
+        strcpy(if2.ifr_name, ifname);
+    } else {
+        JNU_ThrowNullPointerException(env, "network interface name is NULL");
+        return -1;
+    }
+
+    if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFMTU failed");
+        return -1;
+    }
+
+    return  if2.ifr_mtu;
 }
 
 static int getFlags(int sock, const char *ifname, int *flags) {
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
+  struct ifreq if2;
 
-    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
-        return -1;
-    }
+  memset((char *) &if2, 0, sizeof(if2));
+  strcpy(if2.ifr_name, ifname);
 
-    if (sizeof(if2.ifr_flags) == sizeof(short)) {
-        *flags = (if2.ifr_flags & 0xffff);
-    } else {
-        *flags = if2.ifr_flags;
-    }
-    return 0;
+  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0){
+      return -1;
+  }
+
+  if (sizeof(if2.ifr_flags) == sizeof(short)) {
+      *flags = (if2.ifr_flags & 0xffff);
+  } else {
+      *flags = if2.ifr_flags;
+  }
+  return 0;
 }
 
-#endif /* _AIX */
+#endif
 
 /** Solaris **/
-#if defined(__solaris__)
-
-#if defined(AF_INET6)
-/*
- * Opens a socket for further ioctl calls. Tries AF_INET socket first and
- * if it fails return AF_INET6 socket.
+#ifdef __solaris__
+/* Open socket for further ioct calls, try v4 socket first and
+ * if it falls return v6 socket
  */
-static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
+
+#ifdef AF_INET6
+static int openSocketWithFallback(JNIEnv *env, const char *ifname){
     int sock, alreadyV6 = 0;
     struct lifreq if2;
 
-    if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-        if (errno == EPROTONOSUPPORT) {
-            if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
-                NET_ThrowByNameWithLastError
-                    (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
-                return -1;
-            }
-            alreadyV6 = 1;
-        } else { // errno is not NOSUPPORT
-            NET_ThrowByNameWithLastError
-                (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
-            return -1;
-        }
-    }
+     if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
+         if (errno == EPROTONOSUPPORT){
+              if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
+                 NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
+                 return -1;
+              }
 
-    // Solaris requires that we have an IPv6 socket to query an  interface
-    // without an IPv4 address - check it here. POSIX 1 require the kernel to
-    // return ENOTTY if the call is inappropriate for a device e.g. the NETMASK
-    // for a device having IPv6 only address but not all devices follow the
-    // standard so fall back on any error. It's not an ecologically friendly
-    // gesture but more reliable.
-    if (!alreadyV6) {
-        memset((char *)&if2, 0, sizeof(if2));
-        strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
+              alreadyV6=1;
+         }
+         else{ // errno is not NOSUPPORT
+             NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
+             return -1;
+         }
+   }
+
+     /**
+      * Solaris requires that we have an IPv6 socket to query an
+      * interface without an IPv4 address - check it here.
+      * POSIX 1 require the kernel to return ENOTTY if the call is
+      * inappropriate for a device e.g. the NETMASK for a device having IPv6
+      * only address but not all devices follow the standard so
+      * fall back on any error. It's not an ecologically friendly gesture
+      * but more reliable.
+      */
+
+    if (! alreadyV6 ){
+        memset((char *) &if2, 0, sizeof(if2));
+        strcpy(if2.lifr_name, ifname);
         if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
-            close(sock);
-            if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
-                NET_ThrowByNameWithLastError
-                    (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
-                return -1;
-            }
+                close(sock);
+                if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
+                      NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
+                      return -1;
+                }
         }
     }
 
     return sock;
 }
+
 #else
-static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
-    return openSocket(env, AF_INET);
+static int openSocketWithFallback(JNIEnv *env, const char *ifname){
+    return openSocket(env,AF_INET);
 }
 #endif
 
 /*
- * Enumerates and returns all IPv4 interfaces on Solaris.
+ * Enumerates and returns all IPv4 interfaces
+ * (linux verision)
  */
-static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
-    struct lifconf ifc;
-    struct lifreq *ifreqP;
-    struct lifnum numifs;
-    char *buf = NULL;
-    unsigned i;
 
-    // call SIOCGLIFNUM to get the interface count
-    numifs.lifn_family = AF_INET;
+static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
+     return enumIPvXInterfaces(env,sock, ifs, AF_INET);
+}
+
+#ifdef AF_INET6
+static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
+    return enumIPvXInterfaces(env,sock, ifs, AF_INET6);
+}
+#endif
+
+/*
+   Enumerates and returns all interfaces on Solaris
+   use the same code for IPv4 and IPv6
+ */
+static netif *enumIPvXInterfaces(JNIEnv *env, int sock, netif *ifs, int family) {
+    struct lifconf ifc;
+    struct lifreq *ifr;
+    int n;
+    char *buf;
+    struct lifnum numifs;
+    unsigned bufsize;
+
+    /*
+     * Get the interface count
+     */
+    numifs.lifn_family = family;
     numifs.lifn_flags = 0;
     if (ioctl(sock, SIOCGLIFNUM, (char *)&numifs) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFNUM) failed");
+        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGLIFNUM failed");
         return ifs;
     }
 
-    // call SIOCGLIFCONF to enumerate the interfaces
-    ifc.lifc_len = numifs.lifn_count * sizeof(struct lifreq);
-    CHECKED_MALLOC3(buf, char *, ifc.lifc_len);
-    ifc.lifc_buf = buf;
-    ifc.lifc_family = AF_INET;
+    /*
+     *  Enumerate the interface configurations
+     */
+    bufsize = numifs.lifn_count * sizeof (struct lifreq);
+    CHECKED_MALLOC3(buf, char *, bufsize);
+
+    ifc.lifc_family = family;
     ifc.lifc_flags = 0;
+    ifc.lifc_len = bufsize;
+    ifc.lifc_buf = buf;
     if (ioctl(sock, SIOCGLIFCONF, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFCONF) failed");
+        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "ioctl SIOCGLIFCONF failed");
         free(buf);
         return ifs;
     }
 
-    // iterate through each interface
-    ifreqP = ifc.lifc_req;
-    for (i = 0; i < numifs.lifn_count; i++, ifreqP++) {
-        struct sockaddr addr, *broadaddrP = NULL;
+    /*
+     * Iterate through each interface
+     */
+    ifr = ifc.lifc_req;
+    for (n=0; n<numifs.lifn_count; n++, ifr++) {
+        int index = -1;
+        struct lifreq if2;
 
-        // ignore non IPv4 addresses
-        if (ifreqP->lifr_addr.ss_family != AF_INET) {
+        /*
+        * Ignore either IPv4 or IPv6 addresses
+        */
+        if (ifr->lifr_addr.ss_family != family) {
             continue;
         }
 
-        // save socket address
-        memcpy(&addr, &(ifreqP->lifr_addr), sizeof(struct sockaddr));
-
-        // determine broadcast address, if applicable
-        if ((ioctl(sock, SIOCGLIFFLAGS, ifreqP) == 0) &&
-            ifreqP->lifr_flags & IFF_BROADCAST) {
-
-            // restore socket address to ifreqP
-            memcpy(&(ifreqP->lifr_addr), &addr, sizeof(struct sockaddr));
-
-            // query broadcast address and set pointer to it
-            if (ioctl(sock, SIOCGLIFBRDADDR, ifreqP) == 0) {
-                broadaddrP = (struct sockaddr *)&(ifreqP->lifr_broadaddr);
-            }
+#ifdef AF_INET6
+        if (ifr->lifr_addr.ss_family == AF_INET6) {
+            struct sockaddr_in6 *s6= (struct sockaddr_in6 *)&(ifr->lifr_addr);
+            s6->sin6_scope_id = getIndex(sock, ifr->lifr_name);
         }
+#endif
 
-        // add to the list
-        ifs = addif(env, sock, ifreqP->lifr_name, ifs,
-                    &addr, broadaddrP, AF_INET, (short)ifreqP->lifr_addrlen);
+        /* add to the list */
+        ifs = addif(env, sock,ifr->lifr_name, ifs, (struct sockaddr *)&(ifr->lifr_addr),family, (short) ifr->lifr_addrlen);
 
-        // if an exception occurred we return immediately
+        /*
+        * If an exception occurred we return immediately
+        */
         if ((*env)->ExceptionOccurred(env)) {
             free(buf);
             return ifs;
         }
+
    }
 
-    // free buffer
     free(buf);
     return ifs;
 }
 
-#if defined(AF_INET6)
-
-/*
- * Enumerates and returns all IPv6 interfaces on Solaris.
- */
-static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
-    struct lifconf ifc;
-    struct lifreq *ifreqP;
-    struct lifnum numifs;
-    char *buf = NULL;
-    unsigned i;
-
-    // call SIOCGLIFNUM to get the interface count
-    numifs.lifn_family = AF_INET6;
-    numifs.lifn_flags = 0;
-    if (ioctl(sock, SIOCGLIFNUM, (char *)&numifs) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFNUM) failed");
-        return ifs;
-    }
-
-    // call SIOCGLIFCONF to enumerate the interfaces
-    ifc.lifc_len = numifs.lifn_count * sizeof(struct lifreq);
-    CHECKED_MALLOC3(buf, char *, ifc.lifc_len);
-    ifc.lifc_buf = buf;
-    ifc.lifc_family = AF_INET6;
-    ifc.lifc_flags = 0;
-    if (ioctl(sock, SIOCGLIFCONF, (char *)&ifc) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFCONF) failed");
-        free(buf);
-        return ifs;
-    }
-
-    // iterate through each interface
-    ifreqP = ifc.lifc_req;
-    for (i = 0; i < numifs.lifn_count; i++, ifreqP++) {
-
-        // ignore non IPv6 addresses
-        if (ifreqP->lifr_addr.ss_family != AF_INET6) {
-            continue;
-        }
-
-        // set scope ID to interface index
-        ((struct sockaddr_in6 *)&(ifreqP->lifr_addr))->sin6_scope_id =
-            getIndex(sock, ifreqP->lifr_name);
-
-        // add to the list
-        ifs = addif(env, sock, ifreqP->lifr_name, ifs,
-                    (struct sockaddr *)&(ifreqP->lifr_addr),
-                    NULL, AF_INET6, (short)ifreqP->lifr_addrlen);
-
-        // if an exception occurred we return immediately
-        if ((*env)->ExceptionOccurred(env)) {
-            free(buf);
-            return ifs;
-        }
-    }
-
-    // free buffer
-    free(buf);
-    return ifs;
-}
-
-#endif /* AF_INET6 */
-
-/*
- * Try to get the interface index.
- * (Not supported on Solaris 2.6 or 7)
- */
-static int getIndex(int sock, const char *name) {
+static int getIndex(int sock, const char *name){
+   /*
+    * Try to get the interface index
+    * (Not supported on Solaris 2.6 or 7)
+    */
     struct lifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.lifr_name, name, sizeof(if2.lifr_name) - 1);
+    strcpy(if2.lifr_name, name);
 
     if (ioctl(sock, SIOCGLIFINDEX, (char *)&if2) < 0) {
         return -1;
@@ -1822,14 +1684,75 @@
     return if2.lifr_index;
 }
 
-/*
+/**
+ * Returns the IPv4 broadcast address of a named interface, if it exists.
+ * Returns 0 if it doesn't have one.
+ */
+static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store) {
+    struct sockaddr *ret = NULL;
+    struct lifreq if2;
+
+    memset((char *) &if2, 0, sizeof(if2));
+    strcpy(if2.lifr_name, ifname);
+
+    /* Let's make sure the interface does have a broadcast address */
+    if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2)  < 0) {
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL  SIOCGLIFFLAGS failed");
+        return ret;
+    }
+
+    if (if2.lifr_flags & IFF_BROADCAST) {
+        /* It does, let's retrieve it*/
+        if (ioctl(sock, SIOCGLIFBRDADDR, (char *)&if2) < 0) {
+            NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFBRDADDR failed");
+            return ret;
+        }
+
+        ret = brdcast_store;
+        memcpy(ret, &if2.lifr_broadaddr, sizeof(struct sockaddr));
+    }
+
+    return ret;
+}
+
+/**
+ * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
+ * interface, if it has one, otherwise return -1.
+ */
+static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
+    unsigned int mask;
+    short ret;
+    struct lifreq if2;
+
+    memset((char *) &if2, 0, sizeof(if2));
+    strcpy(if2.lifr_name, ifname);
+
+    if (ioctl(sock, SIOCGLIFNETMASK, (char *)&if2) < 0) {
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFNETMASK failed");
+        return -1;
+    }
+
+    mask = ntohl(((struct sockaddr_in*)&(if2.lifr_addr))->sin_addr.s_addr);
+    ret = 0;
+
+    while (mask) {
+       mask <<= 1;
+       ret++;
+    }
+
+    return ret;
+}
+
+
+
+#define DEV_PREFIX  "/dev/"
+
+/**
  * Solaris specific DLPI code to get hardware address from a device.
  * Unfortunately, at least up to Solaris X, you have to have special
  * privileges (i.e. be root).
  */
-static int getMacFromDevice
-  (JNIEnv *env, const char *ifname, unsigned char *retbuf)
-{
+static int getMacFromDevice(JNIEnv *env, const char* ifname, unsigned char* retbuf) {
     char style1dev[MAXPATHLEN];
     int fd;
     dl_phys_addr_req_t dlpareq;
@@ -1838,13 +1761,18 @@
     char buf[128];
     int flags = 0;
 
-    // Device is in /dev.  e.g.: /dev/bge0
+   /**
+    * Device is in /dev
+    * e.g.: /dev/bge0
+    */
     strcpy(style1dev, DEV_PREFIX);
     strcat(style1dev, ifname);
     if ((fd = open(style1dev, O_RDWR)) < 0) {
-        // Can't open it. We probably are missing the privilege.
-        // We'll have to try something else
-        return 0;
+        /*
+         * Can't open it. We probably are missing the privilege.
+         * We'll have to try something else
+         */
+         return 0;
     }
 
     dlpareq.dl_primitive = DL_PHYS_ADDR_REQ;
@@ -1854,8 +1782,7 @@
     msg.len = DL_PHYS_ADDR_REQ_SIZE;
 
     if (putmsg(fd, &msg, NULL, 0) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "putmsg() failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "putmsg failed");
         return -1;
     }
 
@@ -1865,14 +1792,12 @@
     msg.len = 0;
     msg.maxlen = sizeof (buf);
     if (getmsg(fd, &msg, NULL, &flags) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "getmsg() failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "getmsg failed");
         return -1;
     }
 
     if (msg.len < DL_PHYS_ADDR_ACK_SIZE || dlpaack->dl_primitive != DL_PHYS_ADDR_ACK) {
-        JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
-                        "Couldn't obtain phys addr\n");
+        JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "Couldn't obtain phys addr\n");
         return -1;
     }
 
@@ -1880,165 +1805,168 @@
     return dlpaack->dl_addr_length;
 }
 
-/*
- * Gets the Hardware address (usually MAC address) for the named interface.
- * On return puts the data in buf, and returns the length, in byte, of the
+/**
+ * Get the Hardware address (usually MAC address) for the named interface.
+ * return puts the data in buf, and returns the length, in byte, of the
  * MAC address. Returns -1 if there is no hardware address on that interface.
  */
-static int getMacAddress
-  (JNIEnv *env, const char *ifname, const struct in_addr *addr,
-   unsigned char *buf)
-{
-    struct lifreq if2;
-    int len, i, sock;
+static int getMacAddress(JNIEnv *env, int sock, const char *ifname,  const struct in_addr* addr, unsigned char *buf) {
+    struct arpreq arpreq;
+    struct sockaddr_in* sin;
+    struct sockaddr_in ipAddr;
+    int len, i;
+    struct lifreq lif;
 
-    if ((sock = openSocketWithFallback(env, ifname)) < 0) {
-        return -1;
-    }
+    /* First, try the new (S11) SIOCGLIFHWADDR ioctl(). If that fails
+     * try the old way.
+     */
+    memset(&lif, 0, sizeof(lif));
+    strlcpy(lif.lifr_name, ifname, sizeof(lif.lifr_name));
 
-    // First, try the new (S11) SIOCGLIFHWADDR ioctl(). If that fails
-    // try the old way.
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
-
-    if (ioctl(sock, SIOCGLIFHWADDR, &if2) != -1) {
+    if (ioctl(sock, SIOCGLIFHWADDR, &lif) != -1) {
         struct sockaddr_dl *sp;
-        sp = (struct sockaddr_dl *)&if2.lifr_addr;
+        sp = (struct sockaddr_dl *)&lif.lifr_addr;
         memcpy(buf, &sp->sdl_data[0], sp->sdl_alen);
-        close(sock);
         return sp->sdl_alen;
     }
 
-    // On Solaris we have to use DLPI, but it will only work if we have
-    // privileged access (i.e. root). If that fails, we try a lookup
-    // in the ARP table, which requires an IPv4 address.
-    if (((len = getMacFromDevice(env, ifname, buf)) == 0) && (addr != NULL)) {
-        struct arpreq arpreq;
-        struct sockaddr_in *sin;
-        struct sockaddr_in ipAddr;
+   /**
+    * On Solaris we have to use DLPI, but it will only work if we have
+    * privileged access (i.e. root). If that fails, we try a lookup
+    * in the ARP table, which requires an IPv4 address.
+    */
+    if ((len = getMacFromDevice(env, ifname, buf))  == 0) {
+        /*DLPI failed - trying to do arp lookup*/
 
-        len = 6; //???
+        if (addr == NULL) {
+            /**
+             * No IPv4 address for that interface, so can't do an ARP lookup.
+             */
+             return -1;
+         }
 
-        sin = (struct sockaddr_in *)&arpreq.arp_pa;
-        memset((char *)&arpreq, 0, sizeof(struct arpreq));
-        ipAddr.sin_port = 0;
-        ipAddr.sin_family = AF_INET;
-        memcpy(&ipAddr.sin_addr, addr, sizeof(struct in_addr));
-        memcpy(&arpreq.arp_pa, &ipAddr, sizeof(struct sockaddr_in));
-        arpreq.arp_flags= ATF_PUBL;
+         len = 6; //???
 
-        if (ioctl(sock, SIOCGARP, &arpreq) < 0) {
-            close(sock);
-            return -1;
-        }
+         sin = (struct sockaddr_in *) &arpreq.arp_pa;
+         memset((char *) &arpreq, 0, sizeof(struct arpreq));
+         ipAddr.sin_port = 0;
+         ipAddr.sin_family = AF_INET;
+         memcpy(&ipAddr.sin_addr, addr, sizeof(struct in_addr));
+         memcpy(&arpreq.arp_pa, &ipAddr, sizeof(struct sockaddr_in));
+         arpreq.arp_flags= ATF_PUBL;
 
-        memcpy(buf, &arpreq.arp_ha.sa_data[0], len);
+         if (ioctl(sock, SIOCGARP, &arpreq) < 0) {
+             return -1;
+         }
+
+         memcpy(buf, &arpreq.arp_ha.sa_data[0], len );
     }
-    close(sock);
 
-    // all bytes to 0 means no hardware address
+    /*
+     * All bytes to 0 means no hardware address.
+     */
+
     for (i = 0; i < len; i++) {
-        if (buf[i] != 0)
-            return len;
+      if (buf[i] != 0)
+         return len;
     }
 
     return -1;
 }
 
-static int getMTU(JNIEnv *env, int sock, const char *ifname) {
+static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
     struct lifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
+
+    memset((char *) &if2, 0, sizeof(if2));
+    strcpy(if2.lifr_name, ifname);
 
     if (ioctl(sock, SIOCGLIFMTU, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGLIFMTU) failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGLIFMTU failed");
         return -1;
     }
 
-    return if2.lifr_mtu;
+    return  if2.lifr_mtu;
 }
 
+
 static int getFlags(int sock, const char *ifname, int *flags) {
-    struct lifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.lifr_name, ifname, sizeof(if2.lifr_name) - 1);
+     struct   lifreq lifr;
+     memset((caddr_t)&lifr, 0, sizeof(lifr));
+     strcpy((caddr_t)&(lifr.lifr_name), ifname);
 
-    if (ioctl(sock, SIOCGLIFFLAGS, (char *)&if2) < 0) {
-        return -1;
-    }
+     if (ioctl(sock, SIOCGLIFFLAGS, (char *)&lifr) < 0) {
+         return -1;
+     }
 
-    *flags = if2.lifr_flags;
-    return 0;
+     *flags = lifr.lifr_flags;
+     return 0;
 }
 
-#endif /* __solaris__ */
+
+#endif
+
 
 /** BSD **/
-#if defined(_ALLBSD_SOURCE)
-
-#if defined(AF_INET6)
-/*
- * Opens a socket for further ioctl calls. Tries AF_INET socket first and
- * if it fails return AF_INET6 socket.
+#ifdef _ALLBSD_SOURCE
+/* Open socket for further ioct calls, try v4 socket first and
+ * if it falls return v6 socket
  */
-static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
+
+#ifdef AF_INET6
+static int openSocketWithFallback(JNIEnv *env, const char *ifname){
     int sock;
+    struct ifreq if2;
 
-    if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
-        if (errno == EPROTONOSUPPORT) {
-            if ((sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0) {
-                NET_ThrowByNameWithLastError
-                    (env, JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
-                return -1;
-            }
-        } else { // errno is not NOSUPPORT
-            NET_ThrowByNameWithLastError
-                (env, JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
-            return -1;
-        }
-    }
+     if ((sock = JVM_Socket(AF_INET, SOCK_DGRAM, 0)) < 0) {
+         if (errno == EPROTONOSUPPORT){
+              if ( (sock = JVM_Socket(AF_INET6, SOCK_DGRAM, 0)) < 0 ){
+                 NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV6 Socket creation failed");
+                 return -1;
+              }
+         }
+         else{ // errno is not NOSUPPORT
+             NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException", "IPV4 Socket creation failed");
+             return -1;
+         }
+   }
 
-    return sock;
+   return sock;
 }
+
 #else
-static int openSocketWithFallback(JNIEnv *env, const char *ifname) {
-    return openSocket(env, AF_INET);
+static int openSocketWithFallback(JNIEnv *env, const char *ifname){
+    return openSocket(env,AF_INET);
 }
 #endif
 
 /*
- * Enumerates and returns all IPv4 interfaces on BSD.
+ * Enumerates and returns all IPv4 interfaces
  */
 static netif *enumIPv4Interfaces(JNIEnv *env, int sock, netif *ifs) {
     struct ifaddrs *ifa, *origifa;
 
     if (getifaddrs(&origifa) != 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "getifaddrs() failed");
+        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
+                         "getifaddrs() function failed");
         return ifs;
     }
 
     for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
-        struct sockaddr *broadaddrP = NULL;
 
-        // ignore non IPv4 addresses
+        /*
+         * Skip non-AF_INET entries.
+         */
         if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET)
             continue;
 
-        // set ifa_broadaddr, if there is one
-        if ((ifa->ifa_flags & IFF_POINTOPOINT) == 0 &&
-            ifa->ifa_flags & IFF_BROADCAST) {
-            broadaddrP = ifa->ifa_dstaddr;
-        }
+        /*
+         * Add to the list.
+         */
+        ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, AF_INET, 0);
 
-        // add interface to the list
-        ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr,
-                    broadaddrP, AF_INET,
-                    translateIPv4AddressToPrefix((struct sockaddr_in *)
-                                                 ifa->ifa_netmask));
-
-        // if an exception occurred then free the list
+        /*
+         * If an exception occurred then free the list.
+         */
         if ((*env)->ExceptionOccurred(env)) {
             freeifaddrs(origifa);
             freeif(ifs);
@@ -2046,41 +1974,85 @@
         }
     }
 
-    // free ifaddrs buffer
+    /*
+     * Free socket and buffer
+     */
     freeifaddrs(origifa);
     return ifs;
 }
 
-#if defined(AF_INET6)
 
 /*
- * Enumerates and returns all IPv6 interfaces on BSD.
+ * Enumerates and returns all IPv6 interfaces on Linux
+ */
+
+#ifdef AF_INET6
+/*
+ * Determines the prefix on BSD for IPv6 interfaces.
+ */
+static
+int prefix(void *val, int size) {
+    u_char *name = (u_char *)val;
+    int byte, bit, plen = 0;
+
+    for (byte = 0; byte < size; byte++, plen += 8)
+        if (name[byte] != 0xff)
+            break;
+    if (byte == size)
+        return (plen);
+    for (bit = 7; bit != 0; bit--, plen++)
+        if (!(name[byte] & (1 << bit)))
+            break;
+    for (; bit != 0; bit--)
+        if (name[byte] & (1 << bit))
+            return (0);
+    byte++;
+    for (; byte < size; byte++)
+        if (name[byte])
+            return (0);
+    return (plen);
+}
+
+/*
+ * Enumerates and returns all IPv6 interfaces on BSD
  */
 static netif *enumIPv6Interfaces(JNIEnv *env, int sock, netif *ifs) {
     struct ifaddrs *ifa, *origifa;
+    struct sockaddr_in6 *sin6;
+    struct in6_ifreq ifr6;
 
     if (getifaddrs(&origifa) != 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "getifaddrs() failed");
+        NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
+                         "getifaddrs() function failed");
         return ifs;
     }
 
     for (ifa = origifa; ifa != NULL; ifa = ifa->ifa_next) {
-        // ignore non IPv6 addresses
+
+        /*
+         * Skip non-AF_INET6 entries.
+         */
         if (ifa->ifa_addr == NULL || ifa->ifa_addr->sa_family != AF_INET6)
             continue;
 
-        // set scope ID to interface index
-        ((struct sockaddr_in6 *)ifa->ifa_addr)->sin6_scope_id =
-            getIndex(sock, ifa->ifa_name);
+        memset(&ifr6, 0, sizeof(ifr6));
+        strlcpy(ifr6.ifr_name, ifa->ifa_name, sizeof(ifr6.ifr_name));
+        memcpy(&ifr6.ifr_addr, ifa->ifa_addr, MIN(sizeof(ifr6.ifr_addr), ifa->ifa_addr->sa_len));
 
-        // add interface to the list
-        ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, NULL,
-                    AF_INET6,
-                    translateIPv6AddressToPrefix((struct sockaddr_in6 *)
-                                                 ifa->ifa_netmask));
+        if (ioctl(sock, SIOCGIFNETMASK_IN6, (caddr_t)&ifr6) < 0) {
+            NET_ThrowByNameWithLastError(env , JNU_JAVANETPKG "SocketException",
+                             "ioctl SIOCGIFNETMASK_IN6 failed");
+            freeifaddrs(origifa);
+            freeif(ifs);
+            return NULL;
+        }
 
-        // if an exception occurred then free the list
+        /* Add to the list.  */
+        sin6 = (struct sockaddr_in6 *)&ifr6.ifr_addr;
+        ifs = addif(env, sock, ifa->ifa_name, ifs, ifa->ifa_addr, AF_INET6,
+                    prefix(&sin6->sin6_addr, sizeof(struct in6_addr)));
+
+        /* If an exception occurred then free the list.  */
         if ((*env)->ExceptionOccurred(env)) {
             freeifaddrs(origifa);
             freeif(ifs);
@@ -2088,55 +2060,114 @@
         }
     }
 
-    // free ifaddrs buffer
+    /*
+     * Free socket and ifaddrs buffer
+     */
     freeifaddrs(origifa);
     return ifs;
 }
+#endif
 
-#endif /* AF_INET6 */
-
-/*
- * Try to get the interface index.
- */
-static int getIndex(int sock, const char *name) {
-#if !defined(__FreeBSD__)
-    int index = if_nametoindex(name);
-    return (index == 0) ? -1 : index;
-#else
+static int getIndex(int sock, const char *name){
+#ifdef __FreeBSD__
+     /*
+      * Try to get the interface index
+      * (Not supported on Solaris 2.6 or 7)
+      */
     struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, name, sizeof(if2.ifr_name) - 1);
+    strcpy(if2.ifr_name, name);
 
     if (ioctl(sock, SIOCGIFINDEX, (char *)&if2) < 0) {
         return -1;
     }
 
     return if2.ifr_index;
+#else
+    /*
+     * Try to get the interface index using BSD specific if_nametoindex
+     */
+    int index = if_nametoindex(name);
+    return (index == 0) ? -1 : index;
 #endif
 }
 
-/*
- * Gets the Hardware address (usually MAC address) for the named interface.
- * On return puts the data in buf, and returns the length, in byte, of the
+/**
+ * Returns the IPv4 broadcast address of a named interface, if it exists.
+ * Returns 0 if it doesn't have one.
+ */
+static struct sockaddr *getBroadcast(JNIEnv *env, int sock, const char *ifname, struct sockaddr *brdcast_store) {
+  struct sockaddr *ret = NULL;
+  struct ifreq if2;
+
+  memset((char *) &if2, 0, sizeof(if2));
+  strcpy(if2.ifr_name, ifname);
+
+  /* Let's make sure the interface does have a broadcast address */
+  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
+      NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFFLAGS failed");
+      return ret;
+  }
+
+  if (if2.ifr_flags & IFF_BROADCAST) {
+      /* It does, let's retrieve it*/
+      if (ioctl(sock, SIOCGIFBRDADDR, (char *)&if2) < 0) {
+          NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFBRDADDR failed");
+          return ret;
+      }
+
+      ret = brdcast_store;
+      memcpy(ret, &if2.ifr_broadaddr, sizeof(struct sockaddr));
+  }
+
+  return ret;
+}
+
+/**
+ * Returns the IPv4 subnet prefix length (aka subnet mask) for the named
+ * interface, if it has one, otherwise return -1.
+ */
+static short getSubnet(JNIEnv *env, int sock, const char *ifname) {
+    unsigned int mask;
+    short ret;
+    struct ifreq if2;
+
+    memset((char *) &if2, 0, sizeof(if2));
+    strcpy(if2.ifr_name, ifname);
+
+    if (ioctl(sock, SIOCGIFNETMASK, (char *)&if2) < 0) {
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFNETMASK failed");
+        return -1;
+    }
+
+    mask = ntohl(((struct sockaddr_in*)&(if2.ifr_addr))->sin_addr.s_addr);
+    ret = 0;
+    while (mask) {
+       mask <<= 1;
+       ret++;
+    }
+
+    return ret;
+}
+
+/**
+ * Get the Hardware address (usually MAC address) for the named interface.
+ * return puts the data in buf, and returns the length, in byte, of the
  * MAC address. Returns -1 if there is no hardware address on that interface.
  */
-static int getMacAddress
-  (JNIEnv *env, const char *ifname, const struct in_addr *addr,
-   unsigned char *buf)
-{
+static int getMacAddress(JNIEnv *env, int sock, const char* ifname, const struct in_addr* addr, unsigned char *buf) {
     struct ifaddrs *ifa0, *ifa;
     struct sockaddr *saddr;
     int i;
 
-    // grab the interface list
+    /* Grab the interface list */
     if (!getifaddrs(&ifa0)) {
-        // cycle through the interfaces
+        /* Cycle through the interfaces */
         for (i = 0, ifa = ifa0; ifa != NULL; ifa = ifa->ifa_next, i++) {
             saddr = ifa->ifa_addr;
-            // link layer contains the MAC address
+            /* Link layer contains the MAC address */
             if (saddr->sa_family == AF_LINK && !strcmp(ifname, ifa->ifa_name)) {
                 struct sockaddr_dl *sadl = (struct sockaddr_dl *) saddr;
-                // check the address has the correct length
+                /* Check the address is the correct length */
                 if (sadl->sdl_alen == ETHER_ADDR_LEN) {
                     memcpy(buf, (sadl->sdl_data + sadl->sdl_nlen), ETHER_ADDR_LEN);
                     freeifaddrs(ifa0);
@@ -2150,34 +2181,37 @@
     return -1;
 }
 
-static int getMTU(JNIEnv *env, int sock, const char *ifname) {
+static int getMTU(JNIEnv *env, int sock,  const char *ifname) {
     struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
+
+    memset((char *) &if2, 0, sizeof(if2));
+    strcpy(if2.ifr_name, ifname);
 
     if (ioctl(sock, SIOCGIFMTU, (char *)&if2) < 0) {
-        NET_ThrowByNameWithLastError
-            (env, JNU_JAVANETPKG "SocketException", "ioctl(SIOCGIFMTU) failed");
+        NET_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException", "IOCTL SIOCGIFMTU failed");
         return -1;
     }
 
-    return if2.ifr_mtu;
+    return  if2.ifr_mtu;
 }
 
 static int getFlags(int sock, const char *ifname, int *flags) {
-    struct ifreq if2;
-    memset((char *)&if2, 0, sizeof(if2));
-    strncpy(if2.ifr_name, ifname, sizeof(if2.ifr_name) - 1);
+  struct ifreq if2;
+  int ret = -1;
 
-    if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0) {
-        return -1;
-    }
+  memset((char *) &if2, 0, sizeof(if2));
+  strcpy(if2.ifr_name, ifname);
 
-    if (sizeof(if2.ifr_flags) == sizeof(short)) {
-        *flags = (if2.ifr_flags & 0xffff);
-    } else {
-        *flags = if2.ifr_flags;
-    }
-    return 0;
+  if (ioctl(sock, SIOCGIFFLAGS, (char *)&if2) < 0){
+      return -1;
+  }
+
+  if (sizeof(if2.ifr_flags) == sizeof(short)) {
+    *flags = (if2.ifr_flags & 0xffff);
+  } else {
+    *flags = if2.ifr_flags;
+  }
+  return 0;
 }
-#endif /* _ALLBSD_SOURCE */
+
+#endif
diff --git a/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c b/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c
index c48d115..77899d6 100644
--- a/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c
+++ b/jdk/src/solaris/native/java/net/PlainDatagramSocketImpl.c
@@ -174,8 +174,9 @@
     IO_fd_fdID = NET_GetFileDescriptorID(env);
     CHECK_NULL(IO_fd_fdID);
 
-    initInetAddressIDs(env);
-    JNU_CHECK_EXCEPTION(env);
+    Java_java_net_InetAddress_init(env, 0);
+    Java_java_net_Inet4Address_init(env, 0);
+    Java_java_net_Inet6Address_init(env, 0);
     Java_java_net_NetworkInterface_init(env, 0);
 
 }
@@ -991,24 +992,17 @@
                        (char *)&arg, sizeof(arg)) < 0) {
         getErrorString(errno, tmpbuf, sizeof(tmpbuf));
         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", tmpbuf);
-        close(fd);
         return;
     }
     if (JVM_SetSockOpt(fd, SOL_SOCKET, SO_RCVBUF,
                        (char *)&arg, sizeof(arg)) < 0) {
         getErrorString(errno, tmpbuf, sizeof(tmpbuf));
         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", tmpbuf);
-        close(fd);
         return;
     }
 #endif /* __APPLE__ */
 
-    if (setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (char*) &t, sizeof (int)) < 0) {
-        getErrorString(errno, tmpbuf, sizeof(tmpbuf));
-        JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", tmpbuf);
-        close(fd);
-        return;
-    }
+     setsockopt(fd, SOL_SOCKET, SO_BROADCAST, (char*) &t, sizeof(int));
 
 #if defined(__linux__)
     arg = 0;
@@ -1030,13 +1024,8 @@
      */
     if (domain == AF_INET6) {
         int ttl = 1;
-        if (setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *) &ttl,
-                sizeof (ttl)) < 0) {
-            getErrorString(errno, tmpbuf, sizeof(tmpbuf));
-            JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", tmpbuf);
-            close(fd);
-            return;
-        }
+        setsockopt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (char *)&ttl,
+                   sizeof(ttl));
     }
 #endif /* __linux__ */
 
@@ -2193,7 +2182,7 @@
             caddr[14] = ((address >> 8) & 0xff);
             caddr[15] = (address & 0xff);
         } else {
-            getInet6Address_ipaddress(env, iaObj, (char *) caddr);
+            getInet6Address_ipaddress(env, iaObj, caddr);
         }
 
         memcpy((void *)&(mname6.ipv6mr_multiaddr), caddr, sizeof(struct in6_addr));
diff --git a/jdk/src/solaris/native/java/net/PlainSocketImpl.c b/jdk/src/solaris/native/java/net/PlainSocketImpl.c
index 71cbdf8..724c1cf 100644
--- a/jdk/src/solaris/native/java/net/PlainSocketImpl.c
+++ b/jdk/src/solaris/native/java/net/PlainSocketImpl.c
@@ -162,9 +162,6 @@
     IO_fd_fdID = NET_GetFileDescriptorID(env);
     CHECK_NULL(IO_fd_fdID);
 
-    initInetAddressIDs(env);
-    JNU_CHECK_EXCEPTION(env);
-
     /* Create the marker fd used for dup2 */
     marker_fd = getMarkerFD();
 }
diff --git a/jdk/src/solaris/native/sun/awt/awt_Robot.c b/jdk/src/solaris/native/sun/awt/awt_Robot.c
index b8f1b75..89f282c 100644
--- a/jdk/src/solaris/native/sun/awt/awt_Robot.c
+++ b/jdk/src/solaris/native/sun/awt/awt_Robot.c
@@ -61,9 +61,9 @@
 
     /* check if XTest is available */
     isXTestAvailable = XQueryExtension(awt_display, XTestExtensionName, &major_opcode, &first_event, &first_error);
+    DTRACE_PRINTLN3("RobotPeer: XQueryExtension(XTEST) returns major_opcode = %d, first_event = %d, first_error = %d",
+                    major_opcode, first_event, first_error);
     if (isXTestAvailable) {
-        DTRACE_PRINTLN3("RobotPeer: XQueryExtension(XTEST) returns major_opcode = %d, first_event = %d, first_error = %d",
-                        major_opcode, first_event, first_error);
         /* check if XTest version is OK */
         XTestQueryExtension(awt_display, &event_basep, &error_basep, &majorp, &minorp);
         DTRACE_PRINTLN4("RobotPeer: XTestQueryExtension returns event_basep = %d, error_basep = %d, majorp = %d, minorp = %d",
diff --git a/jdk/src/solaris/native/sun/awt/fontpath.c b/jdk/src/solaris/native/sun/awt/fontpath.c
index 4ebf381..3d1d020 100644
--- a/jdk/src/solaris/native/sun/awt/fontpath.c
+++ b/jdk/src/solaris/native/sun/awt/fontpath.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1998, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1998, 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
@@ -804,36 +804,30 @@
     pattern = (*FcPatternBuild)(NULL, FC_OUTLINE, FcTypeBool, FcTrue, NULL);
     objset = (*FcObjectSetBuild)(FC_FILE, NULL);
     fontSet = (*FcFontList)(NULL, pattern, objset);
-    if (fontSet == NULL) {
-        /* FcFontList() may return NULL if fonts are not installed. */
-        fontdirs = NULL;
-    } else {
-        fontdirs = (char**)calloc(fontSet->nfont+1, sizeof(char*));
-        for (f=0; f < fontSet->nfont; f++) {
-            FcChar8 *file;
-            FcChar8 *dir;
-            if ((*FcPatternGetString)(fontSet->fonts[f], FC_FILE, 0, &file) ==
-                                      FcResultMatch) {
-                dir = (*FcStrDirname)(file);
-                found = 0;
-                for (i=0;i<numdirs; i++) {
-                    if (strcmp(fontdirs[i], (char*)dir) == 0) {
-                        found = 1;
-                        break;
-                    }
-                }
-                if (!found) {
-                    fontdirs[numdirs++] = (char*)dir;
-                } else {
-                    free((char*)dir);
+    fontdirs = (char**)calloc(fontSet->nfont+1, sizeof(char*));
+    for (f=0; f < fontSet->nfont; f++) {
+        FcChar8 *file;
+        FcChar8 *dir;
+        if ((*FcPatternGetString)(fontSet->fonts[f], FC_FILE, 0, &file) ==
+                                  FcResultMatch) {
+            dir = (*FcStrDirname)(file);
+            found = 0;
+            for (i=0;i<numdirs; i++) {
+                if (strcmp(fontdirs[i], (char*)dir) == 0) {
+                    found = 1;
+                    break;
                 }
             }
+            if (!found) {
+                fontdirs[numdirs++] = (char*)dir;
+            } else {
+                free((char*)dir);
+            }
         }
-        /* Free fontset if one was returned */
-        (*FcFontSetDestroy)(fontSet);
     }
 
     /* Free memory and close the ".so" */
+    (*FcFontSetDestroy)(fontSet);
     (*FcPatternDestroy)(pattern);
     closeFontConfig(libfontconfig, JNI_TRUE);
     return fontdirs;
diff --git a/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c b/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c
index bf7d578..f5dd361 100644
--- a/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c
+++ b/jdk/src/solaris/native/sun/nio/ch/DatagramChannelImpl.c
@@ -201,7 +201,7 @@
     }
     if (senderAddr == NULL) {
         jobject isa = NULL;
-        int port = 0;
+        int port;
         jobject ia = NET_SockaddrToInetAddress(env, (struct sockaddr *)&sa, &port);
         if (ia != NULL) {
             isa = (*env)->NewObject(env, isa_class, isa_ctorID, ia, port);
diff --git a/jdk/src/solaris/native/sun/nio/ch/DevPollArrayWrapper.c b/jdk/src/solaris/native/sun/nio/ch/DevPollArrayWrapper.c
index 6860a16..962f5e4 100644
--- a/jdk/src/solaris/native/sun/nio/ch/DevPollArrayWrapper.c
+++ b/jdk/src/solaris/native/sun/nio/ch/DevPollArrayWrapper.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 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
@@ -94,7 +94,6 @@
                     return 0;
                 }
                 start = now;
-                a.dp_timeout = remaining;
             }
         } else {
             return res;
diff --git a/jdk/src/solaris/native/sun/nio/ch/EPollArrayWrapper.c b/jdk/src/solaris/native/sun/nio/ch/EPollArrayWrapper.c
index 12b1c85..c7b391f 100644
--- a/jdk/src/solaris/native/sun/nio/ch/EPollArrayWrapper.c
+++ b/jdk/src/solaris/native/sun/nio/ch/EPollArrayWrapper.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 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
@@ -53,7 +53,7 @@
     start = t.tv_sec * 1000 + t.tv_usec / 1000;
 
     for (;;) {
-        int res = epoll_wait(epfd, events, numfds, remaining);
+        int res = epoll_wait(epfd, events, numfds, timeout);
         if (res < 0 && errno == EINTR) {
             if (remaining >= 0) {
                 gettimeofday(&t, NULL);
diff --git a/jdk/src/solaris/native/sun/nio/ch/IOUtil.c b/jdk/src/solaris/native/sun/nio/ch/IOUtil.c
index d8bbe84..438bf41 100644
--- a/jdk/src/solaris/native/sun/nio/ch/IOUtil.c
+++ b/jdk/src/solaris/native/sun/nio/ch/IOUtil.c
@@ -35,7 +35,6 @@
 #include "java_lang_Integer.h"
 #include "nio.h"
 #include "nio_util.h"
-#include "net_util.h"
 
 static jfieldID fd_fdID;        /* for jint 'fd' in java.io.FileDescriptor */
 
@@ -45,7 +44,6 @@
 {
     CHECK_NULL(clazz = (*env)->FindClass(env, "java/io/FileDescriptor"));
     CHECK_NULL(fd_fdID = (*env)->GetFieldID(env, clazz, "fd", "I"));
-    initInetAddressIDs(env);
 }
 
 JNIEXPORT jboolean JNICALL
diff --git a/jdk/src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c b/jdk/src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c
index 04a400a..e96c9b0 100644
--- a/jdk/src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c
+++ b/jdk/src/solaris/native/sun/nio/ch/ServerSocketChannelImpl.c
@@ -84,7 +84,7 @@
     int alloc_len;
     jobject remote_ia = 0;
     jobject isa;
-    jint remote_port = 0;
+    jint remote_port;
 
     NET_AllocSockaddr(&sa, &alloc_len);
     if (sa == NULL) {
diff --git a/jdk/src/solaris/native/sun/nio/ch/sctp/SctpNet.c b/jdk/src/solaris/native/sun/nio/ch/sctp/SctpNet.c
index 9c3efc0..1b700bb 100644
--- a/jdk/src/solaris/native/sun/nio/ch/sctp/SctpNet.c
+++ b/jdk/src/solaris/native/sun/nio/ch/sctp/SctpNet.c
@@ -157,7 +157,6 @@
     }
     preCloseFD = sp[0];
     close(sp[1]);
-    initInetAddressIDs(env);
 }
 
 /*
@@ -431,7 +430,7 @@
     paddr = addr_buf;
     for (i=0; i<addrCount; i++) {
         jobject ia, isa = NULL;
-        int port = 0;
+        int port;
         sap = (struct sockaddr*)addr_buf;
         ia = NET_SockaddrToInetAddress(env, sap, &port);
         if (ia != NULL)
@@ -543,7 +542,6 @@
     void *arg;
     int arglen;
 
-    memset((char *) &linger, 0, sizeof(linger));
     if (mapSocketOption(opt, &klevel, &kopt) < 0) {
         JNU_ThrowByNameWithLastError(env, JNU_JAVANETPKG "SocketException",
                                      "Unsupported socket option");
@@ -601,7 +599,7 @@
   (JNIEnv *env, jclass klass, jint fd, jint assocId, jobject iaObj, jint port) {
     struct sctp_setprim prim;
     struct sockaddr* sap = (struct sockaddr*)&prim.ssp_addr;
-    int sap_len = sizeof(sap);
+    int sap_len;
 
     if (NET_InetAddressToSockaddr(env, iaObj, port, sap,
                                   &sap_len, JNI_TRUE) != 0) {
@@ -626,7 +624,7 @@
    jobject iaObj, jint port, jboolean preferIPv6) {
     struct sctp_setpeerprim prim;
     struct sockaddr* sap = (struct sockaddr*)&prim.sspp_addr;
-    int sap_len = sizeof(sap);
+    int sap_len;
 
     if (NET_InetAddressToSockaddr(env, iaObj, port, sap,
                                   &sap_len, preferIPv6) != 0) {
diff --git a/jdk/src/solaris/native/sun/nio/fs/MacOSXNativeDispatcher.c b/jdk/src/solaris/native/sun/nio/fs/MacOSXNativeDispatcher.c
index 5c75293..f3602b8 100644
--- a/jdk/src/solaris/native/sun/nio/fs/MacOSXNativeDispatcher.c
+++ b/jdk/src/solaris/native/sun/nio/fs/MacOSXNativeDispatcher.c
@@ -39,15 +39,12 @@
                                                      jint form)
 {
     jcharArray result = NULL;
-    char *chars;
+    char chars_buf[(PATH_MAX + 1) * 2];     // utf16 + zero padding
     CFMutableStringRef csref = CFStringCreateMutable(NULL, 0);
     if (csref == NULL) {
         JNU_ThrowOutOfMemoryError(env, "native heap");
-        return NULL;
-    }
-    chars = (char*)(*env)->GetPrimitiveArrayCritical(env, path, 0);
-    if (chars != NULL) {
-        char chars_buf[(PATH_MAX + 1) * 2];     // utf16 + zero padding
+    } else {
+        char *chars = (char*)(*env)->GetPrimitiveArrayCritical(env, path, 0);
         jsize len = (*env)->GetArrayLength(env, path);
         CFStringAppendCharacters(csref, (const UniChar*)chars, len);
         (*env)->ReleasePrimitiveArrayCritical(env, path, chars, 0);
@@ -56,26 +53,24 @@
         if (len < PATH_MAX) {
             if (CFStringGetCString(csref, chars_buf, sizeof(chars_buf), kCFStringEncodingUTF16)) {
                 result = (*env)->NewCharArray(env, len);
-                if (result != NULL) {
-                    (*env)->SetCharArrayRegion(env, result, 0, len, (jchar*)&chars_buf);
-                }
+                (*env)->SetCharArrayRegion(env, result, 0, len, (jchar*)&chars_buf);
             }
         } else {
             int ulen = (len + 1) * 2;
             chars = malloc(ulen);
             if (chars == NULL) {
+                CFRelease(csref);
                 JNU_ThrowOutOfMemoryError(env, "native heap");
+                return result;
             } else {
                 if (CFStringGetCString(csref, chars, ulen, kCFStringEncodingUTF16)) {
                     result = (*env)->NewCharArray(env, len);
-                    if (result != NULL) {
-                        (*env)->SetCharArrayRegion(env, result, 0, len, (jchar*)chars);
-                    }
+                    (*env)->SetCharArrayRegion(env, result, 0, len, (jchar*)chars);
                 }
                 free(chars);
             }
         }
+        CFRelease(csref);
     }
-    CFRelease(csref);
     return result;
 }
diff --git a/jdk/src/solaris/native/sun/xawt/XToolkit.c b/jdk/src/solaris/native/sun/xawt/XToolkit.c
index 71d41f3..099c167 100644
--- a/jdk/src/solaris/native/sun/xawt/XToolkit.c
+++ b/jdk/src/solaris/native/sun/xawt/XToolkit.c
@@ -1020,9 +1020,9 @@
      * before calling XTestFakeButtonEvent().
      */
     xinputAvailable = XQueryExtension(awt_display, INAME, &major_opcode, &first_event, &first_error);
+    DTRACE_PRINTLN3("RobotPeer: XQueryExtension(XINPUT) returns major_opcode = %d, first_event = %d, first_error = %d",
+                    major_opcode, first_event, first_error);
     if (xinputAvailable) {
-        DTRACE_PRINTLN3("RobotPeer: XQueryExtension(XINPUT) returns major_opcode = %d, first_event = %d, first_error = %d",
-                        major_opcode, first_event, first_error);
         devices = XListInputDevices(awt_display, &numDevices);
         for (devIdx = 0; devIdx < numDevices; devIdx++) {
             aDevice = &(devices[devIdx]);
diff --git a/jdk/src/windows/bin/cmdtoargs.c b/jdk/src/windows/bin/cmdtoargs.c
index 29e5e77..352b155 100644
--- a/jdk/src/windows/bin/cmdtoargs.c
+++ b/jdk/src/windows/bin/cmdtoargs.c
@@ -155,7 +155,6 @@
                 }
             }
             dest += copyCh(ch, dest);
-            slashes = 0;
             break;
 
         default:
diff --git a/jdk/src/windows/classes/sun/awt/windows/fontconfig.properties b/jdk/src/windows/classes/sun/awt/windows/fontconfig.properties
index 3a2e2b3..6e488ee 100644
--- a/jdk/src/windows/classes/sun/awt/windows/fontconfig.properties
+++ b/jdk/src/windows/classes/sun/awt/windows/fontconfig.properties
@@ -40,7 +40,6 @@
 allfonts.dingbats=Wingdings
 allfonts.lucida=Lucida Sans Regular
 allfonts.symbol=Symbol
-allfonts.symbols=Segoe UI Symbol
 allfonts.thai=Lucida Sans Regular
 allfonts.georgian=Sylfaen
 
@@ -237,7 +236,7 @@
 
 sequence.allfonts.x-windows-874=alphabetic,thai,dingbats,symbol
 
-sequence.fallback=lucida,symbols,\
+sequence.fallback=lucida,\
                   chinese-ms950,chinese-hkscs,chinese-ms936,chinese-gb18030,\
                   japanese,korean,chinese-ms950-extb,chinese-ms936-extb,georgian
 
@@ -299,4 +298,3 @@
 filename.Wingdings=WINGDING.TTF
 
 filename.Sylfaen=sylfaen.ttf
-filename.Segoe_UI_Symbol=SEGUISYM.TTF
diff --git a/jdk/src/windows/classes/sun/java2d/d3d/D3DMaskFill.java b/jdk/src/windows/classes/sun/java2d/d3d/D3DMaskFill.java
index dae1d08..e5e3d25 100644
--- a/jdk/src/windows/classes/sun/java2d/d3d/D3DMaskFill.java
+++ b/jdk/src/windows/classes/sun/java2d/d3d/D3DMaskFill.java
@@ -26,7 +26,6 @@
 package sun.java2d.d3d;
 
 import java.awt.Composite;
-import sun.java2d.InvalidPipeException;
 import sun.java2d.SunGraphics2D;
 import sun.java2d.loops.GraphicsPrimitive;
 import sun.java2d.loops.GraphicsPrimitiveMgr;
@@ -68,13 +67,7 @@
     protected void validateContext(SunGraphics2D sg2d,
                                    Composite comp, int ctxflags)
     {
-        D3DSurfaceData dstData;
-        try {
-            dstData = (D3DSurfaceData) sg2d.surfaceData;
-        } catch (ClassCastException e) {
-            throw new InvalidPipeException("wrong surface data type: " +
-                                           sg2d.surfaceData);
-        }
+        D3DSurfaceData dstData = (D3DSurfaceData)sg2d.surfaceData;
         D3DContext.validateContext(dstData, dstData,
                                    sg2d.getCompClip(), comp,
                                    null, sg2d.paint, sg2d, ctxflags);
diff --git a/jdk/src/windows/classes/sun/security/mscapi/Key.java b/jdk/src/windows/classes/sun/security/mscapi/Key.java
index 8154c48..0124ffb 100644
--- a/jdk/src/windows/classes/sun/security/mscapi/Key.java
+++ b/jdk/src/windows/classes/sun/security/mscapi/Key.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 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
@@ -30,6 +30,7 @@
 /**
  * The handle for an RSA or DSA key using the Microsoft Crypto API.
  *
+ * @see DSAPrivateKey
  * @see RSAPrivateKey
  * @see RSAPublicKey
  *
@@ -40,35 +41,9 @@
 {
     private static final long serialVersionUID = -1088859394025049194L;
 
-    static class NativeHandles {
-        long hCryptProv = 0;
-        long hCryptKey = 0;
-
-        public NativeHandles(long hCryptProv, long hCryptKey) {
-            this.hCryptProv = hCryptProv;
-            this.hCryptKey = hCryptKey;
-        }
-
-        /**
-         * Finalization method
-         */
-        protected void finalize() throws Throwable
-        {
-            try {
-                synchronized(this)
-                {
-                    cleanUp(hCryptProv, hCryptKey);
-                    hCryptProv = 0;
-                    hCryptKey = 0;
-                }
-
-            } finally {
-                super.finalize();
-            }
-        }
-    }
-
-    protected NativeHandles handles;
+    // Native handle
+    protected long hCryptProv = 0;
+    protected long hCryptKey = 0;
 
     // Key length
     protected int keyLength = 0;
@@ -76,13 +51,32 @@
     /**
      * Construct a Key object.
      */
-    protected Key(NativeHandles handles, int keyLength)
+    protected Key(long hCryptProv, long hCryptKey, int keyLength)
     {
-        this.handles = handles;
+        this.hCryptProv = hCryptProv;
+        this.hCryptKey = hCryptKey;
         this.keyLength = keyLength;
     }
 
     /**
+     * Finalization method
+     */
+    protected void finalize() throws Throwable
+    {
+        try {
+            synchronized(this)
+            {
+                cleanUp(hCryptProv, hCryptKey);
+                hCryptProv = 0;
+                hCryptKey = 0;
+            }
+
+        } finally {
+            super.finalize();
+        }
+    }
+
+    /**
      * Native method to cleanup the key handle.
      */
     private native static void cleanUp(long hCryptProv, long hCryptKey);
@@ -102,7 +96,7 @@
      */
     public long getHCryptKey()
     {
-        return handles.hCryptKey;
+        return hCryptKey;
     }
 
     /**
@@ -110,12 +104,12 @@
      */
     public long getHCryptProvider()
     {
-        return handles.hCryptProv;
+        return hCryptProv;
     }
 
     /**
      * Returns the standard algorithm name for this key. For
-     * example, "RSA" would indicate that this key is a RSA key.
+     * example, "DSA" would indicate that this key is a DSA key.
      * See Appendix A in the <a href=
      * "../../../guide/security/CryptoSpec.html#AppA">
      * Java Cryptography Architecture API Specification &amp; Reference </a>
diff --git a/jdk/src/windows/classes/sun/security/mscapi/KeyStore.java b/jdk/src/windows/classes/sun/security/mscapi/KeyStore.java
index 075ac78..cbf4240 100644
--- a/jdk/src/windows/classes/sun/security/mscapi/KeyStore.java
+++ b/jdk/src/windows/classes/sun/security/mscapi/KeyStore.java
@@ -169,7 +169,7 @@
             }
             certChain = chain;
         }
-    }
+    };
 
     /*
      * An X.509 certificate factory.
@@ -800,8 +800,7 @@
             }
 
             storeWithUniqueAlias(alias, new KeyEntry(alias,
-                    new RSAPrivateKey(new Key.NativeHandles(hCryptProv,
-                            hCryptKey), keyLength),
+                    new RSAPrivateKey(hCryptProv, hCryptKey, keyLength),
                     certChain));
         }
         catch (Throwable e)
@@ -857,6 +856,7 @@
      * Load keys and/or certificates from keystore into Collection.
      *
      * @param name Name of keystore.
+     * @param entries Collection of key/certificate.
      */
     private native void loadKeysOrCertificateChains(String name)
             throws KeyStoreException;
diff --git a/jdk/src/windows/classes/sun/security/mscapi/RSAKeyPair.java b/jdk/src/windows/classes/sun/security/mscapi/RSAKeyPair.java
index 0880c20..6fba2a2 100644
--- a/jdk/src/windows/classes/sun/security/mscapi/RSAKeyPair.java
+++ b/jdk/src/windows/classes/sun/security/mscapi/RSAKeyPair.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
  * 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,9 +41,8 @@
      */
     RSAKeyPair(long hCryptProv, long hCryptKey, int keyLength)
     {
-        Key.NativeHandles handles = new Key.NativeHandles(hCryptProv, hCryptKey);
-        privateKey = new RSAPrivateKey(handles, keyLength);
-        publicKey = new RSAPublicKey(handles, keyLength);
+        privateKey = new RSAPrivateKey(hCryptProv, hCryptKey, keyLength);
+        publicKey = new RSAPublicKey(hCryptProv, hCryptKey, keyLength);
     }
 
     public RSAPrivateKey getPrivate() {
diff --git a/jdk/src/windows/classes/sun/security/mscapi/RSAPrivateKey.java b/jdk/src/windows/classes/sun/security/mscapi/RSAPrivateKey.java
index ca692df..bc530f5 100644
--- a/jdk/src/windows/classes/sun/security/mscapi/RSAPrivateKey.java
+++ b/jdk/src/windows/classes/sun/security/mscapi/RSAPrivateKey.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,15 +42,7 @@
      */
     RSAPrivateKey(long hCryptProv, long hCryptKey, int keyLength)
     {
-        super(new NativeHandles(hCryptProv, hCryptKey), keyLength);
-    }
-
-    /**
-     * Construct an RSAPrivateKey object.
-     */
-    RSAPrivateKey(NativeHandles handles, int keyLength)
-    {
-        super(handles, keyLength);
+        super(hCryptProv, hCryptKey, keyLength);
     }
 
     /**
@@ -71,8 +63,8 @@
     public String toString()
     {
         return "RSAPrivateKey [size=" + keyLength + " bits, type=" +
-            getKeyType(handles.hCryptKey) + ", container=" +
-            getContainerName(handles.hCryptProv) + "]";
+            getKeyType(hCryptKey) + ", container=" +
+            getContainerName(hCryptProv) + "]";
     }
 
     // This class is not serializable
diff --git a/jdk/src/windows/classes/sun/security/mscapi/RSAPublicKey.java b/jdk/src/windows/classes/sun/security/mscapi/RSAPublicKey.java
index 52081ab..a62d783 100644
--- a/jdk/src/windows/classes/sun/security/mscapi/RSAPublicKey.java
+++ b/jdk/src/windows/classes/sun/security/mscapi/RSAPublicKey.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -51,15 +51,7 @@
      */
     RSAPublicKey(long hCryptProv, long hCryptKey, int keyLength)
     {
-        super(new NativeHandles(hCryptProv, hCryptKey), keyLength);
-    }
-
-    /**
-     * Construct an RSAPublicKey object.
-     */
-    RSAPublicKey(NativeHandles handles, int keyLength)
-    {
-        super(handles, keyLength);
+        super(hCryptProv, hCryptKey, keyLength);
     }
 
     /**
@@ -85,8 +77,8 @@
         StringBuffer sb = new StringBuffer();
 
         sb.append("RSAPublicKey [size=").append(keyLength)
-            .append(" bits, type=").append(getKeyType(handles.hCryptKey))
-            .append(", container=").append(getContainerName(handles.hCryptProv))
+            .append(" bits, type=").append(getKeyType(hCryptKey))
+            .append(", container=").append(getContainerName(hCryptProv))
             .append("]\n  modulus: ").append(getModulus())
             .append("\n  public exponent: ").append(getPublicExponent());
 
@@ -101,7 +93,7 @@
         if (exponent == null) {
 
             try {
-                publicKeyBlob = getPublicKeyBlob(handles.hCryptKey);
+                publicKeyBlob = getPublicKeyBlob(hCryptKey);
                 exponent = new BigInteger(1, getExponent(publicKeyBlob));
 
             } catch (KeyException e) {
@@ -120,7 +112,7 @@
         if (modulus == null) {
 
             try {
-                publicKeyBlob = getPublicKeyBlob(handles.hCryptKey);
+                publicKeyBlob = getPublicKeyBlob(hCryptKey);
                 modulus = new BigInteger(1, getModulus(publicKeyBlob));
 
             } catch (KeyException e) {
diff --git a/jdk/src/windows/native/com/sun/security/auth/module/nt.c b/jdk/src/windows/native/com/sun/security/auth/module/nt.c
index 038ceb1..64ef356 100644
--- a/jdk/src/windows/native/com/sun/security/auth/module/nt.c
+++ b/jdk/src/windows/native/com/sun/security/auth/module/nt.c
@@ -43,12 +43,6 @@
 BOOL getTextualSid(PSID pSid, LPTSTR TextualSid, LPDWORD lpdwBufferLen);
 void DisplayErrorText(DWORD dwLastError);
 
-static void throwIllegalArgumentException(JNIEnv *env, const char *msg) {
-    jclass clazz = (*env)->FindClass(env, "java/lang/IllegalArgumentException");
-    if (clazz != NULL)
-        (*env)->ThrowNew(env, clazz, msg);
-}
-
 JNIEXPORT jlong JNICALL
 Java_com_sun_security_auth_module_NTSystem_getImpersonationToken0
         (JNIEnv *env, jobject obj) {
@@ -68,6 +62,7 @@
 
     long i, j = 0;
     HANDLE tokenHandle = INVALID_HANDLE_VALUE;
+    BOOL systemError = FALSE;
 
     LPTSTR userName = NULL;             // user name
     LPTSTR userSid = NULL;              // user sid
@@ -121,59 +116,70 @@
 
     fid = (*env)->GetFieldID(env, cls, "userName", "Ljava/lang/String;");
     if (fid == 0) {
-        (*env)->ExceptionClear(env);
-        throwIllegalArgumentException(env, "invalid field: userName");
-        goto cleanup;
+        jclass newExcCls =
+            (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+        if (newExcCls == 0) {
+            // Unable to find exception class
+            systemError = TRUE;
+            goto out;
+        }
+        (*env)->ThrowNew(env, newExcCls, "invalid field: userName");
     }
     jstr = (*env)->NewStringUTF(env, userName);
-    if (jstr == NULL)
-        goto cleanup;
     (*env)->SetObjectField(env, obj, fid, jstr);
 
     fid = (*env)->GetFieldID(env, cls, "userSID", "Ljava/lang/String;");
     if (fid == 0) {
-        (*env)->ExceptionClear(env);
-        throwIllegalArgumentException(env, "invalid field: userSID");
-        goto cleanup;
+        jclass newExcCls =
+            (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+        if (newExcCls == 0) {
+            systemError = TRUE;
+            goto out;
+        }
+        (*env)->ThrowNew(env, newExcCls, "invalid field: userSID");
     }
     jstr = (*env)->NewStringUTF(env, userSid);
-    if (jstr == NULL)
-        goto cleanup;
     (*env)->SetObjectField(env, obj, fid, jstr);
 
     fid = (*env)->GetFieldID(env, cls, "domain", "Ljava/lang/String;");
     if (fid == 0) {
-        (*env)->ExceptionClear(env);
-        throwIllegalArgumentException(env, "invalid field: domain");
-        goto cleanup;
+        jclass newExcCls =
+            (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+        if (newExcCls == 0) {
+            systemError = TRUE;
+            goto out;
+        }
+        (*env)->ThrowNew(env, newExcCls, "invalid field: domain");
     }
     jstr = (*env)->NewStringUTF(env, domainName);
-    if (jstr == NULL)
-        goto cleanup;
     (*env)->SetObjectField(env, obj, fid, jstr);
 
     if (domainSid != NULL) {
         fid = (*env)->GetFieldID(env, cls, "domainSID", "Ljava/lang/String;");
         if (fid == 0) {
-            (*env)->ExceptionClear(env);
-            throwIllegalArgumentException(env, "invalid field: domainSID");
-            goto cleanup;
+            jclass newExcCls =
+                (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+            if (newExcCls == 0) {
+                systemError = TRUE;
+                goto out;
+            }
+            (*env)->ThrowNew(env, newExcCls, "invalid field: domainSID");
         }
         jstr = (*env)->NewStringUTF(env, domainSid);
-        if (jstr == NULL)
-            goto cleanup;
         (*env)->SetObjectField(env, obj, fid, jstr);
     }
 
     fid = (*env)->GetFieldID(env, cls, "primaryGroupID", "Ljava/lang/String;");
     if (fid == 0) {
-        (*env)->ExceptionClear(env);
-        throwIllegalArgumentException(env, "invalid field: PrimaryGroupID");
-        goto cleanup;
+        jclass newExcCls =
+            (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+        if (newExcCls == 0) {
+            systemError = TRUE;
+            goto out;
+        }
+        (*env)->ThrowNew(env, newExcCls, "invalid field: PrimaryGroupID");
     }
     jstr = (*env)->NewStringUTF(env, primaryGroup);
-    if (jstr == NULL)
-        goto cleanup;
     (*env)->SetObjectField(env, obj, fid, jstr);
 
     // primary group may or may not be part of supplementary groups
@@ -198,14 +204,19 @@
 
         fid = (*env)->GetFieldID(env, cls, "groupIDs", "[Ljava/lang/String;");
         if (fid == 0) {
-            (*env)->ExceptionClear(env);
-            throwIllegalArgumentException(env, "groupIDs");
-            goto cleanup;
+            jclass newExcCls =
+                (*env)->FindClass(env, "java/lang/IllegalArgumentException");
+            if (newExcCls == 0) {
+                systemError = TRUE;
+                goto out;
+            }
+            (*env)->ThrowNew(env, newExcCls, "invalid field: groupIDs");
         }
 
         stringClass = (*env)->FindClass(env, "java/lang/String");
-        if (stringClass == NULL)
-            goto cleanup;
+        if (stringClass == 0) {
+            goto out;
+        }
 
         if (pIndex == -1) {
             // primary group not in groups array
@@ -215,8 +226,6 @@
             // allocate one less array entry and do not add into new array
             jgroups = (*env)->NewObjectArray(env, numGroups-1, stringClass, 0);
         }
-        if (jgroups == NULL)
-            goto cleanup;
 
         for (i = 0, j = 0; i < (long)numGroups; i++) {
             if (pIndex == i) {
@@ -224,14 +233,12 @@
                 continue;
             }
             jstr = (*env)->NewStringUTF(env, groups[i]);
-            if (jstr == NULL)
-                goto cleanup;
             (*env)->SetObjectArrayElement(env, jgroups, j++, jstr);
         }
         (*env)->SetObjectField(env, obj, fid, jgroups);
     }
 
-cleanup:
+out:
     if (userName != NULL) {
         HeapFree(GetProcessHeap(), 0, userName);
     }
@@ -257,6 +264,11 @@
     }
     CloseHandle(tokenHandle);
 
+    if (systemError && debug) {
+        printf("  [getCurrent] System Error: ");
+        printf("unable to find IllegalArgumentException class\n");
+    }
+
     return;
 }
 
@@ -324,7 +336,7 @@
             DisplayErrorText(GetLastError());
         }
         error = TRUE;
-        goto cleanup;
+        goto out;
     }
 
     if (debug) {
@@ -357,7 +369,7 @@
             DisplayErrorText(GetLastError());
         }
         error = TRUE;
-        goto cleanup;
+        goto out;
     }
 
     if (debug) {
@@ -399,7 +411,7 @@
             DisplayErrorText(GetLastError());
         }
         // ok not to have a domain SID (no error)
-        goto cleanup;
+        goto out;
     }
 
     bufSize = 0;
@@ -410,7 +422,7 @@
         printf("  [getUser] domainSid: %s\n", *domainSid);
     }
 
-cleanup:
+out:
     if (tokenUserInfo != NULL) {
         HeapFree(GetProcessHeap(), 0, tokenUserInfo);
     }
@@ -454,7 +466,7 @@
             DisplayErrorText(GetLastError());
         }
         error = TRUE;
-        goto cleanup;
+        goto out;
     }
 
     if (debug) {
@@ -469,7 +481,7 @@
         printf("  [getPrimaryGroup] primaryGroup: %s\n", *primaryGroup);
     }
 
-cleanup:
+out:
     if (tokenGroupInfo != NULL) {
         HeapFree(GetProcessHeap(), 0, tokenGroupInfo);
     }
@@ -507,7 +519,7 @@
             DisplayErrorText(GetLastError());
         }
         error = TRUE;
-        goto cleanup;
+        goto out;
     }
 
     if (debug) {
@@ -516,7 +528,7 @@
 
     if (tokenGroupInfo->GroupCount == 0) {
         // no groups
-        goto cleanup;
+        goto out;
     }
 
     // return group info
@@ -533,7 +545,7 @@
         }
     }
 
-cleanup:
+out:
     if (tokenGroupInfo != NULL) {
         HeapFree(GetProcessHeap(), 0, tokenGroupInfo);
     }
diff --git a/jdk/src/windows/native/java/lang/ProcessEnvironment_md.c b/jdk/src/windows/native/java/lang/ProcessEnvironment_md.c
index e14299a..69bd50b 100644
--- a/jdk/src/windows/native/java/lang/ProcessEnvironment_md.c
+++ b/jdk/src/windows/native/java/lang/ProcessEnvironment_md.c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, 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
diff --git a/jdk/src/windows/native/java/lang/java_props_md.c b/jdk/src/windows/native/java/lang/java_props_md.c
index dc1e00f..8bf3718 100644
--- a/jdk/src/windows/native/java/lang/java_props_md.c
+++ b/jdk/src/windows/native/java/lang/java_props_md.c
@@ -188,7 +188,6 @@
         free(elems[index]);
     }
     } else {
-        free(ret);
         ret = NULL;
     }
 
diff --git a/jdk/src/windows/native/java/net/DualStackPlainSocketImpl.c b/jdk/src/windows/native/java/net/DualStackPlainSocketImpl.c
index 8a66607..604ea9f 100644
--- a/jdk/src/windows/native/java/net/DualStackPlainSocketImpl.c
+++ b/jdk/src/windows/native/java/net/DualStackPlainSocketImpl.c
@@ -47,7 +47,6 @@
     isa_class = (*env)->NewGlobalRef(env, cls);
     isa_ctorID = (*env)->GetMethodID(env, cls, "<init>",
                                      "(Ljava/net/InetAddress;I)V");
-    CHECK_NULL(isa_ctorID);
 
     // implement read timeout with select.
     isRcvTimeoutSupported = 0;
diff --git a/jdk/src/windows/native/java/net/Inet4AddressImpl.c b/jdk/src/windows/native/java/net/Inet4AddressImpl.c
index 9e7097e..bb7f110 100644
--- a/jdk/src/windows/native/java/net/Inet4AddressImpl.c
+++ b/jdk/src/windows/native/java/net/Inet4AddressImpl.c
@@ -33,7 +33,6 @@
 #include <process.h>
 #include <iphlpapi.h>
 #include <icmpapi.h>
-#include <WinError.h>
 
 #include "java_net_InetAddress.h"
 #include "java_net_Inet4AddressImpl.h"
@@ -114,6 +113,11 @@
     return JNU_NewStringPlatform(env, hostname);
 }
 
+static jclass ni_iacls;
+static jclass ni_ia4cls;
+static jmethodID ni_ia4ctrID;
+static int initialized = 0;
+
 /*
  * Find an internet address for a given hostname.  Not this this
  * code only works for addresses of type INET. The translation
@@ -138,8 +142,19 @@
 
     jobjectArray ret = NULL;
 
-    initInetAddressIDs(env);
-    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
+    if (!initialized) {
+      ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
+      CHECK_NULL_RETURN(ni_iacls, NULL);
+      ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
+      CHECK_NULL_RETURN(ni_iacls, NULL);
+      ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
+      CHECK_NULL_RETURN(ni_ia4cls, NULL);
+      ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
+      CHECK_NULL_RETURN(ni_ia4cls, NULL);
+      ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
+      CHECK_NULL_RETURN(ni_ia4ctrID, NULL);
+      initialized = 1;
+    }
 
     if (IS_NULL(host)) {
         JNU_ThrowNullPointerException(env, "host argument");
@@ -183,13 +198,13 @@
         address |= (addr[1]<<8) & 0xff00;
         address |= addr[0];
 
-        ret = (*env)->NewObjectArray(env, 1, ia_class, NULL);
+        ret = (*env)->NewObjectArray(env, 1, ni_iacls, NULL);
 
         if (IS_NULL(ret)) {
             goto cleanupAndReturn;
         }
 
-        iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+        iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
         if (IS_NULL(iaObj)) {
           ret = NULL;
           goto cleanupAndReturn;
@@ -213,7 +228,7 @@
             addrp++;
         }
 
-        ret = (*env)->NewObjectArray(env, i, ia_class, NULL);
+        ret = (*env)->NewObjectArray(env, i, ni_iacls, NULL);
 
         if (IS_NULL(ret)) {
             goto cleanupAndReturn;
@@ -222,7 +237,7 @@
         addrp = (struct in_addr **) hp->h_addr_list;
         i = 0;
         while (*addrp != (struct in_addr *) 0) {
-          jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+          jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
           if (IS_NULL(iaObj)) {
             ret = NULL;
             goto cleanupAndReturn;
@@ -277,6 +292,7 @@
 }
 
 
+
 static BOOL
 WindowsVersionCheck(WORD wMajorVersion, WORD wMinorVersion, WORD wServicePackMajor) {
     OSVERSIONINFOEXW osvi = { sizeof(osvi), 0, 0, 0, 0, {0}, 0, 0 };
@@ -300,7 +316,7 @@
 }
 
 static jboolean
-tcp_ping4(JNIEnv *env,
+wxp_ping4(JNIEnv *env,
           jbyteArray addrArray,
           jint timeout,
           jbyteArray ifArray,
@@ -455,26 +471,24 @@
 ping4(JNIEnv *env,
       unsigned long src_addr,
       unsigned long dest_addr,
-      jint timeout,
-      HANDLE hIcmpFile)
+      jint timeout)
 {
     // See https://msdn.microsoft.com/en-us/library/aa366050%28VS.85%29.aspx
 
+    HANDLE hIcmpFile;
     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
-    ReplySize = sizeof(ICMP_ECHO_REPLY)   // The buffer should be large enough
-                                          // to hold at least one ICMP_ECHO_REPLY
-                                          // structure
-                + sizeof(SendData)        // plus RequestSize bytes of data.
-                + 8;                      // This buffer should also be large enough
-                                          // to also hold 8 more bytes of data
-                                          // (the size of an ICMP error message)
+    hIcmpFile = IcmpCreateFile();
+    if (hIcmpFile == INVALID_HANDLE_VALUE) {
+        NET_ThrowNew(env, WSAGetLastError(), "Unable to open handle");
+        return JNI_FALSE;
+    }
 
+    ReplySize = sizeof(ICMP_ECHO_REPLY) + sizeof(SendData);
     ReplyBuffer = (VOID*) malloc(ReplySize);
     if (ReplyBuffer == NULL) {
         IcmpCloseHandle(hIcmpFile);
@@ -510,47 +524,10 @@
                                    (timeout < 1000) ? 1000 : timeout);   // DWORD Timeout
     }
 
-    if (dwRetVal == 0) { // if the call failed
-        TCHAR *buf;
-        DWORD err = WSAGetLastError();
-        switch (err) {
-            case ERROR_NO_NETWORK:
-            case ERROR_NETWORK_UNREACHABLE:
-            case ERROR_HOST_UNREACHABLE:
-            case ERROR_PROTOCOL_UNREACHABLE:
-            case ERROR_PORT_UNREACHABLE:
-            case ERROR_REQUEST_ABORTED:
-            case ERROR_INCORRECT_ADDRESS:
-            case ERROR_HOST_DOWN:
-            case ERROR_INVALID_COMPUTERNAME:
-            case ERROR_INVALID_NETNAME:
-            case WSAEHOSTUNREACH:   /* Host Unreachable */
-            case WSAENETUNREACH:    /* Network Unreachable */
-            case WSAENETDOWN:       /* Network is down */
-            case WSAEPFNOSUPPORT:   /* Protocol Family unsupported */
-            case IP_REQ_TIMED_OUT:
-                break;
-            default:
-                FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM,
-                        NULL, err, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
-                        (LPTSTR)&buf, 0, NULL);
-                NET_ThrowNew(env, err, buf);
-                LocalFree(buf);
-                break;
-        }
-    } else {
+    if (dwRetVal != 0) {
         PICMP_ECHO_REPLY pEchoReply = (PICMP_ECHO_REPLY)ReplyBuffer;
-
-        // This is to take into account the undocumented minimum
-        // timeout mentioned in the IcmpSendEcho call above.
-        // 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 ((int)pEchoReply->RoundTripTime <= timeout)
             ret = JNI_TRUE;
-        }
     }
 
     free(ReplyBuffer);
@@ -576,7 +553,6 @@
         jint dest_addr = 0;
         jbyte caddr[4];
         int sz;
-        HANDLE hIcmpFile;
 
         /**
          * Convert IP address from byte array to integer
@@ -607,20 +583,8 @@
             src_addr = htonl(src_addr);
         }
 
-        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);
-            } else {
-                NET_ThrowNew(env, err, "Unable to create ICMP file handle");
-                return JNI_FALSE;
-            }
-        } else {
-            return ping4(env, src_addr, dest_addr, timeout, hIcmpFile);
-        }
+        return ping4(env, src_addr, dest_addr, timeout);
     } else {
-        tcp_ping4(env, addrArray, timeout, ifArray, ttl);
+        wxp_ping4(env, addrArray, timeout, ifArray, ttl);
     }
 }
diff --git a/jdk/src/windows/native/java/net/Inet6AddressImpl.c b/jdk/src/windows/native/java/net/Inet6AddressImpl.c
index 0ebd061..ff24d7f 100644
--- a/jdk/src/windows/native/java/net/Inet6AddressImpl.c
+++ b/jdk/src/windows/native/java/net/Inet6AddressImpl.c
@@ -74,6 +74,13 @@
     return JNU_NewStringPlatform (env, hostname);
 }
 
+static jclass ni_iacls;
+static jclass ni_ia4cls;
+static jclass ni_ia6cls;
+static jmethodID ni_ia4ctrID;
+static jmethodID ni_ia6ctrID;
+static int initialized = 0;
+
 JNIEXPORT jobjectArray JNICALL
 Java_java_net_Inet6AddressImpl_lookupAllHostAddr(JNIEnv *env, jobject this,
                                                 jstring host) {
@@ -81,13 +88,30 @@
     jobjectArray ret = 0;
     int retLen = 0;
     jboolean preferIPv6Address;
+    static jfieldID ia_preferIPv6AddressID;
 
     int error=0;
     struct addrinfo hints, *res, *resNew = NULL;
 
-    initInetAddressIDs(env);
-    JNU_CHECK_EXCEPTION_RETURN(env, NULL);
-
+    if (!initialized) {
+      ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
+      CHECK_NULL_RETURN(ni_iacls, NULL);
+      ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
+      CHECK_NULL_RETURN(ni_iacls, NULL);
+      ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
+      CHECK_NULL_RETURN(ni_ia4cls, NULL);
+      ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
+      CHECK_NULL_RETURN(ni_ia4cls, NULL);
+      ni_ia6cls = (*env)->FindClass(env, "java/net/Inet6Address");
+      CHECK_NULL_RETURN(ni_ia6cls, NULL);
+      ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
+      CHECK_NULL_RETURN(ni_ia6cls, NULL);
+      ni_ia4ctrID = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
+      CHECK_NULL_RETURN(ni_ia4ctrID, NULL);
+      ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
+      CHECK_NULL_RETURN(ni_ia6ctrID, NULL);
+      initialized = 1;
+    }
     if (IS_NULL(host)) {
         JNU_ThrowNullPointerException(env, "host is null");
         return 0;
@@ -95,6 +119,17 @@
     hostname = JNU_GetStringPlatformChars(env, host, JNI_FALSE);
     CHECK_NULL_RETURN(hostname, NULL);
 
+    if (ia_preferIPv6AddressID == NULL) {
+        jclass c = (*env)->FindClass(env,"java/net/InetAddress");
+        if (c)  {
+            ia_preferIPv6AddressID =
+                (*env)->GetStaticFieldID(env, c, "preferIPv6Address", "Z");
+        }
+        if (ia_preferIPv6AddressID == NULL) {
+            JNU_ReleaseStringPlatformChars(env, host, hostname);
+            return NULL;
+        }
+    }
     /* get the address preference */
     preferIPv6Address
         = (*env)->GetStaticBooleanField(env, ia_class, ia_preferIPv6AddressID);
@@ -196,7 +231,7 @@
         retLen = i;
         iterator = resNew;
         i = 0;
-        ret = (*env)->NewObjectArray(env, retLen, ia_class, NULL);
+        ret = (*env)->NewObjectArray(env, retLen, ni_iacls, NULL);
 
         if (IS_NULL(ret)) {
             /* we may have memory to free at the end of this */
@@ -213,7 +248,7 @@
 
         while (iterator != NULL) {
             if (iterator->ai_family == AF_INET) {
-              jobject iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+              jobject iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4ctrID);
               if (IS_NULL(iaObj)) {
                 ret = NULL;
                 goto cleanupAndReturn;
@@ -224,7 +259,7 @@
                 inetIndex ++;
             } else if (iterator->ai_family == AF_INET6) {
               jint scope = 0, ret1;
-              jobject iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
+              jobject iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
               if (IS_NULL(iaObj)) {
                 ret = NULL;
                 goto cleanupAndReturn;
@@ -314,7 +349,6 @@
 
     if (!error) {
         ret = (*env)->NewStringUTF(env, host);
-        CHECK_NULL_RETURN(ret, NULL);
     }
 
     if (ret == NULL) {
@@ -326,109 +360,6 @@
 
 #ifdef AF_INET6
 
-/**
- * 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)
-{
-    jint fd;
-    WSAEVENT hEvent;
-    int connect_rv = -1;
-
-    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");
-        return JNI_FALSE;
-    }
-
-    /**
-     * A TTL was specified, let's set the socket option.
-     */
-    if (ttl > 0) {
-      setsockopt(fd, IPPROTO_IPV6, IPV6_UNICAST_HOPS, (const char *)&ttl, sizeof(ttl));
-    }
-
-    /**
-     * A network interface was specified, 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;
-      }
-    }
-
-    /**
-     * Make the socket non blocking.
-     */
-    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);
-
-    /**
-     * 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);
-
-        if (timeout >= 0) {
-          /* has connection been established? */
-          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;
-          }
-        }
-    }
-    WSACloseEvent(hEvent);
-    closesocket(fd);
-    return JNI_FALSE;
-}
 
 /**
  * ping implementation.
@@ -440,9 +371,9 @@
 ping6(JNIEnv *env,
       struct sockaddr_in6* src,
       struct sockaddr_in6* dest,
-      jint timeout,
-      HANDLE hIcmpFile)
+      jint timeout)
 {
+    HANDLE hIcmpFile;
     DWORD dwRetVal = 0;
     char SendData[32] = {0};
     LPVOID ReplyBuffer = NULL;
@@ -450,6 +381,12 @@
     IP_OPTION_INFORMATION ipInfo = {255, 0, 0, 0, NULL};
     struct sockaddr_in6 sa6Source;
 
+    hIcmpFile = Icmp6CreateFile();
+    if (hIcmpFile == INVALID_HANDLE_VALUE) {
+        NET_ThrowNew(env, WSAGetLastError(), "Unable to open handle");
+        return JNI_FALSE;
+    }
+
     ReplySize = sizeof(ICMPV6_ECHO_REPLY) + sizeof(SendData);
     ReplyBuffer = (VOID*) malloc(ReplySize);
     if (ReplyBuffer == NULL) {
@@ -508,7 +445,7 @@
     struct sockaddr_in6* netif = NULL;
     struct sockaddr_in6 inf6;
     int len = 0;
-    HANDLE hIcmpFile;
+    int connect_rv = -1;
 
     /*
      * If IPv6 is not enable, then we can't reach an IPv6 address, can we?
@@ -552,21 +489,7 @@
       inf6.sin6_scope_id = if_scope;
       netif = &inf6;
     }
-
-    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);
-        } else {
-            NET_ThrowNew(env, err, "Unable to create ICMP file handle");
-            return JNI_FALSE;
-        }
-    } else {
-        return ping6(env, netif, &him6, timeout, hIcmpFile);
-    }
-
+    return ping6(env, netif, &him6, timeout);
 #endif /* AF_INET6 */
     return JNI_FALSE;
 }
diff --git a/jdk/src/windows/native/java/net/NetworkInterface.c b/jdk/src/windows/native/java/net/NetworkInterface.c
index 4dc22a0..6483f12 100644
--- a/jdk/src/windows/native/java/net/NetworkInterface.c
+++ b/jdk/src/windows/native/java/net/NetworkInterface.c
@@ -65,6 +65,13 @@
 jfieldID ni_nameID;         /* NetworkInterface.name */
 jfieldID ni_displayNameID;  /* NetworkInterface.displayName */
 jfieldID ni_childsID;       /* NetworkInterface.childs */
+jclass ni_iacls;            /* InetAddress */
+
+jclass ni_ia4cls;           /* Inet4Address */
+jmethodID ni_ia4Ctor;       /* Inet4Address() */
+
+jclass ni_ia6cls;           /* Inet6Address */
+jmethodID ni_ia6ctrID;      /* Inet6Address() */
 
 jclass ni_ibcls;            /* InterfaceAddress */
 jmethodID ni_ibctrID;       /* InterfaceAddress() */
@@ -508,6 +515,26 @@
     CHECK_NULL(ni_childsID);
     ni_ctor = (*env)->GetMethodID(env, ni_class, "<init>", "()V");
     CHECK_NULL(ni_ctor);
+
+    ni_iacls = (*env)->FindClass(env, "java/net/InetAddress");
+    CHECK_NULL(ni_iacls);
+    ni_iacls = (*env)->NewGlobalRef(env, ni_iacls);
+    CHECK_NULL(ni_iacls);
+
+    ni_ia4cls = (*env)->FindClass(env, "java/net/Inet4Address");
+    CHECK_NULL(ni_ia4cls);
+    ni_ia4cls = (*env)->NewGlobalRef(env, ni_ia4cls);
+    CHECK_NULL(ni_ia4cls);
+    ni_ia4Ctor = (*env)->GetMethodID(env, ni_ia4cls, "<init>", "()V");
+    CHECK_NULL(ni_ia4Ctor);
+
+    ni_ia6cls = (*env)->FindClass(env, "java/net/Inet6Address");
+    CHECK_NULL(ni_ia6cls);
+    ni_ia6cls = (*env)->NewGlobalRef(env, ni_ia6cls);
+    CHECK_NULL(ni_ia6cls);
+    ni_ia6ctrID = (*env)->GetMethodID(env, ni_ia6cls, "<init>", "()V");
+    CHECK_NULL(ni_ia6ctrID);
+
     ni_ibcls = (*env)->FindClass(env, "java/net/InterfaceAddress");
     CHECK_NULL(ni_ibcls);
     ni_ibcls = (*env)->NewGlobalRef(env, ni_ibcls);
@@ -519,9 +546,6 @@
     ni_ibbroadcastID = (*env)->GetFieldID(env, ni_ibcls, "broadcast", "Ljava/net/Inet4Address;");
     CHECK_NULL(ni_ibbroadcastID);
     ni_ibmaskID = (*env)->GetFieldID(env, ni_ibcls, "maskLength", "S");
-    CHECK_NULL(ni_ibmaskID);
-
-    initInetAddressIDs(env);
 }
 
 /*
@@ -567,7 +591,7 @@
             return NULL;
         }
     }
-    addrArr = (*env)->NewObjectArray(env, netaddrCount, ia_class, NULL);
+    addrArr = (*env)->NewObjectArray(env, netaddrCount, ni_iacls, NULL);
     if (addrArr == NULL) {
         free_netaddr(netaddrP);
         return NULL;
@@ -585,7 +609,7 @@
         jobject iaObj, ia2Obj;
         jobject ibObj = NULL;
         if (addrs->addr.him.sa_family == AF_INET) {
-            iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+            iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4Ctor);
             if (iaObj == NULL) {
                 free_netaddr(netaddrP);
                 return NULL;
@@ -600,7 +624,7 @@
                 return NULL;
               }
               (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
-              ia2Obj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+              ia2Obj = (*env)->NewObject(env, ni_ia4cls, ni_ia4Ctor);
               if (ia2Obj == NULL) {
                 free_netaddr(netaddrP);
                 return NULL;
@@ -612,7 +636,7 @@
             }
         } else /* AF_INET6 */ {
             int scope;
-            iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
+            iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
             if (iaObj) {
                 int ret = setInet6Address_ipaddress(env, iaObj,  (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
                 if (ret == JNI_FALSE) {
diff --git a/jdk/src/windows/native/java/net/NetworkInterface.h b/jdk/src/windows/native/java/net/NetworkInterface.h
index 3bf4ed0..fc40906 100644
--- a/jdk/src/windows/native/java/net/NetworkInterface.h
+++ b/jdk/src/windows/native/java/net/NetworkInterface.h
@@ -70,6 +70,16 @@
 extern jfieldID ni_displayNameID;   /* NetworkInterface.displayName */
 extern jfieldID ni_childsID;        /* NetworkInterface.childs */
 
+extern jclass ni_iacls;             /* InetAddress */
+
+extern jclass ni_ia4cls;            /* Inet4Address */
+extern jmethodID ni_ia4Ctor;        /* Inet4Address() */
+
+extern jclass ni_ia6cls;            /* Inet6Address */
+extern jmethodID ni_ia6ctrID;       /* Inet6Address() */
+extern jfieldID ni_ia6ipaddressID;
+extern jfieldID ni_ia6ipaddressID;
+
 extern jclass ni_ibcls;             /* InterfaceAddress */
 extern jmethodID ni_ibctrID;        /* InterfaceAddress() */
 extern jfieldID ni_ibaddressID;     /* InterfaceAddress.address */
diff --git a/jdk/src/windows/native/java/net/NetworkInterface_winXP.c b/jdk/src/windows/native/java/net/NetworkInterface_winXP.c
index 8003abc..4042d16 100644
--- a/jdk/src/windows/native/java/net/NetworkInterface_winXP.c
+++ b/jdk/src/windows/native/java/net/NetworkInterface_winXP.c
@@ -489,20 +489,14 @@
      * Create a NetworkInterface object and populate it
      */
     netifObj = (*env)->NewObject(env, ni_class, ni_ctor);
-    if (netifObj == NULL) {
-        return NULL;
-    }
     name = (*env)->NewStringUTF(env, ifs->name);
-    if (name == NULL) {
-        return NULL;
-    }
     if (ifs->dNameIsUnicode) {
         displayName = (*env)->NewString(env, (PWCHAR)ifs->displayName,
                                         (jsize)wcslen ((PWCHAR)ifs->displayName));
     } else {
         displayName = (*env)->NewStringUTF(env, ifs->displayName);
     }
-    if (displayName == NULL) {
+    if (netifObj == NULL || name == NULL || displayName == NULL) {
         return NULL;
     }
     (*env)->SetObjectField(env, netifObj, ni_nameID, name);
@@ -519,7 +513,7 @@
         }
     }
 
-    addrArr = (*env)->NewObjectArray(env, netaddrCount, ia_class, NULL);
+    addrArr = (*env)->NewObjectArray(env, netaddrCount, ni_iacls, NULL);
     if (addrArr == NULL) {
         return NULL;
     }
@@ -537,7 +531,7 @@
         jobject iaObj, ia2Obj;
         jobject ibObj = NULL;
         if (addrs->addr.him.sa_family == AF_INET) {
-            iaObj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+            iaObj = (*env)->NewObject(env, ni_ia4cls, ni_ia4Ctor);
             if (iaObj == NULL) {
                 return NULL;
             }
@@ -551,7 +545,7 @@
               return NULL;
             }
             (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
-            ia2Obj = (*env)->NewObject(env, ia4_class, ia4_ctrID);
+            ia2Obj = (*env)->NewObject(env, ni_ia4cls, ni_ia4Ctor);
             if (ia2Obj == NULL) {
               free_netaddr(netaddrP);
               return NULL;
@@ -562,28 +556,26 @@
             (*env)->SetObjectArrayElement(env, bindsArr, bind_index++, ibObj);
         } else /* AF_INET6 */ {
             int scope;
-            int ret;
-            iaObj = (*env)->NewObject(env, ia6_class, ia6_ctrID);
-            if (iaObj == NULL) {
-                return NULL;
+            iaObj = (*env)->NewObject(env, ni_ia6cls, ni_ia6ctrID);
+            if (iaObj) {
+                int ret = setInet6Address_ipaddress(env, iaObj, (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
+                if (ret == JNI_FALSE) {
+                    return NULL;
+                }
+                scope = addrs->addr.him6.sin6_scope_id;
+                if (scope != 0) { /* zero is default value, no need to set */
+                    setInet6Address_scopeid(env, iaObj, scope);
+                    setInet6Address_scopeifname(env, iaObj, netifObj);
+                }
+                ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
+                if (ibObj == NULL) {
+                  free_netaddr(netaddrP);
+                  return NULL;
+                }
+                (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
+                (*env)->SetShortField(env, ibObj, ni_ibmaskID, addrs->mask);
+                (*env)->SetObjectArrayElement(env, bindsArr, bind_index++, ibObj);
             }
-            ret = setInet6Address_ipaddress(env, iaObj, (jbyte *)&(addrs->addr.him6.sin6_addr.s6_addr));
-            if (ret == JNI_FALSE) {
-                return NULL;
-            }
-            scope = addrs->addr.him6.sin6_scope_id;
-            if (scope != 0) { /* zero is default value, no need to set */
-                setInet6Address_scopeid(env, iaObj, scope);
-                setInet6Address_scopeifname(env, iaObj, netifObj);
-            }
-            ibObj = (*env)->NewObject(env, ni_ibcls, ni_ibctrID);
-            if (ibObj == NULL) {
-              free_netaddr(netaddrP);
-              return NULL;
-            }
-            (*env)->SetObjectField(env, ibObj, ni_ibaddressID, iaObj);
-            (*env)->SetShortField(env, ibObj, ni_ibmaskID, addrs->mask);
-            (*env)->SetObjectArrayElement(env, bindsArr, bind_index++, ibObj);
         }
         (*env)->SetObjectArrayElement(env, addrArr, addr_index, iaObj);
         addrs = addrs->next;
diff --git a/jdk/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c b/jdk/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c
index 356f486..3b1994d 100644
--- a/jdk/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c
+++ b/jdk/src/windows/native/java/net/TwoStacksPlainDatagramSocketImpl.c
@@ -838,7 +838,6 @@
     }
     if (IS_NULL(addressObj)) {
         JNU_ThrowNullPointerException(env, "Null address in peek()");
-        return -1;
     } else {
         address = getInetAddress_addr(env, addressObj);
         /* We only handle IPv4 for now. Will support IPv6 once its in the os */
@@ -1151,23 +1150,11 @@
     }
     if (n == -1) {
         JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException", "socket closed");
-        if (packetBufferLen > MAX_BUFFER_LEN) {
-            free(fullPacket);
-        }
-        return -1;
     } else if (n == -2) {
         JNU_ThrowByName(env, JNU_JAVAIOPKG "InterruptedIOException",
                         "operation interrupted");
-        if (packetBufferLen > MAX_BUFFER_LEN) {
-            free(fullPacket);
-        }
-        return -1;
     } else if (n < 0) {
         NET_ThrowCurrent(env, "Datagram receive failed");
-        if (packetBufferLen > MAX_BUFFER_LEN) {
-            free(fullPacket);
-        }
-        return -1;
     } else {
         jobject packetAddress;
 
@@ -1927,7 +1914,7 @@
         default :
             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
                 "Socket option not supported by PlainDatagramSocketImp");
-            return;
+            break;
 
     }
 
@@ -2370,7 +2357,6 @@
       if (NET_SetSockOpt(fd, IPPROTO_IP, IP_MULTICAST_TTL, (char*)&ittl,
                          sizeof (ittl)) < 0) {
         NET_ThrowCurrent(env, "set IP_MULTICAST_TTL failed");
-        return;
       }
     }
 
@@ -2564,9 +2550,6 @@
         } else {
             ifindex = getIndexFromIf (env, niObj);
             if (ifindex == -1) {
-                if ((*env)->ExceptionOccurred(env)) {
-                    return;
-                }
                 NET_ThrowCurrent(env, "get ifindex failed");
                 return;
             }
diff --git a/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c b/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c
index 6e7ea71..899d5de 100644
--- a/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c
+++ b/jdk/src/windows/native/java/net/TwoStacksPlainSocketImpl.c
@@ -109,7 +109,7 @@
     psi_portID = (*env)->GetFieldID(env, cls, "port", "I");
     CHECK_NULL(psi_portID);
     psi_lastfdID = (*env)->GetFieldID(env, cls, "lastfd", "I");
-    CHECK_NULL(psi_lastfdID);
+    CHECK_NULL(psi_portID);
     psi_localportID = (*env)->GetFieldID(env, cls, "localport", "I");
     CHECK_NULL(psi_localportID);
     psi_timeoutID = (*env)->GetFieldID(env, cls, "timeout", "I");
@@ -154,17 +154,17 @@
         fd1Obj = (*env)->GetObjectField(env, this, psi_fd1ID);
 
         if (IS_NULL(fd1Obj)) {
-            (*env)->SetIntField(env, fdObj, IO_fd_fdID, -1);
-            NET_SocketClose(fd);
             JNU_ThrowByName(env, JNU_JAVANETPKG "SocketException",
                             "null fd1 object");
+            (*env)->SetIntField(env, fdObj, IO_fd_fdID, -1);
+            NET_SocketClose(fd);
             return;
         }
         fd1 = socket(AF_INET6, (stream ? SOCK_STREAM: SOCK_DGRAM), 0);
         if (fd1 == -1) {
+            NET_ThrowCurrent(env, "create");
             (*env)->SetIntField(env, fdObj, IO_fd_fdID, -1);
             NET_SocketClose(fd);
-            NET_ThrowCurrent(env, "create");
             return;
         } else {
             /* Set socket attribute so it is not passed to any child process */
@@ -911,7 +911,6 @@
                     isRcvTimeoutSupported = JNI_FALSE;
                 } else {
                     NET_ThrowCurrent(env, "setsockopt SO_RCVTIMEO");
-                    return;
                 }
             }
             if (fd1 != -1) {
diff --git a/jdk/src/windows/native/java/nio/MappedByteBuffer.c b/jdk/src/windows/native/java/nio/MappedByteBuffer.c
index 05f5680..4880123 100644
--- a/jdk/src/windows/native/java/nio/MappedByteBuffer.c
+++ b/jdk/src/windows/native/java/nio/MappedByteBuffer.c
@@ -83,9 +83,9 @@
         HANDLE h;
         if (handle_fdID == NULL) {
             jclass clazz = (*env)->FindClass(env, "java/io/FileDescriptor");
-            CHECK_NULL(clazz); //exception thrown
+            if (clazz == NULL)
+                return; // exception thrown
             handle_fdID = (*env)->GetFieldID(env, clazz, "handle", "J");
-            CHECK_NULL(handle_fdID);
         }
         h = jlong_to_ptr((*env)->GetLongField(env, fdo, handle_fdID));
         result = FlushFileBuffers(h);
diff --git a/jdk/src/windows/native/sun/bridge/WinAccessBridge.cpp b/jdk/src/windows/native/sun/bridge/WinAccessBridge.cpp
index 20b5d7c..ed42631 100644
--- a/jdk/src/windows/native/sun/bridge/WinAccessBridge.cpp
+++ b/jdk/src/windows/native/sun/bridge/WinAccessBridge.cpp
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 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
@@ -1125,7 +1125,7 @@
 
     PrintDebugString("WinAccessBridge::getAccessibleContextWithFocus(%p, %X, )", window, vmID);
     // find vmID, etc. from HWND; ask that VM for the AC w/Focus
-    HWND pkgVMID;
+        HWND pkgVMID = (HWND)ABLongToHandle( pkg->rVMID ) ;
     if (getAccessibleContextFromHWND(window, (long *)&(pkgVMID), &(pkg->rAccessibleContext)) == TRUE) {
         HWND destABWindow = javaVMs->findAccessBridgeWindow((long)pkgVMID);     // ineffecient [[[FIXME]]]
         if (sendMemoryPackage(buffer, sizeof(buffer), destABWindow) == TRUE) {
diff --git a/jdk/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.cpp b/jdk/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.cpp
index 3e706c4..1b5b71f 100644
--- a/jdk/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.cpp
+++ b/jdk/src/windows/native/sun/java2d/windows/GDIWindowSurfaceData.cpp
@@ -128,7 +128,7 @@
                 return;
             }
             hDC = comp->GetDCFromComponent();
-            if (hDC != NULL && wsdo->device != NULL) {
+            if (hDC != NULL) {
                 ::SelectObject(hDC, nullbrush);
                 ::SelectObject(hDC, nullpen);
                 ::SelectClipRgn(hDC, (HRGN) NULL);
diff --git a/jdk/src/windows/native/sun/nio/ch/IOUtil.c b/jdk/src/windows/native/sun/nio/ch/IOUtil.c
index 49de1eb..370dcf5 100644
--- a/jdk/src/windows/native/sun/nio/ch/IOUtil.c
+++ b/jdk/src/windows/native/sun/nio/ch/IOUtil.c
@@ -33,7 +33,6 @@
 
 #include "nio.h"
 #include "nio_util.h"
-#include "net_util.h"
 #include "sun_nio_ch_IOUtil.h"
 
 /* field id for jlong 'handle' in java.io.FileDescriptor used for file fds */
@@ -56,7 +55,6 @@
     CHECK_NULL(clazz = (*env)->FindClass(env, "java/io/FileDescriptor"));
     CHECK_NULL(fd_fdID = (*env)->GetFieldID(env, clazz, "fd", "I"));
     CHECK_NULL(handle_fdID = (*env)->GetFieldID(env, clazz, "handle", "J"));
-    initInetAddressIDs(env);
 }
 
 /**************************************************************
diff --git a/jdk/src/windows/native/sun/security/mscapi/security.cpp b/jdk/src/windows/native/sun/security/mscapi/security.cpp
index 5796c30..553dd42 100644
--- a/jdk/src/windows/native/sun/security/mscapi/security.cpp
+++ b/jdk/src/windows/native/sun/security/mscapi/security.cpp
@@ -352,50 +352,38 @@
             BOOL bHasNoPrivateKey = FALSE;
             DWORD dwPublicKeyLength = 0;
 
-            // First, probe it silently
-            if (::CryptAcquireCertificatePrivateKey(pCertContext, CRYPT_ACQUIRE_SILENT_FLAG, NULL,
-                    &hCryptProv, &dwKeySpec, &bCallerFreeProv) == FALSE
-                && GetLastError() != NTE_SILENT_CONTEXT)
+            if (::CryptAcquireCertificatePrivateKey(pCertContext, NULL, NULL,
+                                                    &hCryptProv, &dwKeySpec, &bCallerFreeProv) == FALSE)
             {
                 bHasNoPrivateKey = TRUE;
-            }
-            else
-            {
-                if (bCallerFreeProv == TRUE) {
-                    ::CryptReleaseContext(hCryptProv, NULL);
-                    bCallerFreeProv = FALSE;
-                }
 
-                // Second, acquire the key normally (not silently)
-                if (::CryptAcquireCertificatePrivateKey(pCertContext, 0, NULL,
-                        &hCryptProv, &dwKeySpec, &bCallerFreeProv) == FALSE)
+            } else {
+                // Private key is available
+
+                BOOL bGetUserKey = ::CryptGetUserKey(hCryptProv, dwKeySpec, &hUserKey);
+
+                // Skip certificate if cannot find private key
+                if (bGetUserKey == FALSE)
                 {
-                    bHasNoPrivateKey = TRUE;
+                    if (bCallerFreeProv)
+                        ::CryptReleaseContext(hCryptProv, NULL);
+
+                    continue;
                 }
-                else
-                {
-                    // Private key is available
-                    BOOL bGetUserKey = ::CryptGetUserKey(hCryptProv, dwKeySpec, &hUserKey);
 
-                    // Skip certificate if cannot find private key
-                    if (bGetUserKey == FALSE) {
-                        if (bCallerFreeProv)
-                            ::CryptReleaseContext(hCryptProv, NULL);
-                        continue;
-                    }
+                // Set cipher mode to ECB
+                DWORD dwCipherMode = CRYPT_MODE_ECB;
+                ::CryptSetKeyParam(hUserKey, KP_MODE, (BYTE*)&dwCipherMode, NULL);
 
-                    // Set cipher mode to ECB
-                    DWORD dwCipherMode = CRYPT_MODE_ECB;
-                    ::CryptSetKeyParam(hUserKey, KP_MODE, (BYTE*)&dwCipherMode, NULL);
 
-                    // If the private key is present in smart card, we may not be able to
-                    // determine the key length by using the private key handle. However,
-                    // since public/private key pairs must have the same length, we could
-                    // determine the key length of the private key by using the public key
-                    // in the certificate.
-                    dwPublicKeyLength = ::CertGetPublicKeyLength(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
-                            &(pCertContext->pCertInfo->SubjectPublicKeyInfo));
-                }
+                // If the private key is present in smart card, we may not be able to
+                // determine the key length by using the private key handle. However,
+                // since public/private key pairs must have the same length, we could
+                // determine the key length of the private key by using the public key
+                // in the certificate.
+                dwPublicKeyLength = ::CertGetPublicKeyLength(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING,
+                        &(pCertContext->pCertInfo->SubjectPublicKeyInfo));
+
             }
             PCCERT_CHAIN_CONTEXT pCertChainContext = NULL;
 
@@ -404,7 +392,8 @@
             //
             if (GetCertificateChain(OID_EKU_ANY, pCertContext, &pCertChainContext))
             {
-                for (DWORD i = 0; i < pCertChainContext->cChain; i++)
+
+                for (unsigned int i=0; i < pCertChainContext->cChain; i++)
                 {
                     // Found cert chain
                     PCERT_SIMPLE_CHAIN rgpChain =
@@ -454,7 +443,6 @@
                         // cert collection
                         env->CallVoidMethod(obj, mGenCert, byteArray, jArrayList);
                     }
-
                     if (bHasNoPrivateKey)
                     {
                         // Generate certificate chain and store into cert chain
@@ -1373,57 +1361,43 @@
     HCRYPTPROV hCryptProv = NULL;
     HCRYPTKEY hKey = NULL;
     DWORD dwKeySpec;
-    BOOL bCallerFreeProv = FALSE;
-    BOOL bRes;
 
     __try
     {
         if (usePrivateKey == JNI_TRUE) {
             // Locate the key container for the certificate's private key
+            if (!(::CryptAcquireCertificatePrivateKey(
+                (PCCERT_CONTEXT) pCertContext, 0, NULL, &hCryptProv,
+                &dwKeySpec, NULL))) {
 
-            // First, probe it silently
-            bRes = ::CryptAcquireCertificatePrivateKey(
-                    (PCCERT_CONTEXT) pCertContext, CRYPT_ACQUIRE_SILENT_FLAG,
-                    NULL, &hCryptProv, &dwKeySpec, &bCallerFreeProv);
-
-            if (bRes == FALSE && GetLastError() != NTE_SILENT_CONTEXT)
-            {
-                ThrowException(env, KEYSTORE_EXCEPTION, GetLastError());
-                __leave;
-            }
-
-            if (bCallerFreeProv == TRUE) {
-                ::CryptReleaseContext(hCryptProv, NULL);
-                bCallerFreeProv = FALSE;
-            }
-
-            // Now, do it normally (not silently)
-            if (::CryptAcquireCertificatePrivateKey(
-                    (PCCERT_CONTEXT) pCertContext, 0, NULL, &hCryptProv,
-                    &dwKeySpec, &bCallerFreeProv) == FALSE)
-            {
                 ThrowException(env, KEYSTORE_EXCEPTION, GetLastError());
                 __leave;
             }
 
             // Get a handle to the private key
-            if (::CryptGetUserKey(hCryptProv, dwKeySpec, &hKey) == FALSE) {
+            if (!(::CryptGetUserKey(hCryptProv, dwKeySpec, &hKey))) {
                 ThrowException(env, KEY_EXCEPTION, GetLastError());
                 __leave;
             }
-        }
-        else // use public key
-        {
-            bCallerFreeProv = TRUE;
+
+        } else { // use public key
 
             //  Acquire a CSP context.
-            if (::CryptAcquireContext(&hCryptProv, "J2SE", NULL,
-                    PROV_RSA_FULL, 0) == FALSE)
+            if(::CryptAcquireContext(
+               &hCryptProv,
+               "J2SE",
+               NULL,
+               PROV_RSA_FULL,
+               0) == FALSE)
             {
                 // If CSP context hasn't been created, create one.
                 //
-                if (::CryptAcquireContext(&hCryptProv, "J2SE", NULL,
-                        PROV_RSA_FULL, CRYPT_NEWKEYSET) == FALSE)
+                if (::CryptAcquireContext(
+                    &hCryptProv,
+                    "J2SE",
+                    NULL,
+                    PROV_RSA_FULL,
+                    CRYPT_NEWKEYSET) == FALSE)
                 {
                     ThrowException(env, KEYSTORE_EXCEPTION, GetLastError());
                     __leave;
@@ -1431,10 +1405,10 @@
             }
 
             // Import the certificate's public key into the key container
-            if (::CryptImportPublicKeyInfo(hCryptProv, X509_ASN_ENCODING,
-                    &(((PCCERT_CONTEXT) pCertContext)->pCertInfo->SubjectPublicKeyInfo),
-                    &hKey) == FALSE)
-            {
+            if (!(::CryptImportPublicKeyInfo(hCryptProv, X509_ASN_ENCODING,
+                &(((PCCERT_CONTEXT) pCertContext)->pCertInfo->SubjectPublicKeyInfo),
+                &hKey))) {
+
                 ThrowException(env, KEY_EXCEPTION, GetLastError());
                 __leave;
             }
@@ -1445,7 +1419,7 @@
         //--------------------------------------------------------------------
         // Clean up.
 
-        if (bCallerFreeProv == TRUE && hCryptProv != NULL)
+        if (hCryptProv)
             ::CryptReleaseContext(hCryptProv, 0);
     }
 
diff --git a/jdk/src/windows/native/sun/windows/awt_Component.cpp b/jdk/src/windows/native/sun/windows/awt_Component.cpp
index 405098b..0128972 100644
--- a/jdk/src/windows/native/sun/windows/awt_Component.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_Component.cpp
@@ -256,8 +256,6 @@
         AwtComponent::BuildPrimaryDynamicTable();
         sm_PrimaryDynamicTableBuilt = TRUE;
     }
-
-    deadKeyActive = FALSE;
 }
 
 AwtComponent::~AwtComponent()
@@ -2938,7 +2936,6 @@
     {0x037A, java_awt_event_KeyEvent_VK_DEAD_IOTA},             // ASCII ???
     {0x309B, java_awt_event_KeyEvent_VK_DEAD_VOICED_SOUND},
     {0x309C, java_awt_event_KeyEvent_VK_DEAD_SEMIVOICED_SOUND},
-    {0x0004, java_awt_event_KeyEvent_VK_COMPOSE},
     {0,0}
 };
 
@@ -3431,9 +3428,8 @@
     AwtToolkit::GetKeyboardState(keyboardState);
 
     // apply modifiers to keyboard state if necessary
-    BOOL shiftIsDown = FALSE;
     if (modifiers) {
-        shiftIsDown = modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK;
+        BOOL shiftIsDown = modifiers & java_awt_event_InputEvent_SHIFT_DOWN_MASK;
         BOOL altIsDown = modifiers & java_awt_event_InputEvent_ALT_DOWN_MASK;
         BOOL ctrlIsDown = modifiers & java_awt_event_InputEvent_CTRL_DOWN_MASK;
 
@@ -3505,27 +3501,18 @@
         } // ctrlIsDown
     } // modifiers
 
+    // instead of creating our own conversion tables, I'll let Win32
+    // convert the character for me.
     WORD wChar[2];
-    int converted = 1;
-    UINT ch = ::MapVirtualKey(wkey, 2);
-    if (ch & 0x80000000) {
-        // Dead key which is handled as a normal key
-        isDeadKey = deadKeyActive = TRUE;
-    } else if (deadKeyActive) {
-        // We cannot use ::ToUnicodeEx if dead key is active because this will
-        // break dead key function
-        wChar[0] = shiftIsDown ? ch : tolower(ch);
-    } else {
-        UINT scancode = ::MapVirtualKey(wkey, 0);
-        converted = ::ToUnicodeEx(wkey, scancode, keyboardState,
-                                              wChar, 2, 0, GetKeyboardLayout());
-    }
+    UINT scancode = ::MapVirtualKey(wkey, 0);
+    int converted = ::ToUnicodeEx(wkey, scancode, keyboardState,
+                                  wChar, 2, 0, GetKeyboardLayout());
 
     UINT translation;
     BOOL deadKeyFlag = (converted == 2);
 
     // Dead Key
-    if (converted < 0 || isDeadKey) {
+    if (converted < 0) {
         translation = java_awt_event_KeyEvent_CHAR_UNDEFINED;
     } else
     // No translation available -- try known conversions or else punt.
@@ -3679,8 +3666,6 @@
 MsgRouting AwtComponent::WmChar(UINT character, UINT repCnt, UINT flags,
                                 BOOL system)
 {
-    deadKeyActive = FALSE;
-
     // Will only get WmChar messages with DBCS if we create them for
     // an Edit class in the WmForwardChar method. These synthesized
     // DBCS chars are ok to pass on directly to the default window
diff --git a/jdk/src/windows/native/sun/windows/awt_Component.h b/jdk/src/windows/native/sun/windows/awt_Component.h
index 780d810..b914ef1 100644
--- a/jdk/src/windows/native/sun/windows/awt_Component.h
+++ b/jdk/src/windows/native/sun/windows/awt_Component.h
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 1996, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 1996, 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
@@ -820,8 +820,6 @@
     // 6524352: support finer-resolution
     int m_wheelRotationAmount;
 
-    BOOL deadKeyActive;
-
     /*
      * The association list of children's IDs and corresponding components.
      * Some components like Choice or List are required their sizes while
diff --git a/jdk/src/windows/native/sun/windows/awt_Font.cpp b/jdk/src/windows/native/sun/windows/awt_Font.cpp
index abdffdc..7282a8f 100644
--- a/jdk/src/windows/native/sun/windows/awt_Font.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_Font.cpp
@@ -1651,8 +1651,6 @@
 
 CSegTableManager g_segTableManager;
 
-#define KEYLEN 16
-
 class CCombinedSegTable : public CSegTableComponent
 {
 public:
@@ -1663,7 +1661,7 @@
 private:
     LPSTR GetCodePageSubkey();
     void GetEUDCFileName(LPWSTR lpszFileName, int cchFileName);
-    static char m_szCodePageSubkey[KEYLEN];
+    static char m_szCodePageSubkey[16];
     static WCHAR m_szDefaultEUDCFile[_MAX_PATH];
     static BOOL m_fEUDCSubKeyExist;
     static BOOL m_fTTEUDCFileExist;
@@ -1671,7 +1669,7 @@
     CEUDCSegTable* m_pEUDCSegTable;
 };
 
-char CCombinedSegTable::m_szCodePageSubkey[KEYLEN] = "";
+char CCombinedSegTable::m_szCodePageSubkey[16] = "";
 
 WCHAR CCombinedSegTable::m_szDefaultEUDCFile[_MAX_PATH] = L"";
 
@@ -1703,11 +1701,8 @@
     }
     lpszCP++; // cf lpszCP = "932"
 
-    char szSubKey[KEYLEN];
+    char szSubKey[80];
     strcpy(szSubKey, "EUDC\\");
-    if ((strlen(szSubKey) + strlen(lpszCP)) >= KEYLEN) {
-        return NULL;
-    }
     strcpy(&(szSubKey[strlen(szSubKey)]), lpszCP);
     strcpy(m_szCodePageSubkey, szSubKey);
     return m_szCodePageSubkey;
diff --git a/jdk/src/windows/native/sun/windows/awt_TrayIcon.cpp b/jdk/src/windows/native/sun/windows/awt_TrayIcon.cpp
index fbf46ec..e9c74d7 100644
--- a/jdk/src/windows/native/sun/windows/awt_TrayIcon.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_TrayIcon.cpp
@@ -93,12 +93,6 @@
 
 void AwtTrayIcon::Dispose() {
     SendTrayMessage(NIM_DELETE);
-
-    // Destroy the icon to avoid leak of GDI objects
-    if (m_nid.hIcon != NULL) {
-        ::DestroyIcon(m_nid.hIcon);
-    }
-
     UnlinkObjects();
 
     if (--sm_instCount == 0) {
diff --git a/jdk/src/windows/native/sun/windows/awt_Win32GraphicsDevice.cpp b/jdk/src/windows/native/sun/windows/awt_Win32GraphicsDevice.cpp
index b7ab7e0..825a69c 100644
--- a/jdk/src/windows/native/sun/windows/awt_Win32GraphicsDevice.cpp
+++ b/jdk/src/windows/native/sun/windows/awt_Win32GraphicsDevice.cpp
@@ -875,9 +875,6 @@
     // Only want to call this once per session
     make_uns_ordered_dither_array(img_oda_alpha, 256);
 
-    // workaround JDK-6477756, ignore return value to keep dll in memory
-    JDK_LoadSystemLibrary("opengl32.dll");
-
     CATCH_BAD_ALLOC;
 }
 
diff --git a/jdk/test/ProblemList.txt b/jdk/test/ProblemList.txt
index 9c5c29b..825c985 100644
--- a/jdk/test/ProblemList.txt
+++ b/jdk/test/ProblemList.txt
@@ -237,9 +237,6 @@
 # 8026393
 sun/security/tools/jarsigner/warnings/BadKeyUsageTest.java      generic-all
 
-# 8158827
-sun/security/krb5/auto/tools/KinitConfPlusProps.java                       windows-all
-
 ############################################################################
 
 # jdk_sound
@@ -289,10 +286,3 @@
 sun/tools/jps/TestJpsJarRelative.java				generic-all
 
 ############################################################################
-
-# jdk_other
-
-############################################################################
-
-# 8141370
-com/sun/jndi/ldap/DeadSSLLdapTimeoutTest.java			linux-i586,macosx-all
diff --git a/jdk/test/TEST.groups b/jdk/test/TEST.groups
index 3274d85..886566f 100644
--- a/jdk/test/TEST.groups
+++ b/jdk/test/TEST.groups
@@ -394,7 +394,6 @@
   javax/management/mxbean/LeakTest.java \
   javax/management/mxbean/MXBeanTest.java \
   javax/management/mxbean/PropertyNamesTest.java \
-  javax/xml/bind/marshal/8134111/UnmarshalTest.java \
   javax/xml/ws/8043129 \
   jdk/lambda/vm/InterfaceAccessFlagsTest.java \
   sun/misc/URLClassPath/ClassnameCharTest.java \
@@ -567,7 +566,6 @@
   java/net/HttpCookie/IllegalCookieNameTest.java \
   java/net/HttpURLConnection/UnmodifiableMaps.java \
   java/net/ResponseCache/Test.java \
-  java/net/SetFactoryPermission/SetFactoryPermission.java \
   java/net/URLClassLoader/ClassLoad.java \
   java/net/URLClassLoader/closetest/CloseTest.java \
   java/net/URLPermission/URLTest.java \
diff --git a/jdk/test/com/sun/corba/cachedSocket/7056731.sh b/jdk/test/com/sun/corba/cachedSocket/7056731.sh
index 2e5e3fb..0d7c036 100644
--- a/jdk/test/com/sun/corba/cachedSocket/7056731.sh
+++ b/jdk/test/com/sun/corba/cachedSocket/7056731.sh
@@ -102,7 +102,7 @@
 sleep 5 # give time for Client to throw exception
 
 # JVM_PROC should have exited but just in case, include it.
-kill -9 $ORB_PROC $JVM_PROC $SERVER_PROC
+kill -9 $ORB_PROC $JVM_PROC
 
 grep "ORBUtilSystemException.writeErrorSend" client.$$
 result=$?
diff --git a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCopySafe.java b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCopySafe.java
index 697da67..20dff83 100644
--- a/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCopySafe.java
+++ b/jdk/test/com/sun/crypto/provider/Cipher/AES/TestCopySafe.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8026943 8027575
+ * @bug 8026943
  * @summary Verify that same buffer can be used as input and output when
  * using Cipher objects.
  * @author Valerie Peng
@@ -44,7 +44,7 @@
     private static SecretKey KEY = new SecretKeySpec(new byte[16], "AES");
     private static byte[] IV = new byte[16];
 
-    private static int[] OFFSETS = { 1, 8, 9, 16, 17, 32, 33 };
+    private static int[] OFFSETS = { 1, 8, 17 };
 
     private static final String[] MODES = {
         "ECB", "CBC", "PCBC", "CTR", "CTS",
diff --git a/jdk/test/com/sun/jndi/ldap/LdapTimeoutTest.java b/jdk/test/com/sun/jndi/ldap/LdapTimeoutTest.java
index aa071ef..9a55800 100644
--- a/jdk/test/com/sun/jndi/ldap/LdapTimeoutTest.java
+++ b/jdk/test/com/sun/jndi/ldap/LdapTimeoutTest.java
@@ -46,7 +46,6 @@
 import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.TimeoutException;
 import java.util.concurrent.TimeUnit;
-import javax.net.ssl.SSLHandshakeException;
 
 import static java.util.concurrent.TimeUnit.MILLISECONDS;
 import static java.util.concurrent.TimeUnit.NANOSECONDS;
@@ -84,10 +83,6 @@
         throw new RuntimeException("Test failed");
     }
 
-    public void fail(Exception e) {
-        throw new RuntimeException("Test failed", e);
-    }
-
     boolean shutItDown(InitialContext ctx) {
         try {
             if (ctx != null) ctx.close();
@@ -224,6 +219,23 @@
     }
 }
 
+class DeadServerTimeoutSSLTest extends DeadServerTest {
+
+    public DeadServerTimeoutSSLTest(Hashtable env) throws IOException {
+        super(env);
+    }
+
+    public void handleNamingException(NamingException e, long start, long end) {
+        if (e.getCause() instanceof SocketTimeoutException) {
+            // SSL connect will timeout via readReply using
+            // SocketTimeoutException
+            pass();
+        } else {
+            fail();
+        }
+    }
+}
+
 
 class ReadServerNoTimeoutTest extends ReadServerTest {
 
@@ -256,8 +268,7 @@
     }
 
     public void handleNamingException(NamingException e, long start, long end) {
-        System.out.println("ReadServerTimeoutTest: end-start=" + NANOSECONDS.toMillis(end - start));
-        if (NANOSECONDS.toMillis(end - start) < 2_500) {
+        if (NANOSECONDS.toMillis(end - start) < 2_900) {
             fail();
         } else {
             pass();
@@ -395,14 +406,11 @@
 
             // run the ReadServerTest with connect / read timeouts set
             // this should exit after the connect timeout expires
-            //
-            // NOTE: commenting this test out as it is failing intermittently.
-            //
-            // System.out.println("Running read timeout test with 10ms connect timeout, 3000ms read timeout");
-            // Hashtable env4 = createEnv();
-            // env4.put("com.sun.jndi.ldap.connect.timeout", "10");
-            // env4.put("com.sun.jndi.ldap.read.timeout", "3000");
-            // results.add(testPool.submit(new ReadServerTimeoutTest(env4)));
+            System.out.println("Running read timeout test with 10ms connect timeout, 3000ms read timeout");
+            Hashtable env4 = createEnv();
+            env4.put("com.sun.jndi.ldap.connect.timeout", "10");
+            env4.put("com.sun.jndi.ldap.read.timeout", "3000");
+            results.add(testPool.submit(new ReadServerTimeoutTest(env4)));
 
             // run the DeadServerTest with connect timeout set
             // this should exit after the connect timeout expires
@@ -430,6 +438,21 @@
                 }
             }
 
+            //
+            // Running this test serially as it seems to tickle a problem
+            // on older kernels
+            //
+            // run the DeadServerTest with connect / read timeouts set
+            // and ssl enabled
+            // this should exit with a SocketTimeoutException as the root cause
+            // it should also use the connect timeout instead of the read timeout
+            System.out.println("Running connect timeout test with 10ms connect timeout, 3000ms read timeout & SSL");
+            Hashtable sslenv = createEnv();
+            sslenv.put("com.sun.jndi.ldap.connect.timeout", "10");
+            sslenv.put("com.sun.jndi.ldap.read.timeout", "3000");
+            sslenv.put(Context.SECURITY_PROTOCOL, "ssl");
+            testFailed = (new DeadServerTimeoutSSLTest(sslenv).call()) ? false : true;
+
             if (testFailed) {
                 throw new AssertionError("some tests failed");
             }
diff --git a/jdk/test/demo/jvmti/hprof/CpuOldTest.java b/jdk/test/demo/jvmti/hprof/CpuOldTest.java
index 0017b21..8207044 100644
--- a/jdk/test/demo/jvmti/hprof/CpuOldTest.java
+++ b/jdk/test/demo/jvmti/hprof/CpuOldTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
  * 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,7 @@
         DemoRun hprof;
 
         /* Run JVMTI hprof agent with cpu=old */
-        hprof = new DemoRun("hprof", "cpu=old,file=cpuold.txt");
+        hprof = new DemoRun("hprof", "cpu=old");
         hprof.runit(args[0]);
 
         /* Make sure patterns in output look ok */
diff --git a/jdk/test/demo/jvmti/hprof/CpuSamplesTest.java b/jdk/test/demo/jvmti/hprof/CpuSamplesTest.java
index 986af43..ad46618 100644
--- a/jdk/test/demo/jvmti/hprof/CpuSamplesTest.java
+++ b/jdk/test/demo/jvmti/hprof/CpuSamplesTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
  * 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,7 @@
         DemoRun hprof;
 
         /* Run JVMTI hprof agent with cpu=samples */
-        hprof = new DemoRun("hprof", "cpu=samples,file=cpusamples.txt");
+        hprof = new DemoRun("hprof", "cpu=samples");
         hprof.runit(args[0]);
 
         /* Make sure patterns in output look ok */
diff --git a/jdk/test/demo/jvmti/hprof/CpuTimesDefineClassTest.java b/jdk/test/demo/jvmti/hprof/CpuTimesDefineClassTest.java
index 3cf96bb..97c50eb 100644
--- a/jdk/test/demo/jvmti/hprof/CpuTimesDefineClassTest.java
+++ b/jdk/test/demo/jvmti/hprof/CpuTimesDefineClassTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
  * 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,7 @@
         DemoRun hprof;
 
         /* Run JVMTI hprof agent with cpu=times */
-        hprof = new DemoRun("hprof", "cpu=times,file=cputimedefineclass.txt");
+        hprof = new DemoRun("hprof", "cpu=times");
         hprof.runit(args[0]);
 
         /* Make sure patterns in output look ok */
diff --git a/jdk/test/demo/jvmti/hprof/CpuTimesTest.java b/jdk/test/demo/jvmti/hprof/CpuTimesTest.java
index 4d67900..7692d2a 100644
--- a/jdk/test/demo/jvmti/hprof/CpuTimesTest.java
+++ b/jdk/test/demo/jvmti/hprof/CpuTimesTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2010, Oracle and/or its affiliates. All rights reserved.
  * 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,7 @@
         DemoRun hprof;
 
         /* Run JVMTI hprof agent with cpu=times */
-        hprof = new DemoRun("hprof", "cpu=times,file=cputimes.txt");
+        hprof = new DemoRun("hprof", "cpu=times");
         hprof.runit(args[0]);
 
         /* Make sure patterns in output look ok */
diff --git a/jdk/test/demo/jvmti/hprof/HeapAllTest.java b/jdk/test/demo/jvmti/hprof/HeapAllTest.java
index d543f73..0801559 100644
--- a/jdk/test/demo/jvmti/hprof/HeapAllTest.java
+++ b/jdk/test/demo/jvmti/hprof/HeapAllTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
  * 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,7 @@
         DemoRun hprof;
 
         /* Run JVMTI hprof agent with heap=all */
-        hprof = new DemoRun("hprof", "heap=all,file=heapall.txt");
+        hprof = new DemoRun("hprof", "heap=all");
         hprof.runit(args[0]);
 
         /* Make sure patterns in output look ok */
diff --git a/jdk/test/demo/jvmti/hprof/HeapBinaryFormatTest.java b/jdk/test/demo/jvmti/hprof/HeapBinaryFormatTest.java
index 0bc0135..94567cd 100644
--- a/jdk/test/demo/jvmti/hprof/HeapBinaryFormatTest.java
+++ b/jdk/test/demo/jvmti/hprof/HeapBinaryFormatTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, Oracle and/or its affiliates. All rights reserved.
  * 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,7 @@
         DemoRun hprof;
 
         /* Run JVMTI hprof agent to get binary format dump */
-        hprof = new DemoRun("hprof", "heap=dump,format=b,logflags=4,file=heapbinaryformat.txt");
+        hprof = new DemoRun("hprof", "heap=dump,format=b,logflags=4");
         hprof.runit(args[0]);
 
         /* Make sure patterns in output look ok */
diff --git a/jdk/test/demo/jvmti/hprof/HeapDumpTest.java b/jdk/test/demo/jvmti/hprof/HeapDumpTest.java
index 1129e93..32cc01c 100644
--- a/jdk/test/demo/jvmti/hprof/HeapDumpTest.java
+++ b/jdk/test/demo/jvmti/hprof/HeapDumpTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
  * 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,7 @@
         DemoRun hprof;
 
         /* Run JVMTI hprof agent with heap=dump */
-        hprof = new DemoRun("hprof", "heap=dump,file=heapdump.txt");
+        hprof = new DemoRun("hprof", "heap=dump");
         hprof.runit(args[0]);
 
         /* Make sure patterns in output look ok */
diff --git a/jdk/test/demo/jvmti/hprof/HeapSitesTest.java b/jdk/test/demo/jvmti/hprof/HeapSitesTest.java
index 855bfad..3bdbe6c 100644
--- a/jdk/test/demo/jvmti/hprof/HeapSitesTest.java
+++ b/jdk/test/demo/jvmti/hprof/HeapSitesTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
  * 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,7 @@
         DemoRun hprof;
 
         /* Run JVMTI hprof agent with heap=sites */
-        hprof = new DemoRun("hprof", "heap=sites,file=heapsites.txt");
+        hprof = new DemoRun("hprof", "heap=sites");
         hprof.runit(args[0]);
 
         /* Make sure patterns in output look ok */
diff --git a/jdk/test/demo/jvmti/hprof/MonitorTest.java b/jdk/test/demo/jvmti/hprof/MonitorTest.java
index 2e8261f..2512efd 100644
--- a/jdk/test/demo/jvmti/hprof/MonitorTest.java
+++ b/jdk/test/demo/jvmti/hprof/MonitorTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
         DemoRun hprof;
 
         /* Run JVMTI hprof agent with monitor=y */
-        hprof = new DemoRun("hprof", "monitor=y,file=monitor.txt");
+        hprof = new DemoRun("hprof", "monitor=y");
         hprof.runit(args[0]);
 
         /* Make sure patterns in output look ok */
diff --git a/jdk/test/demo/jvmti/hprof/OptionsTest.java b/jdk/test/demo/jvmti/hprof/OptionsTest.java
index ebd0922..397357c 100644
--- a/jdk/test/demo/jvmti/hprof/OptionsTest.java
+++ b/jdk/test/demo/jvmti/hprof/OptionsTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2004, 2014, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2004, 2005, Oracle and/or its affiliates. All rights reserved.
  * 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 @@
         DemoRun hprof;
         List<String> options = new LinkedList<String>();
 
-        options.add("cpu=samples,depth=0,file=options0.txt");
-        options.add("cpu=times,depth=0,file=options1.txt");
-        options.add("cpu=old,depth=0,file=options2.txt");
-        options.add("depth=0,file=options3.txt");
+        options.add("cpu=samples,depth=0");
+        options.add("cpu=times,depth=0");
+        options.add("cpu=old,depth=0");
+        options.add("depth=0");
 
         for(String option: options) {
             /* Run JVMTI hprof agent with various options */
diff --git a/jdk/test/demo/jvmti/hprof/StackMapTableTest.java b/jdk/test/demo/jvmti/hprof/StackMapTableTest.java
index 3e4629e..eb3fae1 100644
--- a/jdk/test/demo/jvmti/hprof/StackMapTableTest.java
+++ b/jdk/test/demo/jvmti/hprof/StackMapTableTest.java
@@ -40,10 +40,10 @@
         DemoRun hprof;
         List<String> options = new LinkedList<String>();
 
-        options.add("cpu=samples,file=stackmaptable0.txt");
-        options.add("cpu=times,file=stackmaptable1.txt");
-        options.add("heap=sites,file=stackmaptable2.txt");
-        options.add("file=stackmaptable3.txt");
+        options.add("cpu=samples");
+        options.add("cpu=times");
+        options.add("heap=sites");
+        options.add("");
 
         for(String option: options) {
             /* Run JVMTI hprof agent with various options */
diff --git a/jdk/test/java/awt/InputMethods/DiacriticsTest/DiacriticsTest.html b/jdk/test/java/awt/InputMethods/DiacriticsTest/DiacriticsTest.html
index 5cf5c91..89dab3d 100644
--- a/jdk/test/java/awt/InputMethods/DiacriticsTest/DiacriticsTest.html
+++ b/jdk/test/java/awt/InputMethods/DiacriticsTest/DiacriticsTest.html
@@ -1,5 +1,5 @@
 <!--
-Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
 DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 
 This code is free software; you can redistribute it and/or modify it
@@ -31,8 +31,6 @@
 Test run requires the following keyboard layouts to be installed:
 Linux OS: English (US, alternative international)
 Windows OS: Hungarian
-A keyboard layout having compose function or compose-like key. Programmer
-Dvorak (http://www.kaufmann.no/roland/dvorak/) is suggested to use.
 
 To test JDK-8000423 fix (Linux only!):
 please switch to US alternative international layout and try to type diacritics
@@ -42,12 +40,6 @@
 please switch to Hungarian keyboard layout and try to type diacritics 
 (Ctrl+Alt+2 e; Ctrl+Alt+2 E)
 
-To test JDK-8139189 fix:
-please switch to Programmer Dvorak keyboard layout try to type diacritics
-using compose combinations (Compose+z+d, Compose+z+Shift+d). The Compose key
-in Programmer Dvorak layout is OEM102 the key which is located between
-Left Shift and Z keys on the standard 102-key keyboard.
-
 If you can do that then the test is passed; otherwise failed.
 </body>
 </html>
diff --git a/jdk/test/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java b/jdk/test/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java
index a22d51f..ec42aa9 100644
--- a/jdk/test/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java
+++ b/jdk/test/java/awt/SplashScreen/MultiResolutionSplash/MultiResolutionSplashTest.java
@@ -93,15 +93,6 @@
         int screenX = (int) splashBounds.getCenterX();
         int screenY = (int) splashBounds.getCenterY();
 
-        if(splashBounds.width != IMAGE_WIDTH){
-            throw new RuntimeException(
-                    "SplashScreen#getBounds has wrong width");
-        }
-        if(splashBounds.height != IMAGE_HEIGHT){
-            throw new RuntimeException(
-                    "SplashScreen#getBounds has wrong height");
-        }
-
         Robot robot = new Robot();
         Color splashScreenColor = robot.getPixelColor(screenX, screenY);
 
diff --git a/jdk/test/java/awt/Window/WindowsLeak/WindowsLeak.java b/jdk/test/java/awt/Window/WindowsLeak/WindowsLeak.java
index 3f44687..dd776a8 100644
--- a/jdk/test/java/awt/Window/WindowsLeak/WindowsLeak.java
+++ b/jdk/test/java/awt/Window/WindowsLeak/WindowsLeak.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,40 +23,41 @@
 
 /*
  * @test
- * @bug 8013563 8028486
+ * @bug 8013563
  * @summary Tests that windows are removed from windows list
- * @library /javax/swing/regtesthelpers
- * @build Util
  * @run main/othervm -Xms32M -Xmx32M WindowsLeak
 */
 
-import java.awt.Frame;
-import java.awt.Robot;
-import java.awt.Window;
-import java.lang.ref.WeakReference;
-import java.util.Vector;
-
+import java.awt.*;
 import sun.awt.AppContext;
-import sun.java2d.Disposer;
+
+import java.lang.ref.WeakReference;
+
+import java.util.Vector;
 
 public class WindowsLeak {
 
-    private static volatile boolean disposerPhantomComplete;
-
-    public static void main(String[] args) throws Exception {
-        Robot r = new Robot();
-        for (int i = 0; i < 100; i++) {
+    public static void main(String[] args) {
+        for (int i = 0; i < 100; i++)
+        {
             Frame f = new Frame();
             f.pack();
             f.dispose();
         }
-        r.waitForIdle();
 
-        Disposer.addRecord(new Object(), () -> disposerPhantomComplete = true);
-
-        while (!disposerPhantomComplete) {
-            Util.generateOOME();
+        Vector garbage = new Vector();
+        while (true)
+        {
+            try
+            {
+                garbage.add(new byte[1000]);
+            }
+            catch (OutOfMemoryError e)
+            {
+                break;
+            }
         }
+        garbage = null;
 
         Vector<WeakReference<Window>> windowList =
                         (Vector<WeakReference<Window>>) AppContext.getAppContext().get(Window.class);
diff --git a/jdk/test/java/awt/datatransfer/DataFlavor/MacOsXFileAndMultipleFileCopingTest/MacOsXFileAndMultipleFileCopingTest.java b/jdk/test/java/awt/datatransfer/DataFlavor/MacOsXFileAndMultipleFileCopingTest/MacOsXFileAndMultipleFileCopingTest.java
index eaa1364..18b7012 100644
--- a/jdk/test/java/awt/datatransfer/DataFlavor/MacOsXFileAndMultipleFileCopingTest/MacOsXFileAndMultipleFileCopingTest.java
+++ b/jdk/test/java/awt/datatransfer/DataFlavor/MacOsXFileAndMultipleFileCopingTest/MacOsXFileAndMultipleFileCopingTest.java
@@ -23,7 +23,7 @@
 
 /*
   @test
-  @bug 8081787 8136763 8160941
+  @bug 8081787 8136763
   @author Mikhail Cherkasov
   @run main/manual MacOsXFileAndMultipleFileCopingTest
 */
diff --git a/jdk/test/java/awt/event/KeyEvent/KeyChar/KeyCharTest.java b/jdk/test/java/awt/event/KeyEvent/KeyChar/KeyCharTest.java
index dd50483..a482cea 100644
--- a/jdk/test/java/awt/event/KeyEvent/KeyChar/KeyCharTest.java
+++ b/jdk/test/java/awt/event/KeyEvent/KeyChar/KeyCharTest.java
@@ -32,7 +32,7 @@
 
 /*
  * @test
- * @bug 8022401 8160623
+ * @bug 8022401
  * @summary Wrong key char
  * @author Alexandr Scherbatiy
  * @run main KeyCharTest
diff --git a/jdk/test/java/lang/invoke/CustomizedLambdaFormTest.java b/jdk/test/java/lang/invoke/CustomizedLambdaFormTest.java
index a0ecdcd..3e24673 100644
--- a/jdk/test/java/lang/invoke/CustomizedLambdaFormTest.java
+++ b/jdk/test/java/lang/invoke/CustomizedLambdaFormTest.java
@@ -26,7 +26,7 @@
 /* @test
  * @summary Assertion in LambdaFormEditor.bindArgumentType is too strong
  *
- * @run main/othervm/bootclasspath -esa java.lang.invoke.CustomizedLambdaFormTest
+ * @run main/bootclasspath -esa java.lang.invoke.CustomizedLambdaFormTest
  */
 public class CustomizedLambdaFormTest {
 
diff --git a/jdk/test/java/lang/invoke/PermuteArgsTest.java b/jdk/test/java/lang/invoke/PermuteArgsTest.java
index a47e4d7..edb9ba3 100644
--- a/jdk/test/java/lang/invoke/PermuteArgsTest.java
+++ b/jdk/test/java/lang/invoke/PermuteArgsTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2011, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2011, 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
@@ -23,7 +23,6 @@
 
 /* @test
  * @summary unit tests for method handles which permute their arguments
- * @library /lib/testlibrary/jsr292 /lib/testlibrary
  * @run testng/othervm -XX:+IgnoreUnrecognizedVMOptions -XX:-VerifyDependencies -ea -esa -DPermuteArgsTest.MAX_ARITY=8 test.java.lang.invoke.PermuteArgsTest
  */
 /* Examples of manual runs:
@@ -37,8 +36,6 @@
 import org.testng.*;
 import org.testng.annotations.*;
 
-import com.oracle.testlibrary.jsr292.CodeCacheOverflowProcessor;
-
 import java.util.*;
 import java.lang.reflect.*;
 
@@ -125,15 +122,9 @@
         }
         new PermuteArgsTest().test();
     }
-
     static int testCases;
-
     @Test
     public void test() throws Throwable {
-        CodeCacheOverflowProcessor.runMHTest(this::test0);
-    }
-
-    public void test0() throws Throwable {
         testCases = 0;
         Lookup lookup = lookup();
         for (Method m : lookup.lookupClass().getDeclaredMethods()) {
diff --git a/jdk/test/java/lang/invoke/VarargsArrayTest.java b/jdk/test/java/lang/invoke/VarargsArrayTest.java
index 468eb42..a247fa5 100644
--- a/jdk/test/java/lang/invoke/VarargsArrayTest.java
+++ b/jdk/test/java/lang/invoke/VarargsArrayTest.java
@@ -32,12 +32,13 @@
  * @summary unit tests for varargs array methods: MethodHandleInfo.varargsArray(int),
  *          MethodHandleInfo.varargsArray(Class,int) & MethodHandleInfo.varargsList(int)
  * @library /lib/testlibrary /lib/testlibrary/jsr292
- * @run main/othervm/bootclasspath java.lang.invoke.VarargsArrayTest
- * @run main/othervm/bootclasspath -DVarargsArrayTest.MAX_ARITY=255 -DVarargsArrayTest.START_ARITY=250 java.lang.invoke.VarargsArrayTest
+ * @run main/bootclasspath java.lang.invoke.VarargsArrayTest
+ * @run main/bootclasspath -DVarargsArrayTest.MAX_ARITY=255 -DVarargsArrayTest.START_ARITY=250
+ *                         java.lang.invoke.VarargsArrayTest
  */
 
 /* This might take a while and burn lots of metadata:
- * @run main/othervm/bootclasspath -DVarargsArrayTest.MAX_ARITY=255 -DVarargsArrayTest.EXHAUSTIVE=true java.lang.invoke.VarargsArrayTest
+ * @run main/bootclasspath -DVarargsArrayTest.MAX_ARITY=255 -DVarargsArrayTest.EXHAUSTIVE=true java.lang.invoke.VarargsArrayTest
  */
 public class VarargsArrayTest {
     private static final Class<?> CLASS = VarargsArrayTest.class;
diff --git a/jdk/test/java/security/SecureRandom/DefaultProvider.java b/jdk/test/java/security/SecureRandom/DefaultProvider.java
index 597f235..50b4719 100644
--- a/jdk/test/java/security/SecureRandom/DefaultProvider.java
+++ b/jdk/test/java/security/SecureRandom/DefaultProvider.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -43,7 +43,12 @@
         out.println("TEST: Default provider with constructor");
         SecureRandom secureRandom = new SecureRandom();
         String provider = secureRandom.getProvider().getName();
-        if (!provider.equals("SUN")) {
+        if (OS_NAME.startsWith(SUNOS)) {
+            if (!provider.startsWith("SunPKCS11-")) {
+                throw new RuntimeException("Unexpected provider name: "
+                        + provider);
+            }
+        } else if (!provider.equals("SUN")) {
             throw new RuntimeException("Unexpected provider name: "
                     + provider);
         }
@@ -72,6 +77,16 @@
         instance = SecureRandom.getInstance(algorithm);
         assertInstance(instance, algorithm, provider);
         out.println("Passed.");
+
+        if (OS_NAME.startsWith(SUNOS)) {
+            out.println(
+                    "TEST: PKCS11 is supported on Solaris by SunPKCS11 provider");
+            algorithm = "PKCS11";
+            provider = "SunPKCS11-Solaris";
+            instance = SecureRandom.getInstance(algorithm);
+            assertInstance(instance, algorithm, provider);
+            out.println("Passed.");
+        }
     }
 
     private static void assertInstance(SecureRandom instance,
diff --git a/jdk/test/java/security/Security/AddProvider.java b/jdk/test/java/security/Security/AddProvider.java
index b702221..27559ff 100644
--- a/jdk/test/java/security/Security/AddProvider.java
+++ b/jdk/test/java/security/Security/AddProvider.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -23,7 +23,7 @@
 
 /*
  * @test
- * @bug 8001319 8154009
+ * @bug 8001319
  * @summary check that SecurityPermission insertProvider permission is enforced
  *          correctly
  * @run main/othervm/policy=AddProvider.policy.1 AddProvider 1
diff --git a/jdk/test/java/security/Security/AddProvider.policy.1 b/jdk/test/java/security/Security/AddProvider.policy.1
index 64b43d7..17a49b4 100644
--- a/jdk/test/java/security/Security/AddProvider.policy.1
+++ b/jdk/test/java/security/Security/AddProvider.policy.1
@@ -1,3 +1,7 @@
+grant codeBase "file:${{java.ext.dirs}}/*" {
+	permission java.security.AllPermission;
+};
+
 grant {
     permission java.security.SecurityPermission "insertProvider";
 };
diff --git a/jdk/test/java/security/Security/AddProvider.policy.2 b/jdk/test/java/security/Security/AddProvider.policy.2
index e2a8677..d5a7ca9 100644
--- a/jdk/test/java/security/Security/AddProvider.policy.2
+++ b/jdk/test/java/security/Security/AddProvider.policy.2
@@ -1,3 +1,7 @@
+grant codeBase "file:${{java.ext.dirs}}/*" {
+	permission java.security.AllPermission;
+};
+
 grant {
     permission java.security.SecurityPermission "insertProvider.Test1";
     permission java.security.SecurityPermission "insertProvider.Test2";
diff --git a/jdk/test/java/security/Security/AddProvider.policy.3 b/jdk/test/java/security/Security/AddProvider.policy.3
index 9a14db2..930b443 100644
--- a/jdk/test/java/security/Security/AddProvider.policy.3
+++ b/jdk/test/java/security/Security/AddProvider.policy.3
@@ -1,3 +1,7 @@
+grant codeBase "file:${{java.ext.dirs}}/*" {
+	permission java.security.AllPermission;
+};
+
 grant {
     permission java.security.SecurityPermission "insertProvider.*";
 };
diff --git a/jdk/test/java/security/Security/removing/RemoveStaticProvider.java b/jdk/test/java/security/Security/removing/RemoveStaticProvider.java
index 20d4435..6a03ec7 100644
--- a/jdk/test/java/security/Security/removing/RemoveStaticProvider.java
+++ b/jdk/test/java/security/Security/removing/RemoveStaticProvider.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2001, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2001, 2003, Oracle and/or its affiliates. All rights reserved.
  * 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 4420687 8154009
+ * @bug 4420687
  * @summary Make sure that a removed provider won't be acceessable.
  * @run main/othervm/policy=RemoveStaticProvider.policy RemoveStaticProvider
  */
diff --git a/jdk/test/java/security/Security/removing/RemoveStaticProvider.policy b/jdk/test/java/security/Security/removing/RemoveStaticProvider.policy
index f31e587..3b186af 100644
--- a/jdk/test/java/security/Security/removing/RemoveStaticProvider.policy
+++ b/jdk/test/java/security/Security/removing/RemoveStaticProvider.policy
@@ -3,3 +3,8 @@
     permission java.security.SecurityPermission "insertProvider.SunJCE";
 };
 
+// Standard extensions get all permissions
+grant codeBase "file:${java.home}/lib/ext/*" {
+        permission java.security.AllPermission;
+};
+
diff --git a/jdk/test/java/time/tck/java/time/TCKZoneOffset.java b/jdk/test/java/time/tck/java/time/TCKZoneOffset.java
index 7646643..c121079 100644
--- a/jdk/test/java/time/tck/java/time/TCKZoneOffset.java
+++ b/jdk/test/java/time/tck/java/time/TCKZoneOffset.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -419,21 +419,6 @@
         ZoneOffset.ofHoursMinutesSeconds(-19, 0, 0);
     }
 
-    @Test(expectedExceptions=DateTimeException.class)
-    public void test_factory_int_hours_minutes_seconds_minutesMinValue() {
-        ZoneOffset.ofHoursMinutesSeconds(0, Integer.MIN_VALUE, -1);
-    }
-
-    @Test(expectedExceptions=DateTimeException.class)
-    public void test_factory_int_hours_minutes_seconds_secondsMinValue() {
-        ZoneOffset.ofHoursMinutesSeconds(0, 0, Integer.MIN_VALUE);
-    }
-
-    @Test(expectedExceptions=DateTimeException.class)
-    public void test_factory_int_hours_minutes_seconds_minutesAndSecondsMinValue() {
-        ZoneOffset.ofHoursMinutesSeconds(0, Integer.MIN_VALUE, Integer.MIN_VALUE);
-    }
-
     //-----------------------------------------------------------------------
     @Test
     public void test_factory_ofTotalSeconds() {
@@ -452,11 +437,6 @@
         ZoneOffset.ofTotalSeconds(-18 * 60 * 60 - 1);
     }
 
-    @Test(expectedExceptions=DateTimeException.class)
-    public void test_factory_ofTotalSeconds_minValue() {
-        ZoneOffset.ofTotalSeconds(Integer.MIN_VALUE);
-    }
-
     //-----------------------------------------------------------------------
     // from()
     //-----------------------------------------------------------------------
diff --git a/jdk/test/java/time/test/java/time/format/TestZoneTextPrinterParser.java b/jdk/test/java/time/test/java/time/format/TestZoneTextPrinterParser.java
index 9484e38..7808624 100644
--- a/jdk/test/java/time/test/java/time/format/TestZoneTextPrinterParser.java
+++ b/jdk/test/java/time/test/java/time/format/TestZoneTextPrinterParser.java
@@ -49,7 +49,7 @@
 
 /*
  * @test
- * @bug 8081022 8151876 8166875
+ * @bug 8081022 8151876
  * @key randomness
  */
 
diff --git a/jdk/test/java/time/test/java/time/format/ZoneName.java b/jdk/test/java/time/test/java/time/format/ZoneName.java
index 1fbb913..2c49446 100644
--- a/jdk/test/java/time/test/java/time/format/ZoneName.java
+++ b/jdk/test/java/time/test/java/time/format/ZoneName.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -378,7 +378,6 @@
         "Europe/Helsinki", "Europe_Eastern", "Europe/Bucharest",
         "America/Nome", "Alaska", "America/Juneau",
         "Asia/Yakutsk", "Yakutsk", "Asia/Yakutsk",
-        "Asia/Yangon", "Myanmar", "Asia/Rangoon",
         "Africa/Conakry", "GMT", "Atlantic/Reykjavik",
         "Asia/Seoul", "Korea", "Asia/Seoul",
         "America/Antigua", "Atlantic", "America/Halifax",
@@ -748,7 +747,6 @@
         "NZ", "Pacific/Auckland",
         "Asia/Tel_Aviv", "Asia/Jerusalem",
         "Hongkong", "Asia/Hong_Kong",
-        "Asia/Rangoon", "Asia/Yangon",
     };
 
     private static final Map<String, String> zidToMzone = new HashMap<>();
diff --git a/jdk/test/java/util/Base64/TestBase64.java b/jdk/test/java/util/Base64/TestBase64.java
index 5ddaafe..bbde587 100644
--- a/jdk/test/java/util/Base64/TestBase64.java
+++ b/jdk/test/java/util/Base64/TestBase64.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -23,11 +23,8 @@
 
 /**
  * @test 4235519 8004212 8005394 8007298 8006295 8006315 8006530 8007379 8008925
- *       8014217 8025003 8026330 8028397 8165243
+ *       8014217 8025003 8026330 8028397
  * @summary tests java.util.Base64
- * @library /lib/testlibrary
- * @build jdk.testlibrary.*
- * @run main TestBase64
  */
 
 import java.io.ByteArrayInputStream;
@@ -37,17 +34,11 @@
 import java.io.OutputStream;
 import java.nio.ByteBuffer;
 import java.util.Arrays;
-import java.util.ArrayList;
 import java.util.Base64;
-import java.util.List;
 import java.util.Random;
 
-import jdk.testlibrary.RandomFactory;
-
 public class TestBase64 {
 
-    private static final Random rnd = RandomFactory.getRandom();
-
     public static void main(String args[]) throws Throwable {
         int numRuns  = 10;
         int numBytes = 200;
@@ -60,6 +51,7 @@
         test(Base64.getUrlEncoder(), Base64.getUrlDecoder(), numRuns, numBytes);
         test(Base64.getMimeEncoder(), Base64.getMimeDecoder(), numRuns, numBytes);
 
+        Random rnd = new java.util.Random();
         byte[] nl_1 = new byte[] {'\n'};
         byte[] nl_2 = new byte[] {'\n', '\r'};
         byte[] nl_3 = new byte[] {'\n', '\r', '\n'};
@@ -83,7 +75,7 @@
         testNull(Base64.getDecoder());
         testNull(Base64.getUrlDecoder());
         testNull(Base64.getMimeDecoder());
-        checkNull(() -> Base64.getMimeEncoder(10, null));
+        checkNull(new Runnable() { public void run() { Base64.getMimeEncoder(10, null); }});
 
         testIOE(Base64.getEncoder());
         testIOE(Base64.getUrlEncoder());
@@ -91,23 +83,26 @@
         testIOE(Base64.getMimeEncoder(10, new byte[]{'\n'}));
 
         byte[] src = new byte[1024];
-        rnd.nextBytes(src);
+        new Random().nextBytes(src);
         final byte[] decoded = Base64.getEncoder().encode(src);
         testIOE(Base64.getDecoder(), decoded);
         testIOE(Base64.getMimeDecoder(), decoded);
         testIOE(Base64.getUrlDecoder(), Base64.getUrlEncoder().encode(src));
 
         // illegal line separator
-        checkIAE(() -> Base64.getMimeEncoder(10, new byte[]{'\r', 'N'}));
+        checkIAE(new Runnable() { public void run() { Base64.getMimeEncoder(10, new byte[]{'\r', 'N'}); }});
 
         // malformed padding/ending
         testMalformedPadding();
 
         // illegal base64 character
         decoded[2] = (byte)0xe0;
-        checkIAE(() -> Base64.getDecoder().decode(decoded));
-        checkIAE(() -> Base64.getDecoder().decode(decoded, new byte[1024]));
-        checkIAE(() -> Base64.getDecoder().decode(ByteBuffer.wrap(decoded)));
+        checkIAE(new Runnable() {
+            public void run() { Base64.getDecoder().decode(decoded); }});
+        checkIAE(new Runnable() {
+            public void run() { Base64.getDecoder().decode(decoded, new byte[1024]); }});
+        checkIAE(new Runnable() { public void run() {
+            Base64.getDecoder().decode(ByteBuffer.wrap(decoded)); }});
 
         // test single-non-base64 character for mime decoding
         testSingleNonBase64MimeDec();
@@ -117,16 +112,6 @@
 
         // test mime decoding with ignored character after padding
         testDecodeIgnoredAfterPadding();
-
-        // given invalid args, encoder should not produce output
-        testEncoderKeepsSilence(Base64.getEncoder());
-        testEncoderKeepsSilence(Base64.getUrlEncoder());
-        testEncoderKeepsSilence(Base64.getMimeEncoder());
-
-        // given invalid args, decoder should not consume input
-        testDecoderKeepsAbstinence(Base64.getDecoder());
-        testDecoderKeepsAbstinence(Base64.getUrlDecoder());
-        testDecoderKeepsAbstinence(Base64.getMimeDecoder());
     }
 
     private static sun.misc.BASE64Encoder sunmisc = new sun.misc.BASE64Encoder();
@@ -297,49 +282,48 @@
     private static final String str_null = null;
     private static final ByteBuffer bb_null = null;
 
-    private static void testNull(Base64.Encoder enc) {
-        checkNull(() -> enc.encode(ba_null));
-        checkNull(() -> enc.encodeToString(ba_null));
-        checkNull(() -> enc.encode(ba_null, new byte[10]));
-        checkNull(() -> enc.encode(new byte[10], ba_null));
-        checkNull(() -> enc.encode(bb_null));
-        checkNull(() -> enc.wrap((OutputStream)null));
+    private static void testNull(final Base64.Encoder enc) {
+        checkNull(new Runnable() { public void run() { enc.encode(ba_null); }});
+        checkNull(new Runnable() { public void run() { enc.encodeToString(ba_null); }});
+        checkNull(new Runnable() { public void run() { enc.encode(ba_null, new byte[10]); }});
+        checkNull(new Runnable() { public void run() { enc.encode(new byte[10], ba_null); }});
+        checkNull(new Runnable() { public void run() { enc.encode(bb_null); }});
+        checkNull(new Runnable() { public void run() { enc.wrap((OutputStream)null); }});
     }
 
-    private static void testNull(Base64.Decoder dec) {
-        checkNull(() -> dec.decode(ba_null));
-        checkNull(() -> dec.decode(str_null));
-        checkNull(() -> dec.decode(ba_null, new byte[10]));
-        checkNull(() -> dec.decode(new byte[10], ba_null));
-        checkNull(() -> dec.decode(bb_null));
-        checkNull(() -> dec.wrap((InputStream)null));
+    private static void testNull(final Base64.Decoder dec) {
+        checkNull(new Runnable() { public void run() { dec.decode(ba_null); }});
+        checkNull(new Runnable() { public void run() { dec.decode(str_null); }});
+        checkNull(new Runnable() { public void run() { dec.decode(ba_null, new byte[10]); }});
+        checkNull(new Runnable() { public void run() { dec.decode(new byte[10], ba_null); }});
+        checkNull(new Runnable() { public void run() { dec.decode(bb_null); }});
+        checkNull(new Runnable() { public void run() { dec.wrap((InputStream)null); }});
     }
 
-    @FunctionalInterface
     private static interface Testable {
         public void test() throws Throwable;
     }
 
-    private static void testIOE(Base64.Encoder enc) throws Throwable {
+    private static void testIOE(final Base64.Encoder enc) throws Throwable {
         ByteArrayOutputStream baos = new ByteArrayOutputStream(8192);
-        OutputStream os = enc.wrap(baos);
+        final OutputStream os = enc.wrap(baos);
         os.write(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9});
         os.close();
-        checkIOE(() -> os.write(10));
-        checkIOE(() -> os.write(new byte[] {10}));
-        checkIOE(() -> os.write(new byte[] {10}, 1, 4));
+        checkIOE(new Testable() { public void test() throws Throwable { os.write(10); }});
+        checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}); }});
+        checkIOE(new Testable() { public void test() throws Throwable { os.write(new byte[] {10}, 1, 4); }});
     }
 
-    private static void testIOE(Base64.Decoder dec, byte[] decoded) throws Throwable {
+    private static void testIOE(final Base64.Decoder dec, byte[] decoded) throws Throwable {
         ByteArrayInputStream bais = new ByteArrayInputStream(decoded);
-        InputStream is = dec.wrap(bais);
+        final InputStream is = dec.wrap(bais);
         is.read(new byte[10]);
         is.close();
-        checkIOE(() -> is.read());
-        checkIOE(() -> is.read(new byte[] {10}));
-        checkIOE(() -> is.read(new byte[] {10}, 1, 4));
-        checkIOE(() -> is.available());
-        checkIOE(() -> is.skip(20));
+        checkIOE(new Testable() { public void test() throws Throwable { is.read(); }});
+        checkIOE(new Testable() { public void test() throws Throwable { is.read(new byte[] {10}); }});
+        checkIOE(new Testable() { public void test() throws Throwable { is.read(new byte[] {10}, 1, 4); }});
+        checkIOE(new Testable() { public void test() throws Throwable { is.available(); }});
+        checkIOE(new Testable() { public void test() throws Throwable { is.skip(20); }});
     }
 
     private static final void checkNull(Runnable r) {
@@ -431,13 +415,13 @@
                 int pos = (Integer)data[i + 2];
 
                 // decode(byte[])
-                checkIAE(() -> dec.decode(srcBytes));
+                checkIAE(new Runnable() { public void run() { dec.decode(srcBytes); }});
 
                 // decode(String)
-                checkIAE(() -> dec.decode(srcStr));
+                checkIAE(new Runnable() { public void run() { dec.decode(srcStr); }});
 
                 // decode(ByteBuffer)
-                checkIAE(() -> dec.decode(srcBB));
+                checkIAE(new Runnable() { public void run() { dec.decode(srcBB); }});
 
                 // wrap stream
                 checkIOE(new Testable() {
@@ -547,67 +531,4 @@
         }
         return ret;
     }
-
-    private static void testEncoderKeepsSilence(Base64.Encoder enc)
-            throws Throwable {
-        List<Integer> vals = Arrays.asList(Integer.MIN_VALUE,
-                Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,
-                Integer.MAX_VALUE - 1, Integer.MAX_VALUE,
-                rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),
-                rnd.nextInt());
-        byte[] buf = new byte[] {1, 0, 91};
-        for (int off : vals) {
-            for (int len : vals) {
-                if (off >= 0 && len >= 0 && off <= buf.length - len) {
-                    // valid args, skip them
-                    continue;
-                }
-                // invalid args, test them
-                System.out.println("testing off=" + off + ", len=" + len);
-
-                ByteArrayOutputStream baos = new ByteArrayOutputStream(100);
-                try (OutputStream os = enc.wrap(baos)) {
-                    os.write(buf, off, len);
-                    throw new RuntimeException("Expected IOOBEx was not thrown");
-                } catch (IndexOutOfBoundsException expected) {
-                }
-                if (baos.size() > 0)
-                    throw new RuntimeException("No output was expected, but got "
-                            + baos.size() + " bytes");
-            }
-        }
-    }
-
-    private static void testDecoderKeepsAbstinence(Base64.Decoder dec)
-            throws Throwable {
-        List<Integer> vals = Arrays.asList(Integer.MIN_VALUE,
-                Integer.MIN_VALUE + 1, -1111, -2, -1, 0, 1, 2, 3, 1111,
-                Integer.MAX_VALUE - 1, Integer.MAX_VALUE,
-                rnd.nextInt(), rnd.nextInt(), rnd.nextInt(),
-                rnd.nextInt());
-        byte[] buf = new byte[3];
-        for (int off : vals) {
-            for (int len : vals) {
-                if (off >= 0 && len >= 0 && off <= buf.length - len) {
-                    // valid args, skip them
-                    continue;
-                }
-                // invalid args, test them
-                System.out.println("testing off=" + off + ", len=" + len);
-
-                String input = "AAAAAAAAAAAAAAAAAAAAAA";
-                ByteArrayInputStream bais =
-                        new ByteArrayInputStream(input.getBytes("Latin1"));
-                try (InputStream is = dec.wrap(bais)) {
-                    is.read(buf, off, len);
-                    throw new RuntimeException("Expected IOOBEx was not thrown");
-                } catch (IndexOutOfBoundsException expected) {
-                }
-                if (bais.available() != input.length())
-                    throw new RuntimeException("No input should be consumed, "
-                            + "but consumed " + (input.length() - bais.available())
-                            + " bytes");
-            }
-        }
-    }
 }
diff --git a/jdk/test/java/util/Currency/tablea1.txt b/jdk/test/java/util/Currency/tablea1.txt
index 92e43ad..12c9f7e 100644
--- a/jdk/test/java/util/Currency/tablea1.txt
+++ b/jdk/test/java/util/Currency/tablea1.txt
@@ -1,12 +1,12 @@
 #
 #
-# Amendments up until ISO 4217 AMENDMENT NUMBER 160
-#   (As of 19 June 2015)
+# Amendments up until ISO 4217 AMENDMENT NUMBER 159
+#   (As of 15 August 2014)
 #
 
 # Version
 FILEVERSION=2
-DATAVERSION=160
+DATAVERSION=159
 
 # ISO 4217 currency data
 AF	AFN	971	2
diff --git a/jdk/test/javax/management/monitor/GaugeMonitorDeadlockTest.java b/jdk/test/javax/management/monitor/GaugeMonitorDeadlockTest.java
index 9e063a2..c85c223 100644
--- a/jdk/test/javax/management/monitor/GaugeMonitorDeadlockTest.java
+++ b/jdk/test/javax/management/monitor/GaugeMonitorDeadlockTest.java
@@ -27,7 +27,6 @@
  * @summary Test that no locks are held when a monitor attribute is sampled
  * or notif delivered.
  * @author Eamonn McManus
- * @library /lib/testlibrary
  * @run clean GaugeMonitorDeadlockTest
  * @run build GaugeMonitorDeadlockTest
  * @run main GaugeMonitorDeadlockTest 1
@@ -48,8 +47,6 @@
 import javax.management.monitor.GaugeMonitor;
 import javax.management.monitor.GaugeMonitorMBean;
 
-import jdk.testlibrary.Utils;
-
 public class GaugeMonitorDeadlockTest {
     private static enum When {IN_GET_ATTRIBUTE, IN_NOTIFY};
     private static long checkingTime;
@@ -57,7 +54,8 @@
     public static void main(String[] args) throws Exception {
         if (args.length != 1)
             throw new Exception("Arg should be test number");
-        checkingTime = Utils.adjustTimeout(1000); // default 1s timeout
+        double factor = Double.parseDouble(System.getProperty("test.timeout.factor", "1.0"));
+        checkingTime = (long)factor*1000;
         System.out.println("=== checkingTime = " + checkingTime + "ms");
 
         int testNo = Integer.parseInt(args[0]) - 1;
@@ -103,12 +101,11 @@
             monitorProxy.setGranularityPeriod(10L); // 10 ms
             monitorProxy.setNotifyHigh(true);
             monitorProxy.setNotifyLow(true);
+            monitorProxy.start();
 
             System.out.println("=== Waiting observedProxy.getGetCount() to be "
                     + "changed, presumable deadlock if timeout?");
             final int initGetCount = observedProxy.getGetCount();
-            monitorProxy.start();
-
             long checkedTime = System.currentTimeMillis();
             long nowTime;
             ThreadMXBean threadMXBean = ManagementFactory.getThreadMXBean();
diff --git a/jdk/test/javax/management/monitor/StringMonitorDeadlockTest.java b/jdk/test/javax/management/monitor/StringMonitorDeadlockTest.java
index 72929c2..2f78ce6 100644
--- a/jdk/test/javax/management/monitor/StringMonitorDeadlockTest.java
+++ b/jdk/test/javax/management/monitor/StringMonitorDeadlockTest.java
@@ -37,6 +37,7 @@
 
 import java.lang.management.ManagementFactory;
 import java.util.concurrent.atomic.AtomicInteger;
+import javax.management.Attribute;
 import javax.management.JMX;
 import javax.management.MBeanServer;
 import javax.management.Notification;
@@ -94,10 +95,9 @@
             monitorProxy.setStringToCompare("old");
             monitorProxy.setGranularityPeriod(10L); // 10 ms
             monitorProxy.setNotifyDiffer(true);
-
-            final int initGetCount = observedProxy.getGetCount();
             monitorProxy.start();
 
+            final int initGetCount = observedProxy.getGetCount();
             int getCount = initGetCount;
             for (int i = 0; i < 500; i++) { // 500 * 10 = 5 seconds
                 getCount = observedProxy.getGetCount();
diff --git a/jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java b/jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java
index 27b5782..382f201 100644
--- a/jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java
+++ b/jdk/test/javax/rmi/PortableRemoteObject/ConcurrentHashMapTest.java
@@ -28,11 +28,7 @@
  * @library /lib/testlibrary
  * @build jdk.testlibrary.*
  * @build Test HelloInterface HelloServer HelloClient HelloImpl _HelloImpl_Tie _HelloInterface_Stub ConcurrentHashMapTest
- * @run main/othervm -Djava.naming.provider.url=iiop://localhost:1050
- *    -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory  ConcurrentHashMapTest
- * @run main/othervm/secure=java.lang.SecurityManager/policy=jtreg.test.policy
- *    -Djava.naming.provider.url=iiop://localhost:1050
- *    -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory ConcurrentHashMapTest
+ * @run main/othervm -Djava.naming.provider.url=iiop://localhost:1050 -Djava.naming.factory.initial=com.sun.jndi.cosnaming.CNCtxFactory  ConcurrentHashMapTest
  */
 
 
diff --git a/jdk/test/javax/security/auth/kerberos/KerberosTixDateTest.java b/jdk/test/javax/security/auth/kerberos/KerberosTixDateTest.java
index 89d38bc..c061d1b 100644
--- a/jdk/test/javax/security/auth/kerberos/KerberosTixDateTest.java
+++ b/jdk/test/javax/security/auth/kerberos/KerberosTixDateTest.java
@@ -23,18 +23,15 @@
 
 /*
  * @test
- * @bug 6659990 8147772
- * @summary test the immutability of the Date fields in KerberosTicket class,
- *          serialization, and behavior after being destroyed.
+ * @bug 6659990
+ * @summary test the immutability of the Date fields in KerberosTicket class.
  * @ignore Must set up KDC and setup Kerberos configuration file
  */
 
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
+import java.net.InetAddress;
 import java.util.Date;
 import java.io.*;
-import javax.security.auth.RefreshFailedException;
+import javax.security.auth.kerberos.KerberosKey;
 import javax.security.auth.kerberos.KerberosPrincipal;
 import javax.security.auth.kerberos.KerberosTicket;
 import java.util.Base64;
@@ -78,7 +75,6 @@
 
         testDateImmutability(t, originalTime);
         testS11nCompatibility(t); // S11n: Serialization
-        testDestroy(t);
     }
 
     private static void checkTime(KerberosTicket kt, long timeValue) {
@@ -141,30 +137,4 @@
 
         System.out.println("S11nCompatibility Test Passed");
     }
-
-    private static void testDestroy(KerberosTicket t) throws Exception {
-        t.destroy();
-        if (!t.isDestroyed()) {
-            throw new RuntimeException("ticket should have been destroyed");
-        }
-        // Although these methods are meaningless, they can be called
-        for (Method m: KerberosTicket.class.getDeclaredMethods()) {
-            if (Modifier.isPublic(m.getModifiers())
-                    && m.getParameterCount() == 0) {
-                System.out.println("Testing " + m.getName() + "...");
-                try {
-                    m.invoke(t);
-                } catch (InvocationTargetException e) {
-                    Throwable cause = e.getCause();
-                    if (cause instanceof RefreshFailedException ||
-                            cause instanceof IllegalStateException) {
-                        // this is OK
-                    } else {
-                        throw e;
-                    }
-                }
-            }
-        }
-        System.out.println("Destroy Test Passed");
-    }
 }
diff --git a/jdk/test/javax/xml/crypto/dsig/GenerationTests.java b/jdk/test/javax/xml/crypto/dsig/GenerationTests.java
index 89fd46a..6cc7bbb 100644
--- a/jdk/test/javax/xml/crypto/dsig/GenerationTests.java
+++ b/jdk/test/javax/xml/crypto/dsig/GenerationTests.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 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
@@ -23,7 +23,7 @@
 
 /**
  * @test
- * @bug 4635230 6283345 6303830 6824440 6867348 7094155 8038184 8038349 8074784
+ * @bug 4635230 6283345 6303830 6824440 6867348 7094155 8038184 8038349
  * @summary Basic unit tests for generating XML Signatures with JSR 105
  * @compile -XDignore.symbol.file KeySelectors.java SignatureValidator.java
  *     X509KeySelector.java GenerationTests.java
@@ -31,23 +31,16 @@
  * @author Sean Mullan
  */
 
-import com.sun.net.httpserver.HttpExchange;
-import com.sun.net.httpserver.HttpHandler;
-import com.sun.net.httpserver.HttpServer;
 import java.io.*;
 import java.math.BigInteger;
-import java.net.InetSocketAddress;
 import java.security.Key;
 import java.security.KeyFactory;
-import java.security.KeyPair;
-import java.security.KeyPairGenerator;
 import java.security.KeyStore;
-import java.security.NoSuchAlgorithmException;
 import java.security.PrivateKey;
 import java.security.PublicKey;
-import java.security.SecureRandom;
 import java.security.cert.Certificate;
 import java.security.cert.CertificateFactory;
+import java.security.cert.X509Certificate;
 import java.security.cert.X509CRL;
 import java.security.spec.KeySpec;
 import java.security.spec.DSAPrivateKeySpec;
@@ -55,10 +48,10 @@
 import java.security.spec.RSAPrivateKeySpec;
 import java.security.spec.RSAPublicKeySpec;
 import java.util.*;
-import javax.crypto.KeyGenerator;
 import javax.crypto.SecretKey;
 import javax.xml.XMLConstants;
 import javax.xml.parsers.*;
+import org.w3c.dom.*;
 import javax.xml.crypto.Data;
 import javax.xml.crypto.KeySelector;
 import javax.xml.crypto.OctetStreamData;
@@ -76,7 +69,6 @@
 import javax.xml.transform.*;
 import javax.xml.transform.dom.DOMSource;
 import javax.xml.transform.stream.StreamResult;
-import org.w3c.dom.*;
 
 /**
  * Test that recreates merlin-xmldsig-twenty-three test vectors but with
@@ -118,73 +110,6 @@
     private final static String DSA_SHA256 =
         "http://www.w3.org/2009/xmldsig11#dsa-sha256";
 
-    private static final String BOGUS = "bogus";
-
-    private static final  String xslt = ""
-          + "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'\n"
-          + "            xmlns='http://www.w3.org/TR/xhtml1/strict' \n"
-          + "            exclude-result-prefixes='foo' \n"
-          + "            version='1.0'>\n"
-          + "  <xsl:output encoding='UTF-8' \n"
-          + "           indent='no' \n"
-          + "           method='xml' />\n"
-          + "  <xsl:template match='/'>\n"
-          + "    <html>\n"
-          + "   <head>\n"
-          + "    <title>Notaries</title>\n"
-          + "   </head>\n"
-          + "   <body>\n"
-          + "    <table>\n"
-          + "      <xsl:for-each select='Notaries/Notary'>\n"
-          + "           <tr>\n"
-          + "           <th>\n"
-          + "            <xsl:value-of select='@name' />\n"
-          + "           </th>\n"
-          + "           </tr>\n"
-          + "      </xsl:for-each>\n"
-          + "    </table>\n"
-          + "   </body>\n"
-          + "    </html>\n"
-          + "  </xsl:template>\n"
-          + "</xsl:stylesheet>\n";
-
-    private static final String[] canonicalizationMethods = new String[] {
-        CanonicalizationMethod.EXCLUSIVE,
-        CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
-        CanonicalizationMethod.INCLUSIVE,
-        CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS
-    };
-
-    private static final String[] xml_transforms = new String[] {
-        Transform.XSLT,
-        Transform.XPATH,
-        Transform.XPATH2,
-        CanonicalizationMethod.EXCLUSIVE,
-        CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS,
-        CanonicalizationMethod.INCLUSIVE,
-        CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
-    };
-
-    private static final String[] non_xml_transforms = new String[] {
-        null, Transform.BASE64
-    };
-
-    private static final String[] signatureMethods = new String[] {
-        SignatureMethod.DSA_SHA1,
-        SignatureMethod.RSA_SHA1,
-        SignatureMethod.HMAC_SHA1
-    };
-
-    private static enum Content {
-        Xml, Text, Base64, NotExisitng
-    }
-
-    private static enum KeyInfoType {
-        KeyValue, x509data, KeyName
-    }
-
-    private static boolean result = true;
-
     public static void main(String args[]) throws Exception {
         setup();
         test_create_signature_enveloped_dsa(1024);
@@ -215,97 +140,6 @@
         test_create_signature_reference_dependency();
         test_create_signature_with_attr_in_no_namespace();
         test_create_signature_with_empty_id();
-
-        // run tests for detached signatures with local http server
-        try (Http server = Http.startServer()) {
-            server.start();
-
-            // tests for XML documents
-            Arrays.stream(canonicalizationMethods).forEach(c ->
-                Arrays.stream(signatureMethods).forEach(s ->
-                    Arrays.stream(xml_transforms).forEach(t ->
-                        Arrays.stream(KeyInfoType.values()).forEach(k -> {
-                            test_create_detached_signature(c, s, t, k,
-                                    Content.Xml, server.getPort(), false, null);
-                        }))));
-
-            // tests for text data with no transform
-            Arrays.stream(canonicalizationMethods).forEach(c ->
-                Arrays.stream(signatureMethods).forEach(s ->
-                    Arrays.stream(KeyInfoType.values()).forEach(k -> {
-                        test_create_detached_signature(c, s, null, k,
-                                Content.Text, server.getPort(), false, null);
-                    })));
-
-            // tests for base64 data
-            Arrays.stream(canonicalizationMethods).forEach(c ->
-                Arrays.stream(signatureMethods).forEach(s ->
-                    Arrays.stream(non_xml_transforms).forEach(t ->
-                        Arrays.stream(KeyInfoType.values()).forEach(k -> {
-                            test_create_detached_signature(c, s, t, k,
-                                    Content.Base64, server.getPort(),
-                                    false, null);
-                        }))));
-
-            // negative tests
-
-            // unknown CanonicalizationMethod
-            test_create_detached_signature(
-                    CanonicalizationMethod.EXCLUSIVE + BOGUS,
-                    SignatureMethod.DSA_SHA1,
-                    CanonicalizationMethod.INCLUSIVE,
-                    KeyInfoType.KeyName,
-                    Content.Xml,
-                    server.getPort(),
-                    true,
-                    NoSuchAlgorithmException.class);
-
-            // unknown SignatureMethod
-            test_create_detached_signature(
-                    CanonicalizationMethod.EXCLUSIVE,
-                    SignatureMethod.DSA_SHA1 + BOGUS,
-                    CanonicalizationMethod.INCLUSIVE,
-                    KeyInfoType.KeyName, Content.Xml,
-                    server.getPort(),
-                    true,
-                    NoSuchAlgorithmException.class);
-
-            // unknown Transform
-            test_create_detached_signature(
-                    CanonicalizationMethod.EXCLUSIVE,
-                    SignatureMethod.DSA_SHA1,
-                    CanonicalizationMethod.INCLUSIVE + BOGUS,
-                    KeyInfoType.KeyName, Content.Xml,
-                    server.getPort(),
-                    true,
-                    NoSuchAlgorithmException.class);
-
-            // no source document
-            test_create_detached_signature(
-                    CanonicalizationMethod.EXCLUSIVE,
-                    SignatureMethod.DSA_SHA1,
-                    CanonicalizationMethod.INCLUSIVE,
-                    KeyInfoType.KeyName,
-                    Content.NotExisitng,
-                    server.getPort(),
-                    true,
-                    XMLSignatureException.class);
-
-            // wrong transform for text data
-            test_create_detached_signature(
-                    CanonicalizationMethod.EXCLUSIVE,
-                    SignatureMethod.DSA_SHA1,
-                    CanonicalizationMethod.INCLUSIVE,
-                    KeyInfoType.KeyName,
-                    Content.Text,
-                    server.getPort(),
-                    true,
-                    XMLSignatureException.class);
-        }
-
-        if (!result) {
-            throw new RuntimeException("At least one test case failed");
-        }
     }
 
     private static void setup() throws Exception {
@@ -882,6 +716,33 @@
 
         // Manifest Reference 3
         List<Transform> manTrans = new ArrayList<Transform>();
+        String xslt = ""
+          + "<xsl:stylesheet xmlns:xsl='http://www.w3.org/1999/XSL/Transform'\n"
+          + "            xmlns='http://www.w3.org/TR/xhtml1/strict' \n"
+          + "            exclude-result-prefixes='foo' \n"
+          + "            version='1.0'>\n"
+          + "  <xsl:output encoding='UTF-8' \n"
+          + "           indent='no' \n"
+          + "           method='xml' />\n"
+          + "  <xsl:template match='/'>\n"
+          + "    <html>\n"
+          + "   <head>\n"
+          + "    <title>Notaries</title>\n"
+          + "   </head>\n"
+          + "   <body>\n"
+          + "    <table>\n"
+          + "      <xsl:for-each select='Notaries/Notary'>\n"
+          + "           <tr>\n"
+          + "           <th>\n"
+          + "            <xsl:value-of select='@name' />\n"
+          + "           </th>\n"
+          + "           </tr>\n"
+          + "      </xsl:for-each>\n"
+          + "    </table>\n"
+          + "   </body>\n"
+          + "    </html>\n"
+          + "  </xsl:template>\n"
+          + "</xsl:stylesheet>\n";
         Document docxslt = db.parse(new ByteArrayInputStream(xslt.getBytes()));
         Node xslElem = docxslt.getDocumentElement();
 
@@ -1260,200 +1121,6 @@
         System.out.println();
     }
 
-    static void test_create_detached_signature(String canonicalizationMethod,
-            String signatureMethod, String transform, KeyInfoType keyInfo,
-            Content contentType, int port, boolean expectedFailure,
-            Class expectedException) {
-
-        final String digestMethod = DigestMethod.SHA1;
-        System.out.println("Test detached signature:");
-        System.out.println("    Canonicalization method: "
-                + canonicalizationMethod);
-        System.out.println("    Signature method: " + signatureMethod);
-        System.out.println("    Transform: " + transform);
-        System.out.println("    Digest method: " + digestMethod);
-        System.out.println("    KeyInfoType: " + keyInfo);
-        System.out.println("    Content type: " + contentType);
-        System.out.println("    Expected failure: "
-                + (expectedFailure ? "yes" : "no"));
-        System.out.println("    Expected exception: "
-                + (expectedException == null ?
-                        "no" : expectedException.getName()));
-
-        try {
-            boolean success = test_create_detached_signature(
-                    canonicalizationMethod,
-                    signatureMethod,
-                    digestMethod,
-                    transform,
-                    keyInfo,
-                    contentType,
-                    port);
-
-            if (success && expectedFailure) {
-                System.out.println("Signature validation unexpectedly passed");
-                result = false;
-            } else if (!success && !expectedFailure) {
-                System.out.println("Signature validation unexpectedly failed");
-                result = false;
-            } else if (expectedException != null) {
-                System.out.println("Expected " + expectedException
-                        + " not thrown");
-                result = false;
-            }
-        } catch (Exception e) {
-            if (expectedException == null
-                    || !e.getClass().isAssignableFrom(expectedException)) {
-                System.out.println("Unexpected exception: " + e);
-                e.printStackTrace(System.out);
-                result = false;
-            } else {
-                System.out.println("Expected exception: " + e);
-            }
-        }
-
-        System.out.println("Test case passed");
-    }
-
-    static boolean test_create_detached_signature(String canonicalizationMethod,
-            String signatureMethod, String digestMethod, String transform,
-            KeyInfoType keyInfo, Content contentType, int port)
-            throws Exception {
-
-        System.out.print("Sign ...");
-
-        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
-        dbf.setNamespaceAware(true);
-        dbf.setValidating(false);
-
-        // Create SignedInfo
-        DigestMethod dm = fac.newDigestMethod(digestMethod, null);
-
-        List transformList = null;
-        if (transform != null) {
-            TransformParameterSpec params = null;
-            switch (transform) {
-                case Transform.XPATH:
-                    params = new XPathFilterParameterSpec("//.");
-                    break;
-                case Transform.XPATH2:
-                    params = new XPathFilter2ParameterSpec(
-                            Collections.singletonList(new XPathType("//.",
-                                    XPathType.Filter.INTERSECT)));
-                    break;
-                case Transform.XSLT:
-                    Element element = dbf.newDocumentBuilder()
-                            .parse(new ByteArrayInputStream(xslt.getBytes()))
-                            .getDocumentElement();
-                    DOMStructure stylesheet = new DOMStructure(element);
-                    params = new XSLTTransformParameterSpec(stylesheet);
-                    break;
-            }
-            transformList = Collections.singletonList(fac.newTransform(
-                    transform, params));
-        }
-
-        String url = String.format("http://localhost:%d/%s", port, contentType);
-        List refs = Collections.singletonList(fac.newReference(url, dm,
-                transformList, null, null));
-
-        CanonicalizationMethod cm = fac.newCanonicalizationMethod(
-                canonicalizationMethod, (C14NMethodParameterSpec) null);
-
-        SignatureMethod sm = fac.newSignatureMethod(signatureMethod, null);
-
-        Key signingKey;
-        Key validationKey;
-        switch (signatureMethod) {
-            case SignatureMethod.DSA_SHA1:
-            case SignatureMethod.RSA_SHA1:
-                KeyPair kp = generateKeyPair(sm);
-                validationKey = kp.getPublic();
-                signingKey = kp.getPrivate();
-                break;
-            case SignatureMethod.HMAC_SHA1:
-                KeyGenerator kg = KeyGenerator.getInstance("HmacSHA1");
-                signingKey = kg.generateKey();
-                validationKey = signingKey;
-                break;
-            default:
-                throw new RuntimeException("Unsupported signature algorithm");
-        }
-
-        SignedInfo si = fac.newSignedInfo(cm, sm, refs, null);
-
-        // Create KeyInfo
-        KeyInfoFactory kif = fac.getKeyInfoFactory();
-        List list = null;
-        if (keyInfo == KeyInfoType.KeyValue) {
-            if (validationKey instanceof PublicKey) {
-                KeyValue kv = kif.newKeyValue((PublicKey) validationKey);
-                list = Collections.singletonList(kv);
-            }
-        } else if (keyInfo == KeyInfoType.x509data) {
-            list = Collections.singletonList(
-                    kif.newX509Data(Collections.singletonList("cn=Test")));
-        } else if (keyInfo == KeyInfoType.KeyName) {
-            list = Collections.singletonList(kif.newKeyName("Test"));
-        } else {
-            throw new RuntimeException("Unexpected KeyInfo: " + keyInfo);
-        }
-        KeyInfo ki = list != null ? kif.newKeyInfo(list) : null;
-
-        // Create an empty doc for detached signature
-        Document doc = dbf.newDocumentBuilder().newDocument();
-        DOMSignContext xsc = new DOMSignContext(signingKey, doc);
-
-        // Generate signature
-        XMLSignature signature = fac.newXMLSignature(si, ki);
-        signature.sign(xsc);
-
-        // Save signature
-        String signatureString;
-        try (StringWriter writer = new StringWriter()) {
-            TransformerFactory tf = TransformerFactory.newInstance();
-            Transformer trans = tf.newTransformer();
-            Node parent = xsc.getParent();
-            trans.transform(new DOMSource(parent), new StreamResult(writer));
-            signatureString = writer.toString();
-        }
-
-        System.out.print("Validate ... ");
-        try (ByteArrayInputStream bis = new ByteArrayInputStream(
-                signatureString.getBytes())) {
-            doc = dbf.newDocumentBuilder().parse(bis);
-        }
-
-        NodeList nodeLst = doc.getElementsByTagName("Signature");
-        Node node = nodeLst.item(0);
-        if (node == null) {
-            throw new RuntimeException("Couldn't find Signature element");
-        }
-        if (!(node instanceof Element)) {
-            throw new RuntimeException("Unexpected node type");
-        }
-        Element sig = (Element) node;
-
-        // Validate signature
-        DOMValidateContext vc = new DOMValidateContext(validationKey, sig);
-        vc.setProperty("org.jcp.xml.dsig.secureValidation", Boolean.FALSE);
-        signature = fac.unmarshalXMLSignature(vc);
-
-        boolean success = signature.validate(vc);
-        if (!success) {
-            System.out.println("Core signature validation failed");
-            return false;
-        }
-
-        success = signature.getSignatureValue().validate(vc);
-        if (!success) {
-            System.out.println("Cryptographic validation of signature failed");
-            return false;
-        }
-
-        return true;
-    }
-
     private static final String DSA_Y =
         "070662842167565771936588335128634396171789331656318483584455493822" +
         "400811200853331373030669235424928346190274044631949560438023934623" +
@@ -1564,25 +1231,6 @@
         };
     }
 
-    static KeyPair generateKeyPair(SignatureMethod sm)
-            throws NoSuchAlgorithmException {
-        KeyPairGenerator keygen;
-        switch (sm.getAlgorithm()) {
-            case SignatureMethod.DSA_SHA1:
-                keygen = KeyPairGenerator.getInstance("DSA");
-                break;
-            case SignatureMethod.RSA_SHA1:
-                keygen = KeyPairGenerator.getInstance("RSA");
-                break;
-            default:
-                throw new RuntimeException("Unsupported signature algorithm");
-        }
-
-        SecureRandom random = new SecureRandom();
-        keygen.initialize(1024, random);
-        return keygen.generateKeyPair();
-    }
-
     /**
      * This URIDereferencer returns locally cached copies of http content to
      * avoid test failures due to network glitches, etc.
@@ -1609,82 +1257,4 @@
             return defaultUd.dereference(ref, ctx);
         }
     }
-
-    // local http server
-    static class Http implements HttpHandler, AutoCloseable {
-
-        private final HttpServer server;
-
-        private Http(HttpServer server) {
-            this.server = server;
-        }
-
-        static Http startServer() throws IOException {
-            HttpServer server = HttpServer.create(new InetSocketAddress(0), 0);
-            return new Http(server);
-        }
-
-        void start() {
-            server.createContext("/", this);
-            server.start();
-        }
-
-        void stop() {
-            server.stop(0);
-        }
-
-        int getPort() {
-            return server.getAddress().getPort();
-        }
-
-        @Override
-        public void handle(HttpExchange t) throws IOException {
-            try {
-                String type;
-                String path = t.getRequestURI().getPath();
-                if (path.startsWith("/")) {
-                    type = path.substring(1);
-                } else {
-                    type = path;
-                }
-
-                String contentTypeHeader = "";
-                byte[] output = new byte[] {};
-                int code = 200;
-                Content testContentType = Content.valueOf(type);
-                switch (testContentType) {
-                    case Base64:
-                        contentTypeHeader = "application/octet-stream";
-                        output = "VGVzdA==".getBytes();
-                        break;
-                    case Text:
-                        contentTypeHeader = "text/plain";
-                        output = "Text".getBytes();
-                        break;
-                    case Xml:
-                        contentTypeHeader = "application/xml";
-                        output = "<tag>test</tag>".getBytes();
-                        break;
-                    case NotExisitng:
-                        code = 404;
-                        break;
-                    default:
-                        throw new IOException("Unknown test content type");
-                }
-
-                t.getResponseHeaders().set("Content-Type", contentTypeHeader);
-                t.sendResponseHeaders(code, output.length);
-                t.getResponseBody().write(output);
-            } catch (IOException e) {
-                System.out.println("Exception: " + e);
-                t.sendResponseHeaders(500, 0);
-            }
-            t.close();
-        }
-
-        @Override
-        public void close() {
-            stop();
-        }
-    }
 }
diff --git a/jdk/test/lib/testlibrary/jdk/testlibrary/JarUtils.java b/jdk/test/lib/testlibrary/jdk/testlibrary/JarUtils.java
index 327594d..13b07a5 100644
--- a/jdk/test/lib/testlibrary/jdk/testlibrary/JarUtils.java
+++ b/jdk/test/lib/testlibrary/jdk/testlibrary/JarUtils.java
@@ -25,7 +25,6 @@
 
 import java.io.File;
 import java.io.FileInputStream;
-import java.io.FileNotFoundException;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.nio.file.Path;
@@ -44,8 +43,7 @@
 
 
     /**
-     * Create jar file with specified files. If a specified file does not exist,
-     * a new jar entry will be created with the file name itself as the content.
+     * Create jar file with specified files from specified location.
      */
     public static void createJar(String dest, Path filesLocation,
                                  String... fileNames) throws IOException {
@@ -65,8 +63,6 @@
                 }
                 try (FileInputStream fis = new FileInputStream(file)) {
                     Utils.transferBetweenStreams(fis, jos);
-                } catch (FileNotFoundException e) {
-                    jos.write(fileName.getBytes());
                 }
             }
         }
@@ -82,17 +78,7 @@
     }
 
     /**
-     * Add or remove specified files to existing jar file. If a specified file
-     * to be updated or added does not exist, the jar entry will be created
-     * with the file name itself as the content.
-     *
-     * @param src the original jar file name
-     * @param dest the new jar file name
-     * @param files the files to update. The list is broken into 2 groups
-     *              by a "-" string. The files before in the 1st group will
-     *              be either updated or added. The files in the 2nd group
-     *              will be removed. If no "-" exists, all files belong to
-     *              the 1st group.
+     * Add specified files to existing jar file.
      */
     public static void updateJar(String src, String dest, String... files)
             throws IOException {
@@ -108,11 +94,8 @@
                     JarEntry entry = entries.nextElement();
                     String name = entry.getName();
                     boolean found = false;
-                    boolean update = true;
                     for (String file : files) {
-                        if (file.equals("-")) {
-                            update = false;
-                        } else if (name.equals(file)) {
+                        if (name.equals(file)) {
                             updatedFiles.add(file);
                             found = true;
                             break;
@@ -120,18 +103,11 @@
                     }
 
                     if (found) {
-                        if (update) {
                         System.out.println(String.format("Updating %s with %s",
                                 dest, name));
                         jos.putNextEntry(new JarEntry(name));
                         try (FileInputStream fis = new FileInputStream(name)) {
                             Utils.transferBetweenStreams(fis, jos);
-                            } catch (FileNotFoundException e) {
-                                jos.write(name.getBytes());
-                            }
-                        } else {
-                            System.out.println(String.format("Removing %s from %s",
-                                    name, dest));
                         }
                     } else {
                         System.out.println(String.format("Copying %s to %s",
@@ -145,17 +121,12 @@
 
             // append new files
             for (String file : files) {
-                if (file.equals("-")) {
-                    break;
-                }
                 if (!updatedFiles.contains(file)) {
                     System.out.println(String.format("Adding %s with %s",
                             dest, file));
                     jos.putNextEntry(new JarEntry(file));
                     try (FileInputStream fis = new FileInputStream(file)) {
                         Utils.transferBetweenStreams(fis, jos);
-                    } catch (FileNotFoundException e) {
-                        jos.write(file.getBytes());
                     }
                 }
             }
diff --git a/jdk/test/sun/misc/URLClassPath/ClassnameCharTest.java b/jdk/test/sun/misc/URLClassPath/ClassnameCharTest.java
index 6eec7cc..330ec32 100644
--- a/jdk/test/sun/misc/URLClassPath/ClassnameCharTest.java
+++ b/jdk/test/sun/misc/URLClassPath/ClassnameCharTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 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
@@ -102,60 +102,16 @@
 
     //--------------------- Infrastructure ---------------------------
     static volatile int passed = 0, failed = 0;
-
-    static boolean pass() {
-        passed++;
-        return true;
-    }
-
-    static boolean fail() {
-        failed++;
-        if (server != null) {
-            server.stop(0);
-        }
-        Thread.dumpStack();
-        return false;
-    }
-
-    static boolean fail(String msg) {
-        System.out.println(msg);
-        return fail();
-    }
-
-    static void unexpected(Throwable t) {
-        failed++;
-        if (server != null) {
-            server.stop(0);
-        }
-        t.printStackTrace();
-    }
-
-    static boolean check(boolean cond) {
-        if (cond) {
-            pass();
-        } else {
-            fail();
-        }
-        return cond;
-    }
-
+    static boolean pass() {passed++; return true;}
+    static boolean fail() {failed++; server.stop(0); Thread.dumpStack(); return false;}
+    static boolean fail(String msg) {System.out.println(msg); return fail();}
+    static void unexpected(Throwable t) {failed++; server.stop(0); t.printStackTrace();}
+    static boolean check(boolean cond) {if (cond) pass(); else fail(); return cond;}
     static boolean equal(Object x, Object y) {
-        if (x == null ? y == null : x.equals(y)) {
-            return pass();
-        } else {
-            return fail(x + " not equal to " + y);
-        }
-    }
-
+        if (x == null ? y == null : x.equals(y)) return pass();
+        else return fail(x + " not equal to " + y);}
     public static void main(String[] args) throws Throwable {
-        try {
-            realMain(args);
-        } catch (Throwable t) {
-            unexpected(t);
-        }
+        try {realMain(args);} catch (Throwable t) {unexpected(t);}
         System.out.println("\nPassed = " + passed + " failed = " + failed);
-        if (failed > 0) {
-            throw new AssertionError("Some tests failed");
-        }
-    }
+        if (failed > 0) throw new AssertionError("Some tests failed");}
 }
diff --git a/jdk/test/sun/net/www/protocol/http/HttpInputStream.java b/jdk/test/sun/net/www/protocol/http/HttpInputStream.java
index d9478ca..413f55a 100644
--- a/jdk/test/sun/net/www/protocol/http/HttpInputStream.java
+++ b/jdk/test/sun/net/www/protocol/http/HttpInputStream.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2003, Oracle and/or its affiliates. All rights reserved.
  * 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,95 +23,77 @@
 
 /* @test
  * @bug 4937598
- * @summary http://www.clipstream.com video does not play; read() problem
+ * @summary http://www.clipstream.com vedio does not play; read() problem
  */
+import java.util.*;
+import java.io.*;
+import java.net.*;
+import java.text.*;
+
+public class HttpInputStream implements Runnable {
+
+  ServerSocket serverSock;
+
+  public void run() {
+      try {
+          Socket s = serverSock.accept();
+          InputStream in = s.getInputStream();
+          byte b[] = new byte[4096];
+
+          // assume we read the entire http request
+          // (bad assumption but okay for test case)
+          int nread = in.read(b);
+
+          OutputStream o = s.getOutputStream();
+
+          o.write( "HTTP/1.1 200 OK".getBytes() );
+          o.write( "Content-Length: 20".getBytes() );
+          o.write( (byte)'\r' );
+          o.write( (byte)'\n' );
+          o.write( (byte)'\r' );
+          o.write( (byte)'\n' );
+
+          for (int i = 0; i < 20; i++) {
+              o.write((byte)0xff);
+          }
+
+          o.flush();
+          o.close();
+
+      } catch (Exception e) { }
+  }
 
 
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.URL;
+  public HttpInputStream() throws Exception {
 
-public class HttpInputStream {
+     serverSock = new ServerSocket(0);
+     int port = serverSock.getLocalPort();
 
-    private static final int CONTENT_LENGTH = 20;
+     Thread thr = new Thread(this);
+     thr.start();
 
-    static class Server implements AutoCloseable, Runnable {
+     Date date = new Date(new Date().getTime()-1440000); // this time yesterday
+     URL url;
+     HttpURLConnection con;
 
-        final ServerSocket serverSocket;
-        static final byte[] requestEnd = new byte[]{'\r', '\n', '\r', '\n'};
-        static final int TIMEOUT = 10 * 1000;
+     url = new URL("http://localhost:" + String.valueOf(port) +
+                   "/anything");
+     con = (HttpURLConnection)url.openConnection();
 
-        Server() throws IOException {
-            serverSocket = new ServerSocket(0);
-        }
+     int ret = con.getResponseCode();
+     byte[] b = new byte[20];
+     InputStream is = con.getInputStream();
+     int i = 0, count = 0;
+     while ((i = is.read()) != -1) {
+         System.out.println("i = "+i);
+         count++;
+     }
+     if (count != 20) {
+         throw new RuntimeException("HttpInputStream.read() failed with 0xff");
+     }
+  }
 
-        void readOneRequest(InputStream is) throws IOException {
-            int requestEndCount = 0, r;
-            while ((r = is.read()) != -1) {
-                if (r == requestEnd[requestEndCount]) {
-                    requestEndCount++;
-                    if (requestEndCount == 4) {
-                        break;
-                    }
-                } else {
-                    requestEndCount = 0;
-                }
-            }
-        }
-
-        @Override
-        public void run() {
-            try (Socket s = serverSocket.accept()) {
-                s.setSoTimeout(TIMEOUT);
-                readOneRequest(s.getInputStream());
-                try (OutputStream os =
-                             s.getOutputStream()) {
-                    os.write("HTTP/1.1 200 OK".getBytes());
-                    os.write(("Content-Length: " + CONTENT_LENGTH).getBytes());
-                    os.write("\r\n\r\n".getBytes());
-                    for (int i = 0; i < CONTENT_LENGTH; i++) {
-                        os.write(0xff);
-                    }
-                    os.flush();
-                }
-            } catch (IOException e) {
-                e.printStackTrace();
-            }
-        }
-
-        @Override
-        public void close() throws IOException {
-            if (!serverSocket.isClosed()) {
-                serverSocket.close();
-            }
-        }
-
-        public int getPort() {
-            return serverSocket.getLocalPort();
-        }
-    }
-
-
-    private static int read(InputStream is) throws IOException {
-        int len = 0;
-        while (is.read() != -1) {
-            len++;
-        }
-        return len;
-    }
-
-    public static void main(String args[]) throws IOException {
-        try (Server server = new Server()) {
-            (new Thread(server)).start();
-            URL url = new URL("http://localhost:" + server.getPort() + "/anything");
-            try (InputStream is = url.openConnection().getInputStream()) {
-                if (read(is) != CONTENT_LENGTH) {
-                    throw new RuntimeException("HttpInputStream.read() failed with 0xff");
-                }
-            }
-        }
-    }
+  public static void main(String args[]) throws Exception {
+      new HttpInputStream();
+  }
 }
diff --git a/jdk/test/sun/security/krb5/auto/Context.java b/jdk/test/sun/security/krb5/auto/Context.java
index f664605..715a1ad 100644
--- a/jdk/test/sun/security/krb5/auto/Context.java
+++ b/jdk/test/sun/security/krb5/auto/Context.java
@@ -23,7 +23,6 @@
 
 import com.sun.security.auth.module.Krb5LoginModule;
 import java.security.Key;
-import java.lang.reflect.InvocationTargetException;
 import java.security.PrivilegedActionException;
 import java.security.PrivilegedExceptionAction;
 import java.util.Arrays;
@@ -582,12 +581,7 @@
             out.name = name + " as " + out.cred.getName().toString();
             return out;
         } catch (PrivilegedActionException pae) {
-            Exception e = pae.getException();
-            if (e instanceof InvocationTargetException) {
-                throw (Exception)((InvocationTargetException) e).getTargetException();
-            } else {
-                throw e;
-            }
+            throw pae.getException();
         }
     }
 
diff --git a/jdk/test/sun/security/krb5/auto/KDC.java b/jdk/test/sun/security/krb5/auto/KDC.java
index b2f7d57..e3d63d0 100644
--- a/jdk/test/sun/security/krb5/auto/KDC.java
+++ b/jdk/test/sun/security/krb5/auto/KDC.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2008, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2008, 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
@@ -30,7 +30,6 @@
 import java.security.SecureRandom;
 import java.util.*;
 import java.util.concurrent.*;
-
 import sun.net.spi.nameservice.NameService;
 import sun.net.spi.nameservice.NameServiceDescriptor;
 import sun.security.krb5.*;
@@ -146,14 +145,9 @@
     private List<String> conf = new ArrayList<>();
 
     private Thread thread1, thread2, thread3;
-    private volatile boolean udpConsumerReady = false;
-    private volatile boolean tcpConsumerReady = false;
-    private volatile boolean dispatcherReady = false;
     DatagramSocket u1 = null;
     ServerSocket t1 = null;
 
-    public static enum KtabMode { APPEND, EXISTING };
-
     /**
      * Option names, to be expanded forever.
      */
@@ -200,10 +194,6 @@
          * Krb5.KDC_ERR_POLICY will be send for S4U2proxy request.
          */
         ALLOW_S4U2PROXY,
-        /**
-         * Sensitive accounts can never be delegated.
-         */
-        SENSITIVE_ACCOUNTS,
     };
 
     static {
@@ -648,7 +638,7 @@
         try {
             System.out.println(realm + "> " + tgsReq.reqBody.cname +
                     " sends TGS-REQ for " +
-                    service + ", " + tgsReq.reqBody.kdcOptions);
+                    service);
             KDCReqBody body = tgsReq.reqBody;
             int[] eTypes = KDCReqBodyDotEType(body);
             int e2 = eTypes[0];     // etype for outgoing session key
@@ -724,13 +714,7 @@
             boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1];
             if (body.kdcOptions.get(KDCOptions.FORWARDABLE)
                     && allowForwardable) {
-                List<String> sensitives = (List<String>)
-                        options.get(Option.SENSITIVE_ACCOUNTS);
-                if (sensitives != null && sensitives.contains(cname.toString())) {
-                    // Cannot make FORWARDABLE
-                } else {
-                    bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
-                }
+                bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
             }
             if (body.kdcOptions.get(KDCOptions.FORWARDED) ||
                     etp.flags.get(Krb5.TKT_OPTS_FORWARDED)) {
@@ -835,8 +819,7 @@
                     t,
                     edata);
             System.out.println("     Return " + tgsRep.cname
-                    + " ticket for " + tgsRep.ticket.sname + ", flags "
-                    + tFlags);
+                    + " ticket for " + tgsRep.ticket.sname);
 
             DerOutputStream out = new DerOutputStream();
             out.write(DerValue.createTag(DerValue.TAG_APPLICATION,
@@ -882,7 +865,7 @@
         try {
             System.out.println(realm + "> " + asReq.reqBody.cname +
                     " sends AS-REQ for " +
-                    service + ", " + asReq.reqBody.kdcOptions);
+                    service);
 
             KDCReqBody body = asReq.reqBody;
 
@@ -925,13 +908,7 @@
             //body.from
             boolean[] bFlags = new boolean[Krb5.TKT_OPTS_MAX+1];
             if (body.kdcOptions.get(KDCOptions.FORWARDABLE)) {
-                List<String> sensitives = (List<String>)
-                        options.get(Option.SENSITIVE_ACCOUNTS);
-                if (sensitives != null && sensitives.contains(body.cname.toString())) {
-                    // Cannot make FORWARDABLE
-                } else {
-                    bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
-                }
+                bFlags[Krb5.TKT_OPTS_FORWARDABLE] = true;
             }
             if (body.kdcOptions.get(KDCOptions.RENEWABLE)) {
                 bFlags[Krb5.TKT_OPTS_RENEWABLE] = true;
@@ -1107,8 +1084,7 @@
                     edata);
 
             System.out.println("     Return " + asRep.cname
-                    + " ticket for " + asRep.ticket.sname + ", flags "
-                    + tFlags);
+                    + " ticket for " + asRep.ticket.sname);
 
             DerOutputStream out = new DerOutputStream();
             out.write(DerValue.createTag(DerValue.TAG_APPLICATION,
@@ -1216,7 +1192,6 @@
         // The UDP consumer
         thread1 = new Thread() {
             public void run() {
-                udpConsumerReady = true;
                 while (true) {
                     try {
                         byte[] inbuf = new byte[8192];
@@ -1237,7 +1212,6 @@
         // The TCP consumer
         thread2 = new Thread() {
             public void run() {
-                tcpConsumerReady = true;
                 while (true) {
                     try {
                         Socket socket = tcp.accept();
@@ -1260,7 +1234,6 @@
         // The dispatcher
         thread3 = new Thread() {
             public void run() {
-                dispatcherReady = true;
                 while (true) {
                     try {
                         q.take().send();
@@ -1271,19 +1244,6 @@
         };
         thread3.setDaemon(true);
         thread3.start();
-
-        // wait for the KDC is ready
-        try {
-            while (!isReady()) {
-                Thread.sleep(100);
-            }
-        } catch(InterruptedException e) {
-            throw new IOException(e);
-        }
-    }
-
-    boolean isReady() {
-        return udpConsumerReady && tcpConsumerReady && dispatcherReady;
     }
 
     public void terminate() {
@@ -1297,72 +1257,6 @@
             // OK
         }
     }
-
-    public static KDC startKDC(final String host, final String krbConfFileName,
-            final String realm, final Map<String, String> principals,
-            final String ktab, final KtabMode mode) {
-
-        KDC kdc;
-        try {
-            kdc = KDC.create(realm, host, 0, true);
-            kdc.setOption(KDC.Option.PREAUTH_REQUIRED, Boolean.FALSE);
-            if (krbConfFileName != null) {
-                KDC.saveConfig(krbConfFileName, kdc);
-            }
-
-            // Add principals
-            if (principals != null) {
-                principals.forEach((name, password) -> {
-                    if (password == null || password.isEmpty()) {
-                        System.out.println(String.format(
-                                "KDC:add a principal '%s' with a random " +
-                                        "password", name));
-                        kdc.addPrincipalRandKey(name);
-                    } else {
-                        System.out.println(String.format(
-                                "KDC:add a principal '%s' with '%s' password",
-                                name, password));
-                        kdc.addPrincipal(name, password.toCharArray());
-                    }
-                });
-            }
-
-            // Create or append keys to existing keytab file
-            if (ktab != null) {
-                File ktabFile = new File(ktab);
-                switch(mode) {
-                    case APPEND:
-                        if (ktabFile.exists()) {
-                            System.out.println(String.format(
-                                    "KDC:append keys to an exising keytab "
-                                    + "file %s", ktab));
-                            kdc.appendKtab(ktab);
-                        } else {
-                            System.out.println(String.format(
-                                    "KDC:create a new keytab file %s", ktab));
-                            kdc.writeKtab(ktab);
-                        }
-                        break;
-                    case EXISTING:
-                        System.out.println(String.format(
-                                "KDC:use an existing keytab file %s", ktab));
-                        break;
-                    default:
-                        throw new RuntimeException(String.format(
-                                "KDC:unsupported keytab mode: %s", mode));
-                }
-            }
-
-            System.out.println(String.format(
-                    "KDC: started on %s:%s with '%s' realm",
-                    host, kdc.getPort(), realm));
-        } catch (Exception e) {
-            throw new RuntimeException("KDC: unexpected exception", e);
-        }
-
-        return kdc;
-    }
-
     /**
      * Helper class to encapsulate a job in a KDC.
      */
@@ -1410,20 +1304,13 @@
     }
 
     public static class KDCNameService implements NameServiceDescriptor {
-
-        public static String NOT_EXISTING_HOST = "not.existing.host";
-
         @Override
         public NameService createNameService() throws Exception {
             NameService ns = new NameService() {
                 @Override
                 public InetAddress[] lookupAllHostAddr(String host)
                         throws UnknownHostException {
-                    // Everything is localhost except NOT_EXISTING_HOST
-                    if (NOT_EXISTING_HOST.equals(host)) {
-                        throw new UnknownHostException("Unknown host name: "
-                                + NOT_EXISTING_HOST);
-                    }
+                    // Everything is localhost
                     return new InetAddress[]{
                         InetAddress.getByAddress(host, new byte[]{127,0,0,1})
                     };
diff --git a/jdk/test/sun/security/krb5/auto/MaxRetries.java b/jdk/test/sun/security/krb5/auto/MaxRetries.java
index 2de3817..880c023 100644
--- a/jdk/test/sun/security/krb5/auto/MaxRetries.java
+++ b/jdk/test/sun/security/krb5/auto/MaxRetries.java
@@ -29,94 +29,49 @@
  * @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();
+        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());
+        // An idle UDP socket to revent PortUnreachableException
+        DatagramSocket ds = new DatagramSocket(33333);
 
         System.setProperty("java.security.krb5.conf", "alternative-krb5.conf");
 
+        // For tryLast
         Security.setProperty("krb5.kdc.bad.policy", "trylast");
-
-        // We always make the real timeout to be 1 second
-        BadKdc.setRatio(0.25f);
         rewriteMaxRetries(4);
+        test1(4000, 6);         // 1 1 1 1 2 2
+        test1(4000, 2);         // 2 2
 
-        // 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)");
-        }
+        test1(1000, 3);         // 1 2 2
+        test1(1000, 2);         // 2 2
 
-        BadKdc.setRatio(0.2f);
         rewriteMaxRetries(-1);
-        test1("a5a5a5b5b5", "a5a5a5(b5){2,4}");
-        test1("b5b5", "(b5){2,4}");
+        test1(5000, 4);         // 1 1 2 2
+        test1(5000, 2);         // 2 2
 
-        BadKdc.setRatio(0.25f);
-        Security.setProperty("krb5.kdc.bad.policy",
-                "tryless:1,1000");
+        // For tryLess
+        Security.setProperty("krb5.kdc.bad.policy", "tryless:1," + BadKdc.toReal(5000));
         rewriteMaxRetries(4);
-        test1("a4a4a4a4b4a4b4", "a4a4a4a4(b4){1,3}a4(b4){1,3}");
-        test1("a4b4a4b4", "a4(b4){1,3}a4(b4){1,3}");
+        test1(4000, 7);         // 1 1 1 1 2 1 2
+        test1(4000, 4);         // 1 2 1 2
 
-        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)");
-        }
+        test1(1000, 4);         // 1 2 1 2
+        test1(1000, 4);         // 1 2 1 2
 
-        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);
+        test1(5000, 5);         // 1 1 2 1 2
+        test1(5000, 4);         // 1 2 1 2
 
         rewriteUdpPrefLimit(-1, -1);    // default, no limit
         test2("UDP");
@@ -135,52 +90,32 @@
 
     /**
      * 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
+     * @param timeout the expected timeout
+     * @param count the expected total try
      */
-    private static String test1(String exact, String relaxed) throws Exception {
+    private static void test1(int timeout, int count) throws Exception {
+        String timeoutTag = "timeout=" + BadKdc.toReal(timeout);
         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;
-        }
+        Context c = Context.fromJAAS("client");
         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();
+        System.out.println("----------------- TEST (" + timeout + "," +
+                count + ") -----------------");
         for (String line: lines) {
-            if (cm.match(line)) {
+            if (line.startsWith(">>> KDCCommunication")) {
                 System.out.println(line);
-                sb.append(cm.kdc()).append(cm.timeout());
+                if (line.indexOf(timeoutTag) < 0) {
+                    throw new Exception("Wrong timeout value" + timeoutTag);
+                }
+                count--;
             }
         }
-        if (failed) {
-            sb.append("x");
+        if (count != 0) {
+            throw new Exception("Retry count is " + count + " less");
         }
-        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;
     }
 
     /**
@@ -198,11 +133,11 @@
         String[] lines = new String(bo.toByteArray()).split("\n");
         System.out.println("----------------- TEST -----------------");
         for (String line: lines) {
-            if (cm.match(line)) {
+            if (line.startsWith(">>> KDCCommunication")) {
                 System.out.println(line);
                 count--;
-                if (!cm.protocol().equals(proto)) {
-                    throw new Exception("Wrong protocol value");
+                if (line.indexOf(proto) < 0) {
+                    throw new Exception("Wrong timeout value");
                 }
             }
         }
@@ -225,7 +160,6 @@
             }
             if (s.startsWith("[realms]")) {
                 // Reconfig global setting
-                fw.write("kdc_timeout = 5000\n");
                 if (global != -1) {
                     fw.write("udp_preference_limit = " + global + "\n");
                 }
@@ -244,8 +178,7 @@
 
     /**
      * Set max_retries and timeout value for realm. The global value is always
-     * 3 and 5000.
-     *
+     * 2 and 5000.
      * @param value max_retries and timeout/1000 for a realm, -1 means none.
      */
     private static void rewriteMaxRetries(int value) throws Exception {
@@ -258,7 +191,7 @@
             }
             if (s.startsWith("[realms]")) {
                 // Reconfig global setting
-                fw.write("max_retries = 3\n");
+                fw.write("max_retries = 2\n");
                 fw.write("kdc_timeout = " + BadKdc.toReal(5000) + "\n");
             } else if (s.trim().startsWith("kdc = ")) {
                 if (value != -1) {
@@ -267,7 +200,7 @@
                     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("    kdc = localhost:33333\n");
             }
             fw.write(s + "\n");
         }
diff --git a/jdk/test/sun/security/krb5/auto/OneKDC.java b/jdk/test/sun/security/krb5/auto/OneKDC.java
index 7526628..2d3fc54 100644
--- a/jdk/test/sun/security/krb5/auto/OneKDC.java
+++ b/jdk/test/sun/security/krb5/auto/OneKDC.java
@@ -95,7 +95,7 @@
      * entries with names using existing OneKDC principals.
      * @throws java.lang.Exception if anything goes wrong
      */
-    public OneKDC writeJAASConf() throws IOException {
+    public void writeJAASConf() throws IOException {
         System.setProperty("java.security.auth.login.config", JAAS_CONF);
         File f = new File(JAAS_CONF);
         FileOutputStream fos = new FileOutputStream(f);
@@ -123,7 +123,6 @@
                 "    isInitiator=false;\n};\n"
                 ).getBytes());
         fos.close();
-        return this;
     }
 
     /**
diff --git a/jdk/test/sun/security/krb5/canonicalize/Test.java b/jdk/test/sun/security/krb5/canonicalize/Test.java
index 3bd0bac..9340163 100644
--- a/jdk/test/sun/security/krb5/canonicalize/Test.java
+++ b/jdk/test/sun/security/krb5/canonicalize/Test.java
@@ -22,7 +22,7 @@
  */
 /*
  * @test
- * @bug 6682516 8149521
+ * @bug 6682516
  * @summary SPNEGO_HTTP_AUTH/WWW_KRB and SPNEGO_HTTP_AUTH/WWW_SPNEGO failed on all non-windows platforms
  * @run main/othervm -Dsun.net.spi.nameservice.provider.1=ns,mock -Djava.security.krb5.conf=krb5.conf Test
  */
@@ -43,11 +43,9 @@
         check("c1", "c1.this.domain");
         check("c1.this", "c1.this.domain");
         check("c1.this.domain", "c1.this.domain");
-        check("c1.this.domain.", "c1.this.domain");
 
         // canonicalized name goes IP, reject
         check("c2", "c2");
-        check("c2.", "c2");
 
         // canonicalized name goes strange, reject
         check("c3", "c3");
diff --git a/jdk/test/sun/security/mscapi/ShortRSAKeyWithinTLS.java b/jdk/test/sun/security/mscapi/ShortRSAKeyWithinTLS.java
index 4a66abb..f2a7525 100644
--- a/jdk/test/sun/security/mscapi/ShortRSAKeyWithinTLS.java
+++ b/jdk/test/sun/security/mscapi/ShortRSAKeyWithinTLS.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2012, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2012, 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
@@ -22,10 +22,7 @@
  */
 
 import java.io.*;
-import java.net.*;
-import java.util.*;
 import java.security.*;
-import java.security.cert.*;
 import javax.net.*;
 import javax.net.ssl.*;
 
@@ -74,34 +71,22 @@
     void doServerSide() throws Exception {
 
         // load the key store
-        serverKS = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
-        serverKS.load(null, null);
+        KeyStore ks = KeyStore.getInstance("Windows-MY", "SunMSCAPI");
+        ks.load(null, null);
         System.out.println("Loaded keystore: Windows-MY");
 
         // check key size
-        checkKeySize(serverKS);
+        checkKeySize(ks);
 
         // initialize the SSLContext
         KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
-        kmf.init(serverKS, null);
+        kmf.init(ks, null);
 
         TrustManagerFactory tmf = TrustManagerFactory.getInstance("SunX509");
-        tmf.init(serverKS);
-        TrustManager[] tms = tmf.getTrustManagers();
-        if (tms == null || tms.length == 0) {
-            throw new Exception("unexpected trust manager implementation");
-        } else {
-            if (!(tms[0] instanceof X509TrustManager)) {
-                throw new Exception("unexpected trust manager" +
-                        " implementation: " +
-                        tms[0].getClass().getCanonicalName());
-            }
-        }
-        serverTM = new MyExtendedX509TM((X509TrustManager)tms[0]);
-        tms = new TrustManager[] {serverTM};
+        tmf.init(ks);
 
         SSLContext ctx = SSLContext.getInstance("TLS");
-        ctx.init(kmf.getKeyManagers(), tms, null);
+        ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
 
         ServerSocketFactory ssf = ctx.getServerSocketFactory();
         SSLServerSocket sslServerSocket = (SSLServerSocket)
@@ -243,8 +228,6 @@
 
     Thread clientThread = null;
     Thread serverThread = null;
-    KeyStore serverKS;
-    MyExtendedX509TM serverTM;
 
     /*
      * Primary constructor, used to drive remainder of the test.
@@ -365,60 +348,5 @@
             }
         }
     }
-
-
-    class MyExtendedX509TM extends X509ExtendedTrustManager
-            implements X509TrustManager {
-
-        X509TrustManager tm;
-
-        MyExtendedX509TM(X509TrustManager tm) {
-            this.tm = tm;
-        }
-
-        public void checkClientTrusted(X509Certificate chain[], String authType)
-                throws CertificateException {
-            tm.checkClientTrusted(chain, authType);
-        }
-
-        public void checkServerTrusted(X509Certificate chain[], String authType)
-                throws CertificateException {
-            tm.checkServerTrusted(chain, authType);
-        }
-
-        public X509Certificate[] getAcceptedIssuers() {
-            List<X509Certificate> certs = new ArrayList<>();
-            try {
-                for (X509Certificate c : tm.getAcceptedIssuers()) {
-                    if (serverKS.getCertificateAlias(c).equals(keyAlias))
-                        certs.add(c);
-                }
-            } catch (KeyStoreException kse) {
-                throw new RuntimeException(kse);
-            }
-            return certs.toArray(new X509Certificate[certs.size()]);
-        }
-
-        public void checkClientTrusted(X509Certificate[] chain, String authType,
-                Socket socket) throws CertificateException {
-            tm.checkClientTrusted(chain, authType);
-        }
-
-        public void checkServerTrusted(X509Certificate[] chain, String authType,
-                Socket socket) throws CertificateException {
-            tm.checkServerTrusted(chain, authType);
-        }
-
-        public void checkClientTrusted(X509Certificate[] chain, String authType,
-            SSLEngine engine) throws CertificateException {
-            tm.checkClientTrusted(chain, authType);
-        }
-
-        public void checkServerTrusted(X509Certificate[] chain, String authType,
-            SSLEngine engine) throws CertificateException {
-            tm.checkServerTrusted(chain, authType);
-        }
-    }
-
 }
 
diff --git a/jdk/test/sun/security/pkcs11/PKCS11Test.java b/jdk/test/sun/security/pkcs11/PKCS11Test.java
index 9155c83..c8a147a 100644
--- a/jdk/test/sun/security/pkcs11/PKCS11Test.java
+++ b/jdk/test/sun/security/pkcs11/PKCS11Test.java
@@ -34,8 +34,6 @@
 
 public abstract class PKCS11Test {
 
-    static final String PKCS11 = "PKCS11";
-
     // directory of the test source
     static final String BASE = System.getProperty("test.src", ".");
 
@@ -570,14 +568,6 @@
         }
     }
 
-    static byte[] generateData(int length) {
-        byte data[] = new byte[length];
-        for (int i=0; i<data.length; i++) {
-            data[i] = (byte) (i % 256);
-        }
-        return data;
-    }
-
     <T> T[] concat(T[] a, T[] b) {
         if ((b == null) || (b.length == 0)) {
             return a;
diff --git a/jdk/test/sun/security/pkcs11/Secmod/AddPrivateKey.java b/jdk/test/sun/security/pkcs11/Secmod/AddPrivateKey.java
index 56833bd..c99c498 100644
--- a/jdk/test/sun/security/pkcs11/Secmod/AddPrivateKey.java
+++ b/jdk/test/sun/security/pkcs11/Secmod/AddPrivateKey.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2006, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2006, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -42,13 +42,6 @@
 // all providers.
 public class AddPrivateKey extends SecmodTest {
 
-    private static final String ALIAS1 = "entry1";
-    private static final String ALIAS2 = "entry2";
-    private static final String ALIAS3 = "entry3";
-    private static final int MAX_LINE = 85;
-    private static final int DATA_LENGTH = 4096;
-    private static final byte[] DATA = generateData(DATA_LENGTH);
-
     public static void main(String[] args) throws Exception {
         if (initSecmod() == false) {
             return;
@@ -63,7 +56,7 @@
         System.out.println();
         Security.addProvider(p);
 
-        KeyStore ks = KeyStore.getInstance(PKCS11, p);
+        KeyStore ks = KeyStore.getInstance("PKCS11", p);
         ks.load(null, password);
         for (String alias : aliases(ks)) {
             System.out.println("Deleting: " + alias);
@@ -71,28 +64,25 @@
         }
 
         KeyStore jks = KeyStore.getInstance("JKS");
-        try (InputStream in = new FileInputStream(BASE + SEP + "keystore.jks")) {
-            char[] jkspass = "passphrase".toCharArray();
-            jks.load(in, jkspass);
-            for (String alias : Collections.list(jks.aliases())) {
-                if (jks.entryInstanceOf(alias, PrivateKeyEntry.class)) {
-                    PrivateKeyEntry entry = (PrivateKeyEntry)jks.getEntry(alias,
-                            new PasswordProtection(jkspass));
-                    String algorithm = entry.getPrivateKey().getAlgorithm();
-                    System.out.printf("-Entry %s (%s)%n", alias, algorithm);
-                    if ((supportsEC == false) && algorithm.equals("EC")) {
-                        System.out.println("EC not supported by provider, "
-                                + "skipping");
-                        continue;
-                    }
-                    if ((supportsEC == false) && algorithm.equals("DSA")) {
-                        System.out.println("Provider does not appear to have "
-                                + "CKA_NETSCAPE_DB fix, skipping");
-                        continue;
-                    }
-                    test(p, entry);
-                } // else ignore
-            }
+        InputStream in = new FileInputStream(new File(BASE, "keystore.jks"));
+        char[] jkspass = "passphrase".toCharArray();
+        jks.load(in, jkspass);
+        List<PrivateKeyEntry> entries = new ArrayList<PrivateKeyEntry>();
+        for (String alias : Collections.list(jks.aliases())) {
+            if (jks.entryInstanceOf(alias, PrivateKeyEntry.class)) {
+                PrivateKeyEntry entry = (PrivateKeyEntry)jks.getEntry(alias, new PasswordProtection(jkspass));
+                String algorithm = entry.getPrivateKey().getAlgorithm();
+                System.out.println("-Entry " + alias + " (" + algorithm + ")");
+                if ((supportsEC == false) && algorithm.equals("EC")) {
+                    System.out.println("EC not supported by provider, skipping");
+                    continue;
+                }
+                if ((supportsEC == false) && algorithm.equals("DSA")) {
+                    System.out.println("Provider does not appear to have CKA_NETSCAPE_DB fix, skipping");
+                    continue;
+                }
+                test(p, entry);
+            } // else ignore
         }
         System.out.println("OK");
     }
@@ -101,6 +91,10 @@
         return Collections.list(ks.aliases());
     }
 
+    private final static String ALIAS1 = "entry1";
+    private final static String ALIAS2 = "entry2";
+    private final static String ALIAS3 = "entry3";
+
     private static void test(Provider p, PrivateKeyEntry entry) throws Exception {
         PrivateKey key = entry.getPrivateKey();
         X509Certificate[] chain = (X509Certificate[])entry.getCertificateChain();
@@ -127,8 +121,11 @@
 
         PrivateKey key2 = (PrivateKey)ks.getKey(ALIAS1, null);
         System.out.println(toString(key2));
-        X509Certificate[] chain2 =
-                (X509Certificate[]) ks.getCertificateChain(ALIAS1);
+        X509Certificate[] chain2 = (X509Certificate[])ks.getCertificateChain(ALIAS1);
+        // NSS makes token keys always sensitive, skip this check
+//      if (key.equals(key2) == false) {
+//          throw new Exception("key mismatch");
+//      }
         if (Arrays.equals(chain, chain2) == false) {
             throw new Exception("chain mismatch");
         }
@@ -156,8 +153,7 @@
 
         PrivateKey key4 = (PrivateKey)ks.getKey(ALIAS2, null);
         System.out.println(toString(key4));
-        X509Certificate[] chain4 = (X509Certificate[])
-                ks.getCertificateChain(ALIAS2);
+        X509Certificate[] chain4 = (X509Certificate[])ks.getCertificateChain(ALIAS2);
         if (Arrays.equals(chain, chain4) == false) {
             throw new Exception("chain mismatch");
         }
@@ -175,8 +171,7 @@
 
         PrivateKey key5 = (PrivateKey)ks.getKey(ALIAS3, null);
         System.out.println(toString(key5));
-        X509Certificate[] chain5 = (X509Certificate[])
-                ks.getCertificateChain(ALIAS3);
+        X509Certificate[] chain5 = (X509Certificate[])ks.getCertificateChain(ALIAS3);
         if (Arrays.equals(chain, chain5) == false) {
             throw new Exception("chain mismatch");
         }
@@ -190,22 +185,24 @@
         System.out.println("OK");
     }
 
-    private static void sign(Provider p, PrivateKey privateKey,
-            PublicKey publicKey) throws Exception {
+    private final static byte[] DATA = new byte[4096];
+
+    static {
+        Random random = new Random();
+        random.nextBytes(DATA);
+    }
+
+    private static void sign(Provider p, PrivateKey privateKey, PublicKey publicKey) throws Exception {
         String keyAlg = privateKey.getAlgorithm();
         String alg;
-        switch (keyAlg) {
-            case "RSA":
-                alg = "SHA1withRSA";
-                break;
-            case "DSA":
-                alg = "SHA1withDSA";
-                break;
-            case "EC":
-                alg = "SHA1withECDSA";
-                break;
-            default:
-                throw new Exception("Unknown algorithm " + keyAlg);
+        if (keyAlg.equals("RSA")) {
+            alg = "SHA1withRSA";
+        } else if (keyAlg.equals("DSA")) {
+            alg = "SHA1withDSA";
+        } else if (keyAlg.equals("EC")) {
+            alg = "SHA1withECDSA";
+        } else {
+            throw new Exception("Unknown algorithm " + keyAlg);
         }
         Signature s = Signature.getInstance(alg, p);
         s.initSign(privateKey);
@@ -219,6 +216,8 @@
         }
     }
 
+    private final static int MAX_LINE = 85;
+
     private static String toString(Object o) {
         String s = String.valueOf(o).split("\n")[0];
         return (s.length() <= MAX_LINE) ? s : s.substring(0, MAX_LINE);
diff --git a/jdk/test/sun/security/pkcs11/Secmod/AddTrustedCert.java b/jdk/test/sun/security/pkcs11/Secmod/AddTrustedCert.java
index 6b2b545..1b3ff81 100644
--- a/jdk/test/sun/security/pkcs11/Secmod/AddTrustedCert.java
+++ b/jdk/test/sun/security/pkcs11/Secmod/AddTrustedCert.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -44,47 +44,29 @@
             return;
         }
 
-        X509Certificate cert;
-        try (InputStream in = new FileInputStream(BASE + SEP + "anchor.cer")) {
-            CertificateFactory factory =
-                    CertificateFactory.getInstance("X.509");
-            cert = (X509Certificate)factory.generateCertificate(in);
-        }
+        InputStream in = new FileInputStream(BASE + SEP + "anchor.cer");
+        CertificateFactory factory = CertificateFactory.getInstance("X.509");
+        X509Certificate cert = (X509Certificate)factory.generateCertificate(in);
+        in.close();
+//      System.out.println(cert);
 
         String configName = BASE + SEP + "nss.cfg";
         Provider p = getSunPKCS11(configName);
 
         System.out.println(p);
         Security.addProvider(p);
-        KeyStore ks = KeyStore.getInstance(PKCS11, p);
+        KeyStore ks = KeyStore.getInstance("PKCS11", p);
         ks.load(null, password);
-        Collection<String> aliases = new TreeSet<>(Collections.list(
-                ks.aliases()));
+        Collection<String> aliases = new TreeSet<String>(Collections.list(ks.aliases()));
         System.out.println("entries: " + aliases.size());
         System.out.println(aliases);
         int size1 = aliases.size();
 
         String alias = "anchor";
-        if (ks.containsAlias(alias)) {
-            throw new Exception("Alias exists: " + alias);
-        }
-
         ks.setCertificateEntry(alias, cert);
-        KeyStore.Entry first = ks.getEntry(alias, null);
-        System.out.println("first entry = " + first);
-        if (!ks.entryInstanceOf(alias, TrustedCertificateEntry.class)) {
-            throw new Exception("Unexpected first entry type: " + first);
-        }
-
         ks.setCertificateEntry(alias, cert);
-        KeyStore.Entry second = ks.getEntry(alias, null);
-        System.out.println("second entry = " + second);
-        if (!ks.entryInstanceOf(alias, TrustedCertificateEntry.class)) {
-            throw new Exception("Unexpected second entry type: "
-                    + second);
-        }
 
-        aliases = new TreeSet<>(Collections.list(ks.aliases()));
+        aliases = new TreeSet<String>(Collections.list(ks.aliases()));
         System.out.println("entries: " + aliases.size());
         System.out.println(aliases);
         int size2 = aliases.size();
@@ -97,12 +79,8 @@
             throw new Exception("KeyStore returned incorrect certificate");
         }
 
-        ks.deleteEntry(alias);
-        if (ks.containsAlias(alias)) {
-            throw new Exception("Alias still exists: " + alias);
-        }
-
         System.out.println("OK");
+
     }
 
 }
diff --git a/jdk/test/sun/security/pkcs11/Secmod/Crypto.java b/jdk/test/sun/security/pkcs11/Secmod/Crypto.java
index 735149f..c44ab87 100644
--- a/jdk/test/sun/security/pkcs11/Secmod/Crypto.java
+++ b/jdk/test/sun/security/pkcs11/Secmod/Crypto.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -30,6 +30,8 @@
  * @run main/othervm Crypto
  */
 
+import java.util.*;
+
 import java.security.*;
 
 public class Crypto extends SecmodTest {
@@ -48,7 +50,9 @@
         System.out.println(kp.getPublic());
         System.out.println(kp.getPrivate());
 
-        byte[] data = generateData(2048);
+        SecureRandom random = new SecureRandom();
+        byte[] data = new byte[2048];
+        random.nextBytes(data);
 
         Signature sig = Signature.getInstance("SHA1withRSA", p);
         sig.initSign(kp.getPrivate());
diff --git a/jdk/test/sun/security/pkcs11/Secmod/GetPrivateKey.java b/jdk/test/sun/security/pkcs11/Secmod/GetPrivateKey.java
index beb07b6..a41bef9 100644
--- a/jdk/test/sun/security/pkcs11/Secmod/GetPrivateKey.java
+++ b/jdk/test/sun/security/pkcs11/Secmod/GetPrivateKey.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2005, 2015, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2005, 2011, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -48,17 +48,18 @@
 
         System.out.println(p);
         Security.addProvider(p);
-        KeyStore ks = KeyStore.getInstance(PKCS11, p);
+        KeyStore ks = KeyStore.getInstance("PKCS11", p);
         ks.load(null, password);
-        Collection<String> aliases = new TreeSet<>(
-                Collections.list(ks.aliases()));
+        Collection<String> aliases = new TreeSet<String>(Collections.list(ks.aliases()));
         System.out.println("entries: " + aliases.size());
         System.out.println(aliases);
 
         PrivateKey privateKey = (PrivateKey)ks.getKey(keyAlias, password);
         System.out.println(privateKey);
 
-        byte[] data = generateData(1024);
+        byte[] data = new byte[1024];
+        Random random = new Random();
+        random.nextBytes(data);
 
         System.out.println("Signing...");
         Signature signature = Signature.getInstance("MD5withRSA");
@@ -66,8 +67,7 @@
         signature.update(data);
         byte[] sig = signature.sign();
 
-        X509Certificate[] chain =
-                (X509Certificate[]) ks.getCertificateChain(keyAlias);
+        X509Certificate[] chain = (X509Certificate[])ks.getCertificateChain(keyAlias);
         signature.initVerify(chain[0].getPublicKey());
         signature.update(data);
         boolean ok = signature.verify(sig);
diff --git a/jdk/test/sun/security/provider/KeyStore/DKSTest.java b/jdk/test/sun/security/provider/KeyStore/DKSTest.java
index 39e4e18..a11210e 100644
--- a/jdk/test/sun/security/provider/KeyStore/DKSTest.java
+++ b/jdk/test/sun/security/provider/KeyStore/DKSTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved.
  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
  *
  * This code is free software; you can redistribute it and/or modify it
@@ -60,38 +60,8 @@
                 new KeyStore.PasswordProtection("passphrase".toCharArray()));
         }};
 
-    private static final Map<String, KeyStore.ProtectionParameter>
-        WRONG_PASSWORDS = new HashMap<String, KeyStore.ProtectionParameter>() {{
-            put("policy_keystore",
-                new KeyStore.PasswordProtection(
-                    "wrong".toCharArray()));
-            put("pw_keystore",
-                new KeyStore.PasswordProtection("wrong".toCharArray()));
-            put("eckeystore1",
-                new KeyStore.PasswordProtection("wrong".toCharArray()));
-            put("eckeystore2",
-                new KeyStore.PasswordProtection("wrong".toCharArray()));
-        }};
-
     public static void main(String[] args) throws Exception {
         /*
-         * domain keystore: keystores with wrong passwords
-         */
-        try {
-            URI config = new URI(CONFIG + "#keystores");
-            KeyStore ks = KeyStore.getInstance("DKS");
-            ks.load(new DomainLoadStoreParameter(config, WRONG_PASSWORDS));
-            throw new RuntimeException("Expected exception not thrown");
-        } catch (IOException e) {
-            System.out.println("Expected exception: " + e);
-            if (!causedBy(e, UnrecoverableKeyException.class)) {
-                e.printStackTrace(System.out);
-                throw new RuntimeException("Unexpected cause");
-            }
-            System.out.println("Expected cause: " + e);
-        }
-
-        /*
          * domain keystore: system
          */
         URI config = new URI(CONFIG + "#system");
@@ -212,15 +182,4 @@
             return factory.generateCertificate(certStream);
         }
     }
-
-    // checks if an exception was caused by specified exception class
-    private static boolean causedBy(Exception e, Class klass) {
-        Throwable cause = e;
-        while ((cause = cause.getCause()) != null) {
-            if (cause.getClass().equals(klass)) {
-                return true;
-            }
-        }
-        return false;
-    }
 }
diff --git a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLContextImpl/TrustTrustedCert.java b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLContextImpl/TrustTrustedCert.java
index b10431b..b812ba5 100644
--- a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLContextImpl/TrustTrustedCert.java
+++ b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLContextImpl/TrustTrustedCert.java
@@ -30,13 +30,12 @@
 
 /*
  * @test
- * @bug 7113275 8164846
+ * @bug 7113275
  * @summary compatibility issue with MD2 trust anchor and old X509TrustManager
- * @run main/othervm TrustTrustedCert PKIX TLSv1.1 true
- * @run main/othervm TrustTrustedCert PKIX TLSv1.1 false
- * @run main/othervm TrustTrustedCert SunX509 TLSv1.1 false
- * @run main/othervm TrustTrustedCert PKIX TLSv1.2 false
- * @run main/othervm TrustTrustedCert SunX509 TLSv1.2 false
+ * @run main/othervm TrustTrustedCert PKIX TLSv1.1
+ * @run main/othervm TrustTrustedCert SunX509 TLSv1.1
+ * @run main/othervm TrustTrustedCert PKIX TLSv1.2
+ * @run main/othervm TrustTrustedCert SunX509 TLSv1.2
  */
 
 import java.net.*;
@@ -182,32 +181,23 @@
             Thread.sleep(50);
         }
 
-        SSLSocket sslSocket = null;
-        try {
-            SSLContext context = generateSSLContext();
-            SSLSocketFactory sslsf = context.getSocketFactory();
+        SSLContext context = generateSSLContext();
+        SSLSocketFactory sslsf = context.getSocketFactory();
 
-            sslSocket = (SSLSocket)sslsf.createSocket("localhost", serverPort);
+        SSLSocket sslSocket =
+            (SSLSocket)sslsf.createSocket("localhost", serverPort);
 
-            // enable the specified TLS protocol
-            sslSocket.setEnabledProtocols(new String[] {tlsProtocol});
+        // enable the specified TLS protocol
+        sslSocket.setEnabledProtocols(new String[] {tlsProtocol});
 
-            InputStream sslIS = sslSocket.getInputStream();
-            OutputStream sslOS = sslSocket.getOutputStream();
-            sslOS.write('B');
-            sslOS.flush();
-            sslIS.read();
-        } catch (SSLHandshakeException e) {
-            // focus in on the CertPathValidatorException
-            Throwable t = e.getCause().getCause();
-            if ((t == null) || (expectFail &&
-                !t.toString().contains("MD5withRSA"))) {
-                throw new RuntimeException(
-                    "Expected to see MD5withRSA in exception output " + t);
-            }
-        } finally {
-            if (sslSocket != null) sslSocket.close();
-        }
+        InputStream sslIS = sslSocket.getInputStream();
+        OutputStream sslOS = sslSocket.getOutputStream();
+
+        sslOS.write('B');
+        sslOS.flush();
+        sslIS.read();
+
+        sslSocket.close();
     }
 
     /*
@@ -216,13 +206,10 @@
      */
     private static String tmAlgorithm;        // trust manager
     private static String tlsProtocol;        // trust manager
-    // set this flag to test context of CertificateException
-    private static boolean expectFail;
 
     private static void parseArguments(String[] args) {
         tmAlgorithm = args[0];
         tlsProtocol = args[1];
-        expectFail = Boolean.parseBoolean(args[2]);
     }
 
     private static SSLContext generateSSLContext() throws Exception {
@@ -245,7 +232,7 @@
 
         // generate the private key.
         PKCS8EncodedKeySpec priKeySpec = new PKCS8EncodedKeySpec(
-                            Base64.getMimeDecoder().decode(targetPrivateKey));
+                                Base64.getMimeDecoder().decode(targetPrivateKey));
         KeyFactory kf = KeyFactory.getInstance("RSA");
         RSAPrivateKey priKey =
                 (RSAPrivateKey)kf.generatePrivate(priKeySpec);
@@ -351,19 +338,9 @@
     volatile Exception clientException = null;
 
     public static void main(String[] args) throws Exception {
-        /*
-         * Get the customized arguments.
-         */
-        parseArguments(args);
-
-        /*
-         * MD5 is used in this test case, don't disable MD5 algorithm.
-         * if expectFail is set, we're testing exception message
-         */
-        if (!expectFail) {
-            Security.setProperty("jdk.certpath.disabledAlgorithms",
+        // MD5 is used in this test case, don't disable MD5 algorithm.
+        Security.setProperty("jdk.certpath.disabledAlgorithms",
                 "MD2, RSA keySize < 1024");
-        }
         Security.setProperty("jdk.tls.disabledAlgorithms",
                 "SSLv3, RC4, DH keySize < 768");
 
@@ -371,6 +348,11 @@
             System.setProperty("javax.net.debug", "all");
 
         /*
+         * Get the customized arguments.
+         */
+        parseArguments(args);
+
+        /*
          * Start the tests.
          */
         new TrustTrustedCert();
@@ -394,8 +376,7 @@
                 startServer(false);
             }
         } catch (Exception e) {
-            System.out.println("Unexpected exception: ");
-            e.printStackTrace();
+            // swallow for now.  Show later
         }
 
         /*
@@ -459,11 +440,7 @@
                          */
                         System.err.println("Server died...");
                         serverReady = true;
-                        if (!expectFail) {
-                            // only record if we weren't expecting.
-                            // client side will record exception
-                            serverException = e;
-                        }
+                        serverException = e;
                     }
                 }
             };
@@ -472,11 +449,7 @@
             try {
                 doServerSide();
             } catch (Exception e) {
-                // only record if we weren't expecting.
-                // client side will record exception
-                if (!expectFail) {
-                    serverException = e;
-                }
+                serverException = e;
             } finally {
                 serverReady = true;
             }
diff --git a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/CloseSocket.java b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/CloseSocket.java
index 12bfb4e..4c532be 100644
--- a/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/CloseSocket.java
+++ b/jdk/test/sun/security/ssl/com/sun/net/ssl/internal/ssl/SSLSocketImpl/CloseSocket.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2002, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved.
  * 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,96 +26,67 @@
  * @bug 4674913
  * @summary Verify that EOFException are correctly handled during the handshake
  * @author Andreas Sterbenz
- * @run main/othervm CloseSocket
  */
 
-import javax.net.SocketFactory;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.util.ArrayList;
+import java.io.*;
+import java.net.*;
+
+import javax.net.ssl.*;
 
 public class CloseSocket {
 
-    private static ArrayList<TestCase> testCases = new ArrayList<>();
-
-    static {
-        testCases.add(socket -> socket.startHandshake());
-        testCases.add(socket -> {
+    public static void main(String[] args) throws Exception {
+        final ServerSocket serverSocket = new ServerSocket(0);
+        int serverPort = serverSocket.getLocalPort();
+        new Thread() {
+            public void run() {
+                try {
+                    Socket s = serverSocket.accept();
+                    System.out.println("Server accepted connection");
+                    // wait a bit before closing the socket to give
+                    // the client time to send its hello message
+                    Thread.currentThread().sleep(100);
+                    s.close();
+                    System.out.println("Server closed socket, done.");
+                } catch (Exception e) {
+                    System.out.println("Server exception:");
+                    e.printStackTrace();
+                }
+            }
+        }.start();
+        SSLSocketFactory factory = (SSLSocketFactory)SSLSocketFactory.getDefault();
+        SSLSocket socket = (SSLSocket)factory.createSocket("localhost", serverPort);
+        System.out.println("Client established TCP connection");
+        boolean failed = false;
+        try {
+            System.out.println("Starting handshake...");
+            socket.startHandshake();
+            System.out.println("ERROR: no exception");
+            failed = true;
+        } catch (IOException e) {
+            System.out.println("Failed as expected: " + e);
+        }
+        try {
+            System.out.println("Trying read...");
             InputStream in = socket.getInputStream();
-            in.read();
-        });
-        testCases.add(socket -> {
+            int b = in.read();
+            System.out.println("ERROR: no exception, read: " + b);
+            failed = true;
+        } catch (IOException e) {
+            System.out.println("Failed as expected: " + e);
+        }
+        try {
+            System.out.println("Trying read...");
             OutputStream out = socket.getOutputStream();
             out.write(43);
-        });
-    }
-
-    public static void main(String[] args) throws Exception {
-        try (Server server = new Server()) {
-            new Thread(server).start();
-
-            SocketFactory factory = SSLSocketFactory.getDefault();
-            try (SSLSocket socket = (SSLSocket) factory.createSocket("localhost",
-                    server.getPort())) {
-                socket.setSoTimeout(2000);
-                System.out.println("Client established TCP connection");
-                boolean failed = false;
-                for (TestCase testCase : testCases) {
-                    try {
-                        testCase.test(socket);
-                        System.out.println("ERROR: no exception");
-                        failed = true;
-                    } catch (IOException e) {
-                        System.out.println("Failed as expected: " + e);
-                    }
-                }
-                if (failed) {
-                    throw new Exception("One or more tests failed");
-                }
-            }
+            System.out.println("ERROR: no exception");
+            failed = true;
+        } catch (IOException e) {
+            System.out.println("Failed as expected: " + e);
+        }
+        if (failed) {
+            throw new Exception("One or more tests failed");
         }
     }
 
-    static class Server implements AutoCloseable, Runnable {
-
-        final ServerSocket serverSocket;
-
-        Server() throws IOException {
-            serverSocket = new ServerSocket(0);
-        }
-
-        public int getPort() {
-            return serverSocket.getLocalPort();
-        }
-
-        @Override
-        public void run() {
-            try (Socket s = serverSocket.accept()) {
-                System.out.println("Server accepted connection");
-                // wait a bit before closing the socket to give
-                // the client time to send its hello message
-                Thread.currentThread().sleep(100);
-                s.close();
-                System.out.println("Server closed socket, done.");
-            } catch (Exception e) {
-                throw new RuntimeException("Problem in test execution", e);
-            }
-        }
-
-        @Override
-        public void close() throws Exception {
-            if (!serverSocket.isClosed()) {
-                serverSocket.close();
-            }
-        }
-    }
-
-    interface TestCase {
-        void test(SSLSocket socket) throws IOException;
-    }
 }
diff --git a/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java b/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java
index 6e51257..bc4d6ed 100644
--- a/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java
+++ b/jdk/test/sun/security/tools/jarsigner/TimestampCheck.java
@@ -22,31 +22,25 @@
  */
 
 import com.sun.net.httpserver.*;
+import java.io.BufferedReader;
 import java.io.ByteArrayOutputStream;
-import java.io.File;
 import java.io.FileInputStream;
 import java.io.IOException;
 import java.io.InputStream;
+import java.io.InputStreamReader;
 import java.io.OutputStream;
 import java.math.BigInteger;
 import java.net.InetSocketAddress;
-import java.nio.file.Files;
-import java.nio.file.Paths;
 import java.security.KeyStore;
 import java.security.PrivateKey;
 import java.security.Signature;
 import java.security.cert.Certificate;
 import java.security.cert.X509Certificate;
-import java.util.ArrayList;
-import java.util.Arrays;
 import java.util.Calendar;
-import java.util.List;
 import java.util.jar.JarEntry;
 import java.util.jar.JarFile;
 
 import sun.misc.IOUtils;
-import jdk.testlibrary.*;
-import jdk.testlibrary.JarUtils;
 import sun.security.pkcs.ContentInfo;
 import sun.security.pkcs.PKCS7;
 import sun.security.pkcs.PKCS9Attribute;
@@ -58,22 +52,11 @@
 import sun.security.x509.AlgorithmId;
 import sun.security.x509.X500Name;
 
-/*
- * @test
- * @bug 6543842 6543440 6939248 8009636 8024302 8163304
- * @summary checking response of timestamp
- * @modules java.base/sun.security.pkcs
- *          java.base/sun.security.timestamp
- *          java.base/sun.security.x509
- *          java.base/sun.security.util
- *          java.base/sun.security.tools.keytool
- * @library /lib/testlibrary
- * @run main/timeout=600 TimestampCheck
- */
 public class TimestampCheck {
+    static final String TSKS = "tsks";
+    static final String JAR = "old.jar";
 
-    static final String defaultPolicyId = "2.3.4";
-    static String host = null;
+    static final String defaultPolicyId = "2.3.4.5";
 
     static class Handler implements HttpHandler, AutoCloseable {
 
@@ -92,7 +75,11 @@
             t.getRequestBody().read(input);
 
             try {
-                String path = t.getRequestURI().getPath().substring(1);
+                int path = 0;
+                if (t.getRequestURI().getPath().length() > 1) {
+                    path = Integer.parseInt(
+                            t.getRequestURI().getPath().substring(1));
+                }
                 byte[] output = sign(input, path);
                 Headers out = t.getResponseHeaders();
                 out.set("Content-Type", "application/timestamp-reply");
@@ -110,9 +97,24 @@
         /**
          * @param input The data to sign
          * @param path different cases to simulate, impl on URL path
+         * 0: normal
+         * 1: Missing nonce
+         * 2: Different nonce
+         * 3: Bad digets octets in messageImprint
+         * 4: Different algorithmId in messageImprint
+         * 5: whole chain in cert set
+         * 6: extension is missing
+         * 7: extension is non-critical
+         * 8: extension does not have timestamping
+         * 9: no cert in response
+         * 10: normal
+         * 11: always return default policy id
+         * 12: normal
+         * otherwise: normal
          * @returns the signed
          */
-        byte[] sign(byte[] input, String path) throws Exception {
+        byte[] sign(byte[] input, int path) throws Exception {
+            // Read TSRequest
             DerValue value = new DerValue(input);
             System.err.println("\nIncoming Request\n===================");
             System.err.println("Version: " + value.data.getInteger());
@@ -136,35 +138,36 @@
                 }
             }
 
+            // Write TSResponse
             System.err.println("\nResponse\n===================");
-            FileInputStream is = new FileInputStream(keystore);
-            KeyStore ks = KeyStore.getInstance("JCEKS");
-            ks.load(is, "changeit".toCharArray());
-            is.close();
-
-            String alias = "ts";
-            if (path.startsWith("bad") || path.equals("weak")) {
-                alias = "ts" + path;
+            KeyStore ks = KeyStore.getInstance("JKS");
+            try (FileInputStream fis = new FileInputStream(keystore)) {
+                ks.load(fis, "changeit".toCharArray());
             }
 
-            if (path.equals("diffpolicy")) {
+            String alias = "ts";
+            if (path == 6) alias = "tsbad1";
+            if (path == 7) alias = "tsbad2";
+            if (path == 8) alias = "tsbad3";
+
+            if (path == 11) {
                 policyId = new ObjectIdentifier(defaultPolicyId);
             }
 
             DerOutputStream statusInfo = new DerOutputStream();
             statusInfo.putInteger(0);
 
+            DerOutputStream token = new DerOutputStream();
             AlgorithmId[] algorithms = {aid};
             Certificate[] chain = ks.getCertificateChain(alias);
-            X509Certificate[] signerCertificateChain;
+            X509Certificate[] signerCertificateChain = null;
             X509Certificate signer = (X509Certificate)chain[0];
-
-            if (path.equals("fullchain")) {   // Only case 5 uses full chain
+            if (path == 5) {   // Only case 5 uses full chain
                 signerCertificateChain = new X509Certificate[chain.length];
                 for (int i=0; i<chain.length; i++) {
                     signerCertificateChain[i] = (X509Certificate)chain[i];
                 }
-            } else if (path.equals("nocert")) {
+            } else if (path == 9) {
                 signerCertificateChain = new X509Certificate[0];
             } else {
                 signerCertificateChain = new X509Certificate[1];
@@ -176,11 +179,11 @@
             tst.putInteger(1);
             tst.putOID(policyId);
 
-            if (!path.equals("baddigest") && !path.equals("diffalg")) {
+            if (path != 3 && path != 4) {
                 tst.putDerValue(messageImprint);
             } else {
                 byte[] data = messageImprint.toByteArray();
-                if (path.equals("diffalg")) {
+                if (path == 4) {
                     data[6] = (byte)0x01;
                 } else {
                     data[data.length-1] = (byte)0x01;
@@ -195,10 +198,10 @@
             Calendar cal = Calendar.getInstance();
             tst.putGeneralizedTime(cal.getTime());
 
-            if (path.equals("diffnonce")) {
+            if (path == 2) {
                 tst.putInteger(1234);
-            } else if (path.equals("nononce")) {
-                // no noce
+            } else if (path == 1) {
+                // do nothing
             } else {
                 tst.putInteger(nonce);
             }
@@ -209,8 +212,6 @@
             DerOutputStream tstInfo2 = new DerOutputStream();
             tstInfo2.putOctetString(tstInfo.toByteArray());
 
-            // Always use the same algorithm at timestamp signing
-            // so it is different from the hash algorithm.
             Signature sig = Signature.getInstance("SHA1withRSA");
             sig.initSign((PrivateKey)(ks.getKey(
                     alias, "changeit".toCharArray())));
@@ -228,11 +229,12 @@
             SignerInfo signerInfo = new SignerInfo(
                     new X500Name(signer.getIssuerX500Principal().getName()),
                     signer.getSerialNumber(),
-                    AlgorithmId.get("SHA-1"), AlgorithmId.get("RSA"), sig.sign());
+                    aid, AlgorithmId.get("RSA"), sig.sign());
 
             SignerInfo[] signerInfos = {signerInfo};
-            PKCS7 p7 = new PKCS7(algorithms, contentInfo,
-                    signerCertificateChain, signerInfos);
+            PKCS7 p7 =
+                    new PKCS7(algorithms, contentInfo, signerCertificateChain,
+                    signerInfos);
             ByteArrayOutputStream p7out = new ByteArrayOutputStream();
             p7.encodeSignedData(p7out);
 
@@ -291,67 +293,42 @@
             stop();
         }
     }
-
-    public static void main(String[] args) throws Throwable {
-
-        prepare();
-
-        try (Handler tsa = Handler.init(0, "tsks");) {
+    public static void main(String[] args) throws Exception {
+        try (Handler tsa = Handler.init(0, TSKS);) {
             tsa.start();
             int port = tsa.getPort();
 
-            host = "http://localhost:" + port + "/";
+            String cmd;
+            // Use -J-Djava.security.egd=file:/dev/./urandom to speed up
+            // nonce generation in timestamping request. Not avaibale on
+            // Windows and defaults to thread seed generator, not too bad.
+            if (System.getProperty("java.home").endsWith("jre")) {
+                cmd = System.getProperty("java.home") + "/../bin/jarsigner";
+            } else {
+                cmd = System.getProperty("java.home") + "/bin/jarsigner";
+            }
+
+            cmd += " -J-Djava.security.egd=file:/dev/./urandom"
+                    + " -debug -keystore " + TSKS + " -storepass changeit"
+                    + " -tsa http://localhost:" + port + "/%d"
+                    + " -signedjar new_%d.jar " + JAR + " old";
 
             if (args.length == 0) {         // Run this test
-                sign("none")
-                        .shouldContain("is not timestamped")
-                        .shouldHaveExitValue(0);
-
-                sign("badku")
-                        .shouldHaveExitValue(0);
-                checkBadKU("badku.jar");
-
-                sign("normal")
-                        .shouldNotContain("is not timestamped")
-                        .shouldHaveExitValue(0);
-
-                sign("nononce")
-                        .shouldHaveExitValue(1);
-                sign("diffnonce")
-                        .shouldHaveExitValue(1);
-                sign("baddigest")
-                        .shouldHaveExitValue(1);
-                sign("diffalg")
-                        .shouldHaveExitValue(1);
-                sign("fullchain")
-                        .shouldHaveExitValue(0);   // Success, 6543440 solved.
-                sign("bad1")
-                        .shouldHaveExitValue(1);
-                sign("bad2")
-                        .shouldHaveExitValue(1);
-                sign("bad3")
-                        .shouldHaveExitValue(1);
-                sign("nocert")
-                        .shouldHaveExitValue(1);
-
-                sign("policy", "-tsapolicyid",  "1.2.3")
-                        .shouldHaveExitValue(0);
-                checkTimestamp("policy.jar", "1.2.3", "SHA-256");
-
-                sign("diffpolicy", "-tsapolicyid", "1.2.3")
-                        .shouldHaveExitValue(1);
-
-                sign("tsaalg", "-tsadigestalg", "SHA")
-                        .shouldHaveExitValue(0);
-                checkTimestamp("tsaalg.jar", defaultPolicyId, "SHA-1");
-
-                sign("weak", "-digestalg", "MD5",
-                                "-sigalg", "MD5withRSA", "-tsadigestalg", "MD5")
-                        .shouldHaveExitValue(0);
-                checkWeak("weak.jar");
-
-                // When .SF or .RSA is missing or invalid
-                checkMissingOrInvalidFiles("normal.jar");
+                jarsigner(cmd, 0, true);    // Success, normal call
+                jarsigner(cmd, 1, false);   // These 4 should fail
+                jarsigner(cmd, 2, false);
+                jarsigner(cmd, 3, false);
+                jarsigner(cmd, 4, false);
+                jarsigner(cmd, 5, true);    // Success, 6543440 solved.
+                jarsigner(cmd, 6, false);   // tsbad1
+                jarsigner(cmd, 7, false);   // tsbad2
+                jarsigner(cmd, 8, false);   // tsbad3
+                jarsigner(cmd, 9, false);   // no cert in timestamp
+                jarsigner(cmd + " -tsapolicyid 1.2.3.4", 10, true);
+                checkTimestamp("new_10.jar", "1.2.3.4", "SHA-256");
+                jarsigner(cmd + " -tsapolicyid 1.2.3.5", 11, false);
+                jarsigner(cmd + " -tsadigestalg SHA", 12, true);
+                checkTimestamp("new_12.jar", defaultPolicyId, "SHA-1");
             } else {                        // Run as a standalone server
                 System.err.println("Press Enter to quit server");
                 System.in.read();
@@ -359,101 +336,6 @@
         }
     }
 
-    private static void checkMissingOrInvalidFiles(String s)
-            throws Throwable {
-        JarUtils.updateJar(s, "1.jar", "-", "META-INF/OLD.SF");
-        verify("1.jar", "-verbose")
-                .shouldHaveExitValue(0)
-                .shouldContain("treated as unsigned")
-                .shouldContain("Missing signature-related file META-INF/OLD.SF");
-        JarUtils.updateJar(s, "2.jar", "-", "META-INF/OLD.RSA");
-        verify("2.jar", "-verbose")
-                .shouldHaveExitValue(0)
-                .shouldContain("treated as unsigned")
-                .shouldContain("Missing block file for signature-related file META-INF/OLD.SF");
-        JarUtils.updateJar(s, "3.jar", "META-INF/OLD.SF");
-        verify("3.jar", "-verbose")
-                .shouldHaveExitValue(0)
-                .shouldContain("treated as unsigned")
-                .shouldContain("Unparsable signature-related file META-INF/OLD.SF");
-        JarUtils.updateJar(s, "4.jar", "META-INF/OLD.RSA");
-        verify("4.jar", "-verbose")
-                .shouldHaveExitValue(0)
-                .shouldContain("treated as unsigned")
-                .shouldContain("Unparsable signature-related file META-INF/OLD.RSA");
-    }
-
-    static OutputAnalyzer jarsigner(List<String> extra)
-            throws Throwable {
-        JDKToolLauncher launcher = JDKToolLauncher.createUsingTestJDK("jarsigner")
-                .addVMArg("-Duser.language=en")
-                .addVMArg("-Duser.country=US")
-                .addToolArg("-keystore")
-                .addToolArg("tsks")
-                .addToolArg("-storepass")
-                .addToolArg("changeit");
-        for (String s : extra) {
-            if (s.startsWith("-J")) {
-                launcher.addVMArg(s.substring(2));
-            } else {
-                launcher.addToolArg(s);
-            }
-        }
-        System.err.println("COMMAND: ");
-        for (String cmd : launcher.getCommand()) {
-            System.err.print(cmd + " ");
-        }
-        System.err.println();
-        return ProcessTools.executeCommand(launcher.getCommand());
-    }
-
-    static OutputAnalyzer verify(String file, String... extra)
-            throws Throwable {
-        List<String> args = new ArrayList<>();
-        args.add("-verify");
-        args.add(file);
-        args.addAll(Arrays.asList(extra));
-        return jarsigner(args);
-    }
-
-    static void checkBadKU(String file) throws Throwable {
-        System.err.println("BadKU: " + file);
-        verify(file)
-                .shouldHaveExitValue(0)
-                .shouldContain("treated as unsigned")
-                .shouldContain("re-run jarsigner with debug enabled");
-        verify(file, "-verbose")
-                .shouldHaveExitValue(0)
-                .shouldContain("Signed by")
-                .shouldContain("treated as unsigned")
-                .shouldContain("re-run jarsigner with debug enabled");
-        verify(file, "-J-Djava.security.debug=jar")
-                .shouldHaveExitValue(0)
-                .shouldContain("SignatureException: Key usage restricted")
-                .shouldContain("treated as unsigned")
-                .shouldContain("re-run jarsigner with debug enabled");
-    }
-
-    static void checkWeak(String file) throws Throwable {
-        verify(file)
-                .shouldHaveExitValue(0)
-                .shouldContain("treated as unsigned")
-                .shouldMatch("weak algorithm that is now disabled.")
-                .shouldMatch("Re-run jarsigner with the -verbose option for more details");
-        verify(file, "-verbose")
-                .shouldHaveExitValue(0)
-                .shouldContain("treated as unsigned")
-                .shouldMatch("weak algorithm that is now disabled by")
-                .shouldMatch("Digest algorithm: .*weak")
-                .shouldMatch("Signature algorithm: .*weak")
-                .shouldMatch("Timestamp digest algorithm: .*weak")
-                .shouldNotMatch("Timestamp signature algorithm: .*weak.*weak")
-                .shouldMatch("Timestamp signature algorithm: .*key.*weak");
-        verify(file, "-J-Djava.security.debug=jar")
-                .shouldHaveExitValue(0)
-                .shouldMatch("SignatureException:.*Disabled");
-    }
-
     static void checkTimestamp(String file, String policyId, String digestAlg)
             throws Exception {
         try (JarFile jf = new JarFile(file)) {
@@ -480,65 +362,41 @@
         }
     }
 
-    static int which = 0;
-
     /**
-     * @param extra more args given to jarsigner
+     * @param cmd the command line (with a hole to plug in)
+     * @param path the path in the URL, i.e, http://localhost/path
+     * @param expected if this command should succeed
      */
-    static OutputAnalyzer sign(String path, String... extra)
-            throws Throwable {
-        which++;
-        System.err.println("\n>> Test #" + which + ": " + Arrays.toString(extra));
-        List<String> args = new ArrayList<>();
-        args.add("-J-Djava.security.egd=file:/dev/./urandom");
-        args.add("-debug");
-        args.add("-signedjar");
-        args.add(path + ".jar");
-        args.add("old.jar");
-        args.add(path.equals("badku") ? "badku" : "old");
-        if (!path.equals("none") && !path.equals("badku")) {
-            args.add("-tsa");
-            args.add(host + path);
-         }
-        args.addAll(Arrays.asList(extra));
-        return jarsigner(args);
-    }
-
-    static void prepare() throws Exception {
-        jdk.testlibrary.JarUtils.createJar("old.jar", "A");
-        Files.deleteIfExists(Paths.get("tsks"));
-        keytool("-alias ca -genkeypair -ext bc -dname CN=CA");
-        keytool("-alias old -genkeypair -dname CN=old");
-        keytool("-alias badku -genkeypair -dname CN=badku");
-        keytool("-alias ts -genkeypair -dname CN=ts");
-        keytool("-alias tsweak -genkeypair -keysize 512 -dname CN=tsbad1");
-        keytool("-alias tsbad1 -genkeypair -dname CN=tsbad1");
-        keytool("-alias tsbad2 -genkeypair -dname CN=tsbad2");
-        keytool("-alias tsbad3 -genkeypair -dname CN=tsbad3");
-
-        gencert("old");
-        gencert("badku", "-ext ku:critical=keyAgreement");
-        gencert("ts", "-ext eku:critical=ts");
-        gencert("tsweak", "-ext eku:critical=ts");
-        gencert("tsbad1");
-        gencert("tsbad2", "-ext eku=ts");
-        gencert("tsbad3", "-ext eku:critical=cs");
-    }
-
-    static void gencert(String alias, String... extra) throws Exception {
-        keytool("-alias " + alias + " -certreq -file " + alias + ".req");
-        String genCmd = "-gencert -alias ca -infile " +
-                alias + ".req -outfile " + alias + ".cert";
-        for (String s : extra) {
-            genCmd += " " + s;
+    static void jarsigner(String cmd, int path, boolean expected)
+            throws Exception {
+        System.err.println("Test " + path);
+        Process p = Runtime.getRuntime().exec(String.format(cmd, path, path));
+        BufferedReader reader = new BufferedReader(
+                new InputStreamReader(p.getErrorStream()));
+        while (true) {
+            String s = reader.readLine();
+            if (s == null) break;
+            System.err.println(s);
         }
-        keytool(genCmd);
-        keytool("-alias " + alias + " -importcert -file " + alias + ".cert");
-    }
 
-    static void keytool(String cmd) throws Exception {
-        cmd = "-keystore tsks -storepass changeit -keypass changeit " +
-                "-keyalg rsa -validity 200 " + cmd;
-        sun.security.tools.keytool.Main.main(cmd.split(" "));
+        // Will not see noTimestamp warning
+        boolean seeWarning = false;
+        reader = new BufferedReader(
+                new InputStreamReader(p.getInputStream()));
+        while (true) {
+            String s = reader.readLine();
+            if (s == null) break;
+            System.err.println(s);
+            if (s.indexOf("Warning:") >= 0) {
+                seeWarning = true;
+            }
+        }
+        int result = p.waitFor();
+        if (expected && result != 0 || !expected && result == 0) {
+            throw new Exception("Failed");
+        }
+        if (seeWarning) {
+            throw new Exception("See warning");
+        }
     }
 }
diff --git a/jdk/test/sun/security/tools/jarsigner/ts.sh b/jdk/test/sun/security/tools/jarsigner/ts.sh
new file mode 100644
index 0000000..6cee680
--- /dev/null
+++ b/jdk/test/sun/security/tools/jarsigner/ts.sh
@@ -0,0 +1,91 @@
+#
+# Copyright (c) 2007, 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.
+#
+
+# @test
+# @bug 6543842 6543440 6939248 8009636 8024302
+# @summary checking response of timestamp
+#
+# @run shell/timeout=600 ts.sh
+
+# Run for a long time because jarsigner with timestamp needs to create a
+# 64-bit random number and it might be extremely slow on a machine with
+# not enough entropy pool
+
+# set platform-dependent variables
+OS=`uname -s`
+case "$OS" in
+  Windows_* )
+    FS="\\"
+    ;;
+  * )
+    FS="/"
+    ;;
+esac
+
+if [ "${TESTSRC}" = "" ] ; then
+  TESTSRC="."
+fi
+if [ "${TESTJAVA}" = "" ] ; then
+  JAVAC_CMD=`which javac`
+  TESTJAVA=`dirname $JAVAC_CMD`/..
+fi
+
+JAR="${TESTJAVA}${FS}bin${FS}jar"
+JAVA="${TESTJAVA}${FS}bin${FS}java"
+JAVAC="${TESTJAVA}${FS}bin${FS}javac"
+KT="${TESTJAVA}${FS}bin${FS}keytool -keystore tsks -storepass changeit -keypass changeit -keyalg rsa -validity 200"
+
+rm tsks
+echo Nothing > A
+rm old.jar
+$JAR cvf old.jar A
+
+# ca is CA
+# old is signer for code
+# ts is signer for timestamp
+# tsbad1 has no extendedKeyUsage
+# tsbad2's extendedKeyUsage is non-critical
+# tsbad3's extendedKeyUsage has no timestamping
+
+$KT -alias ca -genkeypair -ext bc -dname CN=CA
+$KT -alias old -genkeypair -dname CN=old
+$KT -alias ts -genkeypair -dname CN=ts
+$KT -alias tsbad1 -genkeypair -dname CN=tsbad1
+$KT -alias tsbad2 -genkeypair -dname CN=tsbad2
+$KT -alias tsbad3 -genkeypair -dname CN=tsbad3
+$KT -alias ts -certreq | \
+        $KT -alias ca -gencert -ext eku:critical=ts | \
+        $KT -alias ts -importcert
+$KT -alias tsbad1 -certreq | \
+        $KT -alias ca -gencert | \
+        $KT -alias tsbad1 -importcert
+$KT -alias tsbad2 -certreq | \
+        $KT -alias ca -gencert -ext eku=ts | \
+        $KT -alias tsbad2 -importcert
+$KT -alias tsbad3 -certreq | \
+        $KT -alias ca -gencert -ext eku:critical=cs | \
+        $KT -alias tsbad3 -importcert
+
+$JAVAC -XDignore.symbol.file -d . ${TESTSRC}/TimestampCheck.java
+$JAVA ${TESTVMOPTS} TimestampCheck
+
diff --git a/jdk/test/sun/text/resources/LocaleData b/jdk/test/sun/text/resources/LocaleData
index df78c83..a80c129 100644
--- a/jdk/test/sun/text/resources/LocaleData
+++ b/jdk/test/sun/text/resources/LocaleData
@@ -8287,6 +8287,3 @@
 
 # bug #8075173
 FormatData/de/standalone.MonthAbbreviations/2=M\u00e4r
-
-# bug #8129361
-CurrencyNames//hrk=Kuna
diff --git a/jdk/test/sun/text/resources/LocaleDataTest.java b/jdk/test/sun/text/resources/LocaleDataTest.java
index c05f9e5..44f94e7 100644
--- a/jdk/test/sun/text/resources/LocaleDataTest.java
+++ b/jdk/test/sun/text/resources/LocaleDataTest.java
@@ -36,7 +36,7 @@
  *      6919624 6998391 7019267 7020960 7025837 7020583 7036905 7066203 7101495
  *      7003124 7085757 7028073 7171028 7189611 8000983 7195759 8004489 8006509
  *      7114053 7074882 7040556 8013836 8021121 6192407 6931564 8027695 7090826
- *      8017142 8037343 8055222 8042126 8074791 8075173 8080774 8129361
+ *      8017142 8037343 8055222 8042126 8074791 8075173 8080774
  * @summary Verify locale data
  *
  */
diff --git a/jdk/test/sun/tools/native2ascii/Native2AsciiTests.sh b/jdk/test/sun/tools/native2ascii/Native2AsciiTests.sh
index 5c886c2..f656bbc 100644
--- a/jdk/test/sun/tools/native2ascii/Native2AsciiTests.sh
+++ b/jdk/test/sun/tools/native2ascii/Native2AsciiTests.sh
@@ -24,7 +24,7 @@
 #
 
 # @test
-# @bug 4630463 4630971 4636448 4701617 4721296 4710890 6247817 7021987 8067964
+# @bug 4630463 4630971 4636448 4701617 4721296 4710890 6247817 7021987
 # @summary Tests miscellaneous native2ascii bugfixes and regressions
 
 
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/VERSION b/jdk/test/sun/util/calendar/zi/tzdata/VERSION
index f587cb7..6bf3661 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/VERSION
+++ b/jdk/test/sun/util/calendar/zi/tzdata/VERSION
@@ -21,4 +21,4 @@
 # or visit www.oracle.com if you need additional information or have any
 # questions.
 #
-tzdata2016g
+tzdata2016f
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/africa b/jdk/test/sun/util/calendar/zi/tzdata/africa
index cbde238..b523dc3 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/africa
+++ b/jdk/test/sun/util/calendar/zi/tzdata/africa
@@ -487,7 +487,7 @@
 # http://www.libyaherald.com/2013/10/24/correction-no-time-change-tomorrow/
 #
 # From Paul Eggert (2013-10-25):
-# For now, assume they're reverting to the pre-2012 rules of permanent UT +02.
+# For now, assume they're reverting to the pre-2012 rules of permanent UTC+2.
 
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Libya	1951	only	-	Oct	14	2:00	1:00	S
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/antarctica b/jdk/test/sun/util/calendar/zi/tzdata/antarctica
index f96947a..e12c764 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/antarctica
+++ b/jdk/test/sun/util/calendar/zi/tzdata/antarctica
@@ -33,7 +33,9 @@
 # http://www.spri.cam.ac.uk/bob/periant.htm
 # for information.
 # Unless otherwise specified, we have no time zone information.
-
+#
+# Except for the French entries,
+# I made up all time zone abbreviations mentioned here; corrections welcome!
 # FORMAT is '-00' and GMTOFF is 0 for locations while uninhabited.
 
 # Argentina - year-round bases
@@ -50,7 +52,7 @@
 #	previously sealers and scientific personnel wintered
 #	Margaret Turner reports
 #	http://web.archive.org/web/20021204222245/http://www.dstc.qut.edu.au/DST/marg/daylight.html
-#	(1999-09-30) that they're UT +05, with no DST;
+#	(1999-09-30) that they're UTC+5, with no DST;
 #	presumably this is when they have visitors.
 #
 # year-round bases
@@ -89,22 +91,23 @@
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Antarctica/Casey	0	-	-00	1969
-			8:00	-	+08	2009 Oct 18  2:00
-			11:00	-	+11	2010 Mar  5  2:00
-			8:00	-	+08	2011 Oct 28  2:00
-			11:00	-	+11	2012 Feb 21 17:00u
-			8:00	-	+08
+			8:00	-	AWST	2009 Oct 18  2:00
+						# Australian Western Std Time
+			11:00	-	CAST	2010 Mar  5  2:00  # Casey Time
+			8:00	-	AWST	2011 Oct 28  2:00
+			11:00	-	CAST	2012 Feb 21 17:00u
+			8:00	-	AWST
 Zone Antarctica/Davis	0	-	-00	1957 Jan 13
-			7:00	-	+07	1964 Nov
+			7:00	-	DAVT	1964 Nov    # Davis Time
 			0	-	-00	1969 Feb
-			7:00	-	+07	2009 Oct 18  2:00
-			5:00	-	+05	2010 Mar 10 20:00u
-			7:00	-	+07	2011 Oct 28  2:00
-			5:00	-	+05	2012 Feb 21 20:00u
-			7:00	-	+07
+			7:00	-	DAVT	2009 Oct 18  2:00
+			5:00	-	DAVT	2010 Mar 10 20:00u
+			7:00	-	DAVT	2011 Oct 28  2:00
+			5:00	-	DAVT	2012 Feb 21 20:00u
+			7:00	-	DAVT
 Zone Antarctica/Mawson	0	-	-00	1954 Feb 13
-			6:00	-	+06	2009 Oct 18  2:00
-			5:00	-	+05
+			6:00	-	MAWT	2009 Oct 18  2:00 # Mawson Time
+			5:00	-	MAWT
 # References:
 # Casey Weather (1998-02-26)
 # http://www.antdiv.gov.au/aad/exop/sfo/casey/casey_aws.html
@@ -158,7 +161,7 @@
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Indian/Kerguelen	0	-	-00	1950 # Port-aux-Français
-			5:00	-	+05
+			5:00	-	TFT	# ISO code TF Time
 #
 # year-round base in the main continent
 # Dumont d'Urville, Île des Pétrels, -6640+14001, since 1956-11
@@ -169,9 +172,9 @@
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Antarctica/DumontDUrville 0 -	-00	1947
-			10:00	-	+10	1952 Jan 14
+			10:00	-	PMT	1952 Jan 14 # Port-Martin Time
 			0	-	-00	1956 Nov
-			10:00	-	+10
+			10:00	-	DDUT	# Dumont-d'Urville Time
 
 # France & Italy - year-round base
 # Concordia, -750600+1232000, since 2005
@@ -197,7 +200,7 @@
 # station of Japan, it's appropriate for the principal location.
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Antarctica/Syowa	0	-	-00	1957 Jan 29
-			3:00	-	+03
+			3:00	-	SYOT	# Syowa Time
 # See:
 # NIPR Antarctic Research Activities (1999-08-17)
 # http://www.nipr.ac.jp/english/ara01.html
@@ -234,17 +237,17 @@
 # correct, but they should be quite close to the actual dates.
 #
 # From Paul Eggert (2014-03-21):
-# The CET-switching Troll rules require zic from tz 2014b or later, so as
+# The CET-switching Troll rules require zic from tzcode 2014b or later, so as
 # suggested by Bengt-Inge Larsson comment them out for now, and approximate
 # with only UTC and CEST.  Uncomment them when 2014b is more prevalent.
 #
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
-#Rule	Troll	2005	max	-	Mar	 1	1:00u	1:00	+01
-Rule	Troll	2005	max	-	Mar	lastSun	1:00u	2:00	+02
-#Rule	Troll	2005	max	-	Oct	lastSun	1:00u	1:00	+01
-#Rule	Troll	2004	max	-	Nov	 7	1:00u	0:00	+00
+#Rule	Troll	2005	max	-	Mar	 1	1:00u	1:00	CET
+Rule	Troll	2005	max	-	Mar	lastSun	1:00u	2:00	CEST
+#Rule	Troll	2005	max	-	Oct	lastSun	1:00u	1:00	CET
+#Rule	Troll	2004	max	-	Nov	 7	1:00u	0:00	UTC
 # Remove the following line when uncommenting the above '#Rule' lines.
-Rule	Troll	2004	max	-	Oct	lastSun	1:00u	0:00	+00
+Rule	Troll	2004	max	-	Oct	lastSun	1:00u	0:00	UTC
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Antarctica/Troll	0	-	-00	2005 Feb 12
 			0:00	Troll	%s
@@ -285,10 +288,10 @@
 # changes during the year and does not necessarily correspond to mean
 # solar noon.  So the Vostok time might have been whatever the clocks
 # happened to be during their visit.  So we still don't really know what time
-# it is at Vostok.  But we'll guess +06.
+# it is at Vostok.  But we'll guess UTC+6.
 #
 Zone Antarctica/Vostok	0	-	-00	1957 Dec 16
-			6:00	-	+06
+			6:00	-	VOST	# Vostok time
 
 # S Africa - year-round bases
 # Marion Island, -4653+03752
@@ -321,7 +324,7 @@
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone Antarctica/Rothera	0	-	-00	1976 Dec  1
-			-3:00	-	-03
+			-3:00	-	ROTT	# Rothera time
 
 # Uruguay - year round base
 # Artigas, King George Island, -621104-0585107
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/asia b/jdk/test/sun/util/calendar/zi/tzdata/asia
index 65e5f94..35ac37c 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/asia
+++ b/jdk/test/sun/util/calendar/zi/tzdata/asia
@@ -139,11 +139,13 @@
 # http://www.worldtimezone.com/dst_news/dst_news_armenia03.html
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Yerevan	2:58:00 -	LMT	1924 May  2
-			3:00	-	+03	1957 Mar
-			4:00 RussiaAsia +04/+05	1991 Mar 31  2:00s
-			3:00 RussiaAsia	+03/+04	1995 Sep 24  2:00s
-			4:00	-	+04	1997
-			4:00 RussiaAsia	+04/+05
+			3:00	-	YERT	1957 Mar    # Yerevan Time
+			4:00 RussiaAsia YER%sT	1991 Mar 31  2:00s
+			3:00	1:00	YERST	1991 Sep 23 # independence
+			3:00 RussiaAsia	AM%sT	1995 Sep 24  2:00s
+			4:00	-	AMT	1997
+			4:00 RussiaAsia	AM%sT	2012 Feb  9
+			4:00	-	AMT
 
 # Azerbaijan
 
@@ -164,12 +166,13 @@
 Rule	Azer	1997	2015	-	Oct	lastSun	 5:00	0	-
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Baku	3:19:24 -	LMT	1924 May  2
-			3:00	-	+03	1957 Mar
-			4:00 RussiaAsia +04/+05	1991 Mar 31  2:00s
-			3:00 RussiaAsia	+03/+04	1992 Sep lastSun  2:00s
-			4:00	-	+04	1996
-			4:00	EUAsia	+04/+05	1997
-			4:00	Azer	+04/+05
+			3:00	-	BAKT	1957 Mar    # Baku Time
+			4:00 RussiaAsia BAK%sT	1991 Mar 31  2:00s
+			3:00	1:00	BAKST	1991 Aug 30 # independence
+			3:00 RussiaAsia	AZ%sT	1992 Sep lastSun  2:00s
+			4:00	-	AZT	1996     # Azerbaijan Time
+			4:00	EUAsia	AZ%sT	1997
+			4:00	Azer	AZ%sT
 
 # Bahrain
 # See Asia/Qatar.
@@ -288,7 +291,7 @@
 # Milne says 6:24:40 was the meridian of the time ball observatory at Rangoon.
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
-Zone	Asia/Yangon	6:24:40 -	LMT	1880        # or Rangoon
+Zone	Asia/Rangoon	6:24:40 -	LMT	1880        # or Yangon
 			6:24:40	-	RMT	1920        # Rangoon Mean Time?
 			6:30	-	BURT	1942 May    # Burma Time
 			9:00	-	JST	1945 May  3
@@ -403,7 +406,7 @@
 # Lewiston (ME) Daily Sun (1939-05-29), p 17, said "Even the time is
 # different - the occupied districts going by Tokyo time, an hour
 # ahead of that prevailing in the rest of Shanghai."  Guess that the
-# Xujiahui Observatory was under French control and stuck with UT +08.
+# Xujiahui Observatory was under French control and stuck with UT+8.
 #
 # In earlier versions of this file, China had many separate Zone entries, but
 # this was based on what were apparently incorrect data in Shanks & Pottenger.
@@ -412,26 +415,26 @@
 # Proposed in 1918 and theoretically in effect until 1949 (although in practice
 # mainly observed in coastal areas), the five zones were:
 #
-# Changbai Time ("Long-white Time", Long-white = Heilongjiang area) UT +08:30
+# Changbai Time ("Long-white Time", Long-white = Heilongjiang area) UT+8.5
 # Asia/Harbin (currently a link to Asia/Shanghai)
 # Heilongjiang (except Mohe county), Jilin
 #
-# Zhongyuan Time ("Central plain Time") UT +08
+# Zhongyuan Time ("Central plain Time") UT+8
 # Asia/Shanghai
 # most of China
 # This currently represents most other zones as well,
 # as apparently these regions have been the same since 1970.
 # Milne gives 8:05:43.2 for Xujiahui Observatory time; round to nearest.
-# Guo says Shanghai switched to UT +08 "from the end of the 19th century".
+# Guo says Shanghai switched to UT+8 "from the end of the 19th century".
 #
-# Long-shu Time (probably due to Long and Shu being two names of the area) UT +07
+# Long-shu Time (probably due to Long and Shu being two names of that area) UT+7
 # Asia/Chongqing (currently a link to Asia/Shanghai)
 # Guangxi, Guizhou, Hainan, Ningxia, Sichuan, Shaanxi, and Yunnan;
 # most of Gansu; west Inner Mongolia; west Qinghai; and the Guangdong
 # counties Deqing, Enping, Kaiping, Luoding, Taishan, Xinxing,
 # Yangchun, Yangjiang, Yu'nan, and Yunfu.
 #
-# Xin-zang Time ("Xinjiang-Tibet Time") UT +06
+# Xin-zang Time ("Xinjiang-Tibet Time") UT+6
 # Asia/Urumqi
 # This currently represents Kunlun Time as well,
 # as apparently the two regions have been the same since 1970.
@@ -444,7 +447,7 @@
 # Shihezi, Changji, Yanqi, Heshuo, Tuokexun, Tulufan, Shanshan, Hami,
 # Fukang, Kuitun, Kumukuli, Miquan, Qitai, and Turfan.
 #
-# Kunlun Time UT +05:30
+# Kunlun Time UT+5.5
 # Asia/Kashgar (currently a link to Asia/Urumqi)
 # West Tibet, including Pulan, Aheqi, Shufu, Shule;
 # West Xinjiang, including Aksu, Atushi, Yining, Hetian, Cele, Luopu, Nileke,
@@ -460,7 +463,7 @@
 #
 # On the other hand, ethnic Uyghurs, who make up about half the
 # population of Xinjiang, typically use "Xinjiang time" which is two
-# hours behind Beijing time, or UT +06. The government of the Xinjiang
+# hours behind Beijing time, or UTC +0600. The government of the Xinjiang
 # Uyghur Autonomous Region, (XAUR, or just Xinjiang for short) as well as
 # local governments such as the Ürümqi city government use both times in
 # publications, referring to what is popularly called Xinjiang time as
@@ -516,8 +519,8 @@
 # having the same time as Beijing.
 
 # From Paul Eggert (2014-06-30):
-# In the early days of the PRC, Tibet was given its own time zone (UT +06)
-# but this was withdrawn in 1959 and never reinstated; see Tubten Khétsun,
+# In the early days of the PRC, Tibet was given its own time zone (UT+6) but
+# this was withdrawn in 1959 and never reinstated; see Tubten Khétsun,
 # Memories of life in Lhasa under Chinese Rule, Columbia U Press, ISBN
 # 978-0231142861 (2008), translator's introduction by Matthew Akester, p x.
 # As this is before our 1970 cutoff, Tibet doesn't need a separate zone.
@@ -531,12 +534,12 @@
 # Republics, the Soviet Union, the Kuomintang, and the People's Republic of
 # China, and tracking down all these organizations' timekeeping rules would be
 # quite a trick.  Approximate this lost history by a transition from LMT to
-# UT +06 at the start of 1928, the year of accession of the warlord Jin Shuren,
+# XJT at the start of 1928, the year of accession of the warlord Jin Shuren,
 # which happens to be the date given by Shanks & Pottenger (no doubt as a
-# guess) as the transition from LMT.  Ignore the usage of +08 before
-# 1986-02-01 under the theory that the transition date to +08 is unknown and
+# guess) as the transition from LMT.  Ignore the usage of UT+8 before
+# 1986-02-01 under the theory that the transition date to UT+8 is unknown and
 # that the sort of users who prefer Asia/Urumqi now typically ignored the
-# +08 mandate back then.
+# UT+8 mandate back then.
 
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 # Beijing time, used throughout China; represented by Shanghai.
@@ -741,7 +744,7 @@
 # be found from historical government announcement database.
 
 # From Paul Eggert (2014-07-03):
-# As per Yu-Cheng Chuang, say that Taiwan was at UT +09 from 1937-10-01
+# As per Yu-Cheng Chuang, say that Taiwan was at UT+9 from 1937-10-01
 # until 1945-09-21 at 01:00, overriding Shanks & Pottenger.
 # Likewise, use Yu-Cheng Chuang's data for DST in Taiwan.
 
@@ -855,15 +858,16 @@
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Tbilisi	2:59:11 -	LMT	1880
 			2:59:11	-	TBMT	1924 May  2 # Tbilisi Mean Time
-			3:00	-	+03	1957 Mar
-			4:00 RussiaAsia +04/+05	1991 Mar 31  2:00s
-			3:00 RussiaAsia +03/+04	1992
-			3:00 E-EurAsia	+03/+04	1994 Sep lastSun
-			4:00 E-EurAsia	+04/+05	1996 Oct lastSun
-			4:00	1:00	+05	1997 Mar lastSun
-			4:00 E-EurAsia	+04/+05	2004 Jun 27
-			3:00 RussiaAsia	+03/+04	2005 Mar lastSun  2:00
-			4:00	-	+04
+			3:00	-	TBIT	1957 Mar    # Tbilisi Time
+			4:00 RussiaAsia TBI%sT	1991 Mar 31  2:00s
+			3:00	1:00	TBIST	1991 Apr  9 # independence
+			3:00 RussiaAsia GE%sT	1992        # Georgia Time
+			3:00 E-EurAsia	GE%sT	1994 Sep lastSun
+			4:00 E-EurAsia	GE%sT	1996 Oct lastSun
+			4:00	1:00	GEST	1997 Mar lastSun
+			4:00 E-EurAsia	GE%sT	2004 Jun 27
+			3:00 RussiaAsia	GE%sT	2005 Mar lastSun  2:00
+			4:00	-	GET
 
 # East Timor
 
@@ -940,7 +944,7 @@
 # These would be the earliest possible times for a change.
 # Régimes horaires pour le monde entier, by Henri Le Corre, (Éditions
 # Traditionnelles, 1987, Paris) says that Java and Madura switched
-# from UT +09 to +07:30 on 1945-09-23, and gives 1944-09-01 for Jayapura
+# from JST to UTC+07:30 on 1945-09-23, and gives 1944-09-01 for Jayapura
 # (Hollandia).  For now, assume all Indonesian locations other than Jayapura
 # switched on 1945-09-23.
 #
@@ -951,11 +955,11 @@
 # summary published by the Time and Frequency Laboratory of the
 # Research Center for Calibration, Instrumentation and Metrology,
 # Indonesia, <http://time.kim.lipi.go.id/time-eng.php> (2006-09-29).
-# The time zone abbreviations and UT offsets are:
+# The abbreviations are:
 #
-# WIB  - +07 - Waktu Indonesia Barat (Indonesia western time)
-# WITA - +08 - Waktu Indonesia Tengah (Indonesia central time)
-# WIT  - +09 - Waktu Indonesia Timur (Indonesia eastern time)
+# WIB  - UTC+7 - Waktu Indonesia Barat (Indonesia western time)
+# WITA - UTC+8 - Waktu Indonesia Tengah (Indonesia central time)
+# WIT  - UTC+9 - Waktu Indonesia Timur (Indonesia eastern time)
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 # Java, Sumatra
@@ -1844,11 +1848,11 @@
 Rule	Kyrgyz	1997	2004	-	Oct	lastSun	2:30	0	-
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Bishkek	4:58:24 -	LMT	1924 May  2
-			5:00	-	+05	1930 Jun 21
-			6:00 RussiaAsia +06/+07	1991 Mar 31  2:00s
-			5:00 RussiaAsia	+05/+06	1991 Aug 31  2:00
-			5:00	Kyrgyz	+05/+06	2005 Aug 12
-			6:00	-	+06
+			5:00	-	FRUT	1930 Jun 21 # Frunze Time
+			6:00 RussiaAsia FRU%sT	1991 Mar 31  2:00s
+			5:00	1:00	FRUST	1991 Aug 31  2:00 # independence
+			5:00	Kyrgyz	KG%sT	2005 Aug 12 # Kyrgyzstan Time
+			6:00	-	KGT
 
 ###############################################################################
 
@@ -1887,24 +1891,25 @@
 Rule	ROK	1987	1988	-	May	Sun>=8	2:00	1:00	D
 Rule	ROK	1987	1988	-	Oct	Sun>=8	3:00	0	S
 
-# From Paul Eggert (2016-08-23):
+# From Paul Eggert (2014-10-30):
 # The Korean Wikipedia entry gives the following sources for UT offsets:
 #
-# 1908: Official Journal Article No. 3994 (decree No. 5)
+# 1908: Official Journal Article No. 3994 (Edict No. 5)
 # 1912: Governor-General of Korea Official Gazette Issue No. 367
 #       (Announcement No. 338)
 # 1954: Presidential Decree No. 876 (1954-03-17)
 # 1961: Law No. 676 (1961-08-07)
+# 1987: Law No. 3919 (1986-12-31)
 #
-# (Another source "1987: Law No. 3919 (1986-12-31)" was in the 2014-10-30
-# edition of the Korean Wikipedia entry.)
+# The Wikipedia entry also has confusing information about a change
+# to UT+9 in April 1910, but then what would be the point of the later change
+# to UT+9 on 1912-01-01?  Omit the 1910 change for now.
 #
 # I guessed that time zone abbreviations through 1945 followed the same
 # rules as discussed under Taiwan, with nominal switches from JST to KST
 # when the respective cities were taken over by the Allies after WWII.
 #
-# For Pyongyang, guess no changes from World War II until 2015, as we
-# have no information otherwise.
+# For Pyongyang we have no information; guess no changes since World War II.
 
 # From Steffen Thorsen (2015-08-07):
 # According to many news sources, North Korea is going to change to
@@ -2064,7 +2069,7 @@
 # Bill Bonnet (2005-05-19) reports that the US Embassy in Ulaanbaatar says
 # there is only one time zone and that DST is observed, citing Microsoft
 # Windows XP as the source.  Risto Nykänen (2005-05-16) reports that
-# travelmongolia.org says there are two time zones (UT +07, +08) with no DST.
+# travelmongolia.org says there are two time zones (UTC+7, UTC+8) with no DST.
 # Oscar van Vlijmen (2005-05-20) reports that the Mongolian Embassy in
 # Washington, DC says there are two time zones, with DST observed.
 # He also found
@@ -2700,7 +2705,7 @@
 # earlier date.
 #
 # Shanks & Pottenger also state that until 1968-05-01 Saudi Arabia had two
-# time zones; the other zone, at UT +04, was in the far eastern part of
+# time zones; the other zone, at UTC+4, was in the far eastern part of
 # the country.  Ignore this, as it's before our 1970 cutoff.
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
@@ -2969,10 +2974,10 @@
 # From Shanks & Pottenger.
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Dushanbe	4:35:12 -	LMT	1924 May  2
-			5:00	-	+05	1930 Jun 21
-			6:00 RussiaAsia +06/+07	1991 Mar 31  2:00s
-			5:00	1:00	+05/+06	1991 Sep  9  2:00s
-			5:00	-	+05
+			5:00	-	DUST	1930 Jun 21 # Dushanbe Time
+			6:00 RussiaAsia DUS%sT	1991 Mar 31  2:00s
+			5:00	1:00	DUSST	1991 Sep  9  2:00s
+			5:00	-	TJT	# Tajikistan Time
 
 # Thailand
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
@@ -2986,10 +2991,11 @@
 # From Shanks & Pottenger.
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Ashgabat	3:53:32 -	LMT	1924 May  2 # or Ashkhabad
-			4:00	-	+04	1930 Jun 21
-			5:00 RussiaAsia	+05/+06	1991 Mar 31  2:00
-			4:00 RussiaAsia	+04/+05	1992 Jan 19  2:00
-			5:00	-	+05
+			4:00	-	ASHT	1930 Jun 21 # Ashkhabad Time
+			5:00 RussiaAsia	ASH%sT	1991 Mar 31  2:00
+			4:00 RussiaAsia	ASH%sT	1991 Oct 27 # independence
+			4:00 RussiaAsia	TM%sT	1992 Jan 19  2:00
+			5:00	-	TMT
 
 # United Arab Emirates
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
@@ -3001,18 +3007,20 @@
 # Byalokoz 1919 says Uzbekistan was 4:27:53.
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Asia/Samarkand	4:27:53 -	LMT	1924 May  2
-			4:00	-	+04	1930 Jun 21
-			5:00	-	+05	1981 Apr  1
-			5:00	1:00	+06	1981 Oct  1
-			6:00	-	+06	1982 Apr  1
-			5:00 RussiaAsia	+05/+06	1992
-			5:00	-	+05
+			4:00	-	SAMT	1930 Jun 21 # Samarkand Time
+			5:00	-	SAMT	1981 Apr  1
+			5:00	1:00	SAMST	1981 Oct  1
+			6:00	-	TAST	1982 Apr  1 # Tashkent Time
+			5:00 RussiaAsia	SAM%sT	1991 Sep  1 # independence
+			5:00 RussiaAsia	UZ%sT	1992
+			5:00	-	UZT
 # Milne says Tashkent was 4:37:10.8; round to nearest.
 Zone	Asia/Tashkent	4:37:11 -	LMT	1924 May  2
-			5:00	-	+05	1930 Jun 21
-			6:00 RussiaAsia	+06/+07	1991 Mar 31  2:00
-			5:00 RussiaAsia	+05/+06	1992
-			5:00	-	+05
+			5:00	-	TAST	1930 Jun 21 # Tashkent Time
+			6:00 RussiaAsia	TAS%sT	1991 Mar 31  2:00
+			5:00 RussiaAsia	TAS%sT	1991 Sep  1 # independence
+			5:00 RussiaAsia	UZ%sT	1992
+			5:00	-	UZT
 
 # Vietnam
 
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/australasia b/jdk/test/sun/util/calendar/zi/tzdata/australasia
index 20a4020..134a01e 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/australasia
+++ b/jdk/test/sun/util/calendar/zi/tzdata/australasia
@@ -568,7 +568,7 @@
 # Base the Bougainville entry on the Arawa-Kieta region, which appears to have
 # the most people even though it was devastated in the Bougainville Civil War.
 #
-# Although Shanks gives 1942-03-15 / 1943-11-01 for UT +09, these dates
+# Although Shanks gives 1942-03-15 / 1943-11-01 for JST, these dates
 # are apparently rough guesswork from the starts of military campaigns.
 # The World War II entries below are instead based on Arawa-Kieta.
 # The Japanese occupied Kieta in July 1942,
@@ -576,8 +576,8 @@
 # http://pwencycl.kgbudge.com/B/o/Bougainville.htm
 # and seem to have controlled it until their 1945-08-21 surrender.
 #
-# The Autonomous Region of Bougainville switched from UT +10 to +11
-# on 2014-12-28 at 02:00.  They call +11 "Bougainville Standard Time";
+# The Autonomous Region of Bougainville plans to switch from UTC+10 to UTC+11
+# on 2014-12-28 at 02:00.  They call UTC+11 "Bougainville Standard Time";
 # abbreviate this as BST.  See:
 # http://www.bougainville24.com/bougainville-issues/bougainville-gets-own-timezone/
 #
@@ -643,7 +643,7 @@
 # From Paul Eggert (2014-06-27):
 # The International Date Line Act 2011
 # http://www.parliament.gov.ws/images/ACTS/International_Date_Line_Act__2011_-_Eng.pdf
-# changed Samoa from UT -11 to +13, effective "12 o'clock midnight, on
+# changed Samoa from UTC-11 to UTC+13, effective "12 o'clock midnight, on
 # Thursday 29th December 2011".  The International Date Line was adjusted
 # accordingly.
 
@@ -738,7 +738,7 @@
 # 1886-1891; Baker was similar but exact dates are not known.
 # Inhabited by civilians 1935-1942; U.S. military bases 1943-1944;
 # uninhabited thereafter.
-# Howland observed Hawaii Standard Time (UT -10:30) in 1937;
+# Howland observed Hawaii Standard Time (UT-10:30) in 1937;
 # see page 206 of Elgen M. Long and Marie K. Long,
 # Amelia Earhart: the Mystery Solved, Simon & Schuster (2000).
 # So most likely Howland and Baker observed Hawaii Time from 1935
@@ -1496,7 +1496,7 @@
 # Zealand time.  I understand that is the time they keep locally, anyhow."
 # For now, assume this practice goes back to the introduction of standard time
 # in New Zealand, as this would make Chatham Islands time almost exactly match
-# LMT back when New Zealand was at UT +11:30; also, assume Chatham Islands did
+# LMT back when New Zealand was at UTC+11:30; also, assume Chatham Islands did
 # not observe New Zealand's prewar DST.
 
 ###############################################################################
@@ -1552,7 +1552,7 @@
 # For now, we assume the Ladrones switched at the same time as the Philippines;
 # see Asia/Manila.
 
-# US Public Law 106-564 (2000-12-23) made UT +10 the official standard time,
+# US Public Law 106-564 (2000-12-23) made UTC+10 the official standard time,
 # under the name "Chamorro Standard Time".  There is no official abbreviation,
 # but Congressman Robert A. Underwood, author of the bill that became law,
 # wrote in a press release (2000-12-27) that he will seek the use of "ChST".
@@ -1564,15 +1564,15 @@
 # "I am certain, having lived there for the past decade, that 'Truk'
 # (now properly known as Chuuk) ... is in the time zone GMT+10."
 #
-# Shanks & Pottenger write that Truk switched from UT +10 to +11
+# Shanks & Pottenger write that Truk switched from UTC+10 to UTC+11
 # on 1978-10-01; ignore this for now.
 
 # From Paul Eggert (1999-10-29):
 # The Federated States of Micronesia Visitors Board writes in
 # The Federated States of Micronesia - Visitor Information (1999-01-26)
 # http://www.fsmgov.org/info/clocks.html
-# that Truk and Yap are UT +10, and Ponape and Kosrae are +11.
-# We don't know when Kosrae switched from +12; assume January 1 for now.
+# that Truk and Yap are UTC+10, and Ponape and Kosrae are UTC+11.
+# We don't know when Kosrae switched from UTC+12; assume January 1 for now.
 
 
 # Midway
@@ -1638,11 +1638,11 @@
 # ordaining - by a masterpiece of diplomatic flattery - that
 # the Fourth of July should be celebrated twice in that year."
 
-# Although Shanks & Pottenger says they both switched to UT -11:30
-# in 1911, and to -11 in 1950. many earlier sources give -11
+# Although Shanks & Pottenger says they both switched to UTC-11:30
+# in 1911, and to UTC-11 in 1950. many earlier sources give UTC-11
 # for American Samoa, e.g., the US National Bureau of Standards
 # circular "Standard Time Throughout the World", 1932.
-# Assume American Samoa switched to -11 in 1911, not 1950,
+# Assume American Samoa switched to UTC-11 in 1911, not 1950,
 # and that after 1950 they agreed until (western) Samoa skipped a
 # day in 2011.  Assume also that the Samoas follow the US and New
 # Zealand's "ST"/"DT" style of daylight-saving abbreviations.
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/backward b/jdk/test/sun/util/calendar/zi/tzdata/backward
index ec96c7e..8352705 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/backward
+++ b/jdk/test/sun/util/calendar/zi/tzdata/backward
@@ -59,7 +59,6 @@
 Link	Asia/Urumqi		Asia/Kashgar
 Link	Asia/Kathmandu		Asia/Katmandu
 Link	Asia/Macau		Asia/Macao
-Link	Asia/Yangon		Asia/Rangoon
 Link	Asia/Ho_Chi_Minh	Asia/Saigon
 Link	Asia/Jerusalem		Asia/Tel_Aviv
 Link	Asia/Thimphu		Asia/Thimbu
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/etcetera b/jdk/test/sun/util/calendar/zi/tzdata/etcetera
index ec31f1b..d2fb91c 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/etcetera
+++ b/jdk/test/sun/util/calendar/zi/tzdata/etcetera
@@ -31,13 +31,6 @@
 # need now for the entries that are not on UTC are for ships at sea
 # that cannot use POSIX TZ settings.
 
-# Starting with POSIX 1003.1-2001, the entries below are all
-# unnecessary as settings for the TZ environment variable.  E.g.,
-# instead of TZ='Etc/GMT+4' one can use the POSIX setting TZ='<-04>+4'.
-#
-# Do not use a POSIX TZ setting like TZ='GMT+4', which is four hours
-# behind GMT but uses the completely misleading abbreviation "GMT".
-
 Zone	Etc/GMT		0	-	GMT
 Zone	Etc/UTC		0	-	UTC
 Zone	Etc/UCT		0	-	UCT
@@ -56,13 +49,23 @@
 Link	Etc/GMT				Etc/GMT+0
 Link	Etc/GMT				Etc/GMT0
 
-# Be consistent with POSIX TZ settings in the Zone names,
+# We use POSIX-style signs in the Zone names and the output abbreviations,
 # even though this is the opposite of what many people expect.
 # POSIX has positive signs west of Greenwich, but many people expect
 # positive signs east of Greenwich.  For example, TZ='Etc/GMT+4' uses
-# the abbreviation "-04" and corresponds to 4 hours behind UT
+# the abbreviation "GMT+4" and corresponds to 4 hours behind UT
 # (i.e. west of Greenwich) even though many people would expect it to
 # mean 4 hours ahead of UT (i.e. east of Greenwich).
+#
+# In the draft 5 of POSIX 1003.1-200x, the angle bracket notation allows for
+# TZ='<GMT-4>+4'; if you want time zone abbreviations conforming to
+# ISO 8601 you can use TZ='<-0400>+4'.  Thus the commonly-expected
+# offset is kept within the angle bracket (and is used for display)
+# while the POSIX sign is kept outside the angle bracket (and is used
+# for calculation).
+#
+# Do not use a TZ setting like TZ='GMT+4', which is four hours behind
+# GMT but uses the completely misleading abbreviation "GMT".
 
 # Earlier incarnations of this package were not POSIX-compliant,
 # and had lines such as
@@ -71,31 +74,30 @@
 # way does a
 #		zic -l GMT-12
 # so we moved the names into the Etc subdirectory.
-# Also, the time zone abbreviations are now compatible with %z.
 
-Zone	Etc/GMT-14	14	-	+14
-Zone	Etc/GMT-13	13	-	+13
-Zone	Etc/GMT-12	12	-	+12
-Zone	Etc/GMT-11	11	-	+11
-Zone	Etc/GMT-10	10	-	+10
-Zone	Etc/GMT-9	9	-	+09
-Zone	Etc/GMT-8	8	-	+08
-Zone	Etc/GMT-7	7	-	+07
-Zone	Etc/GMT-6	6	-	+06
-Zone	Etc/GMT-5	5	-	+05
-Zone	Etc/GMT-4	4	-	+04
-Zone	Etc/GMT-3	3	-	+03
-Zone	Etc/GMT-2	2	-	+02
-Zone	Etc/GMT-1	1	-	+01
-Zone	Etc/GMT+1	-1	-	-01
-Zone	Etc/GMT+2	-2	-	-02
-Zone	Etc/GMT+3	-3	-	-03
-Zone	Etc/GMT+4	-4	-	-04
-Zone	Etc/GMT+5	-5	-	-05
-Zone	Etc/GMT+6	-6	-	-06
-Zone	Etc/GMT+7	-7	-	-07
-Zone	Etc/GMT+8	-8	-	-08
-Zone	Etc/GMT+9	-9	-	-09
-Zone	Etc/GMT+10	-10	-	-10
-Zone	Etc/GMT+11	-11	-	-11
-Zone	Etc/GMT+12	-12	-	-12
+Zone	Etc/GMT-14	14	-	GMT-14	# 14 hours ahead of GMT
+Zone	Etc/GMT-13	13	-	GMT-13
+Zone	Etc/GMT-12	12	-	GMT-12
+Zone	Etc/GMT-11	11	-	GMT-11
+Zone	Etc/GMT-10	10	-	GMT-10
+Zone	Etc/GMT-9	9	-	GMT-9
+Zone	Etc/GMT-8	8	-	GMT-8
+Zone	Etc/GMT-7	7	-	GMT-7
+Zone	Etc/GMT-6	6	-	GMT-6
+Zone	Etc/GMT-5	5	-	GMT-5
+Zone	Etc/GMT-4	4	-	GMT-4
+Zone	Etc/GMT-3	3	-	GMT-3
+Zone	Etc/GMT-2	2	-	GMT-2
+Zone	Etc/GMT-1	1	-	GMT-1
+Zone	Etc/GMT+1	-1	-	GMT+1
+Zone	Etc/GMT+2	-2	-	GMT+2
+Zone	Etc/GMT+3	-3	-	GMT+3
+Zone	Etc/GMT+4	-4	-	GMT+4
+Zone	Etc/GMT+5	-5	-	GMT+5
+Zone	Etc/GMT+6	-6	-	GMT+6
+Zone	Etc/GMT+7	-7	-	GMT+7
+Zone	Etc/GMT+8	-8	-	GMT+8
+Zone	Etc/GMT+9	-9	-	GMT+9
+Zone	Etc/GMT+10	-10	-	GMT+10
+Zone	Etc/GMT+11	-11	-	GMT+11
+Zone	Etc/GMT+12	-12	-	GMT+12
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/europe b/jdk/test/sun/util/calendar/zi/tzdata/europe
index aededb1..8ed7d4b 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/europe
+++ b/jdk/test/sun/util/calendar/zi/tzdata/europe
@@ -98,7 +98,8 @@
 #        1:00       CET CEST CEMT Central Europe
 #        1:00:14    SET           Swedish (1879-1899)*
 #        2:00       EET EEST      Eastern Europe
-#        3:00       MSK MSD       Moscow
+#        3:00       FET           Further-eastern Europe (2011-2014)*
+#        3:00       MSK MSD  MSM* Minsk, Moscow
 
 # From Peter Ilieve (1994-12-04),
 # The original six [EU members]: Belgium, France, (West) Germany, Italy,
@@ -605,33 +606,16 @@
 Rule	E-Eur	1981	max	-	Mar	lastSun	 0:00	1:00	S
 Rule	E-Eur	1996	max	-	Oct	lastSun	 0:00	0	-
 
-
-# Daylight saving time for Russia and the Soviet Union
-#
-# The 1917-1921 decree URLs are from Alexander Belopolsky (2016-08-23).
-
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Russia	1917	only	-	Jul	 1	23:00	1:00	MST  # Moscow Summer Time
-#
-# Decree No. 142 (1917-12-22) http://istmat.info/node/28137
 Rule	Russia	1917	only	-	Dec	28	 0:00	0	MMT  # Moscow Mean Time
-#
-# Decree No. 497 (1918-05-30) http://istmat.info/node/30001
 Rule	Russia	1918	only	-	May	31	22:00	2:00	MDST # Moscow Double Summer Time
 Rule	Russia	1918	only	-	Sep	16	 1:00	1:00	MST
-#
-# Decree No. 258 (1919-05-29) http://istmat.info/node/37949
 Rule	Russia	1919	only	-	May	31	23:00	2:00	MDST
-#
-Rule	Russia	1919	only	-	Jul	 1	 0:00u	1:00	MSD
+Rule	Russia	1919	only	-	Jul	 1	 2:00	1:00	MSD
 Rule	Russia	1919	only	-	Aug	16	 0:00	0	MSK
-#
-# Decree No. 63 (1921-02-03) http://istmat.info/node/45840
 Rule	Russia	1921	only	-	Feb	14	23:00	1:00	MSD
-#
-# Decree No. 121 (1921-03-07) http://istmat.info/node/45949
-Rule	Russia	1921	only	-	Mar	20	23:00	2:00	+05
-#
+Rule	Russia	1921	only	-	Mar	20	23:00	2:00	MSM  # Midsummer
 Rule	Russia	1921	only	-	Sep	 1	 0:00	1:00	MSD
 Rule	Russia	1921	only	-	Oct	 1	 0:00	0	-
 # Act No. 925 of the Council of Ministers of the USSR (1980-10-24):
@@ -814,6 +798,8 @@
 # From Alexander Bokovoy (2014-10-09):
 # Belarussian government decided against changing to winter time....
 # http://eng.belta.by/all_news/society/Belarus-decides-against-adjusting-time-in-Russias-wake_i_76335.html
+# From Paul Eggert (2014-10-08):
+# Hence Belarus can share time zone abbreviations with Moscow again.
 #
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
 Zone	Europe/Minsk	1:50:16 -	LMT	1880
@@ -824,7 +810,8 @@
 			3:00	Russia	MSK/MSD	1990
 			3:00	-	MSK	1991 Mar 31  2:00s
 			2:00	Russia	EE%sT	2011 Mar 27  2:00s
-			3:00	-	+03
+			3:00	-	FET	2014 Oct 26  1:00s
+			3:00	-	MSK
 
 # Belgium
 #
@@ -1332,7 +1319,7 @@
 # http://www.parlament-berlin.de/pds-fraktion.nsf/727459127c8b66ee8525662300459099/defc77cb784f180ac1256c2b0030274b/$FILE/bersarint.pdf
 # says that Bersarin issued an order to use Moscow time on May 20.
 # However, Moscow did not observe daylight saving in 1945, so
-# this was equivalent to UT +03, not +04.
+# this was equivalent to CEMT (GMT+3), not GMT+4.
 
 
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
@@ -2296,6 +2283,7 @@
 # http://www.worldtimezone.com/dst_news/dst_news_russia-map-2014-07.html
 
 # From Paul Eggert (2006-03-22):
+# Except for Moscow after 1919-07-01, I invented the time zone abbreviations.
 # Moscow time zone abbreviations after 1919-07-01, and Moscow rules after 1991,
 # are from Andrey A. Chernov.  The rest is from Shanks & Pottenger,
 # except we follow Chernov's report that 1992 DST transitions were Sat
@@ -2371,7 +2359,7 @@
 			 2:00	Poland	CE%sT	1946
 			 3:00	Russia	MSK/MSD	1989 Mar 26  2:00s
 			 2:00	Russia	EE%sT	2011 Mar 27  2:00s
-			 3:00	-	+03	2014 Oct 26  2:00s
+			 3:00	-	FET	2014 Oct 26  2:00s
 			 2:00	-	EET
 
 
@@ -2424,16 +2412,6 @@
 # 78	RU-SPE	Saint Petersburg
 # 83	RU-NEN	Nenets Autonomous Okrug
 
-# From Paul Eggert (2016-08-23):
-# The Soviets switched to UT-based time in 1919.  Decree No. 59
-# (1919-02-08) http://istmat.info/node/35567 established UT-based time
-# zones, and Decree No. 147 (1919-03-29) http://istmat.info/node/35854
-# specified a transition date of 1919-07-01, apparently at 00:00 UT.
-# No doubt only the Soviet-controlled regions switched on that date;
-# later transitions to UT-based time in other parts of Russia are
-# taken from what appear to be guesses by Shanks.
-# (Thanks to Alexander Belopolsky for pointers to the decrees.)
-
 # From Stepan Golosunov (2016-03-07):
 # 11. Regions-violators, 1981-1982.
 # Wikipedia refers to
@@ -2475,7 +2453,7 @@
 # attributes the 1982 changes to the Act of the Council of Ministers
 # of the USSR No. 126 from 18.02.1982.  1980-925.txt also adds
 # Udmurtia to the list of affected territories and lists Khatangsky
-# district separately from Taymyr Autonomous Okrug.  Probably erroneously.
+# district separately from Taymyr Autonomous Okurg.  Probably erroneously.
 #
 # The affected territories are currently listed under Europe/Moscow,
 # Asia/Yekaterinburg and Asia/Krasnoyarsk.
@@ -2535,7 +2513,7 @@
 
 Zone Europe/Moscow	 2:30:17 -	LMT	1880
 			 2:30:17 -	MMT	1916 Jul  3 # Moscow Mean Time
-			 2:31:19 Russia	%s	1919 Jul  1  0:00u
+			 2:31:19 Russia	%s	1919 Jul  1  2:00
 			 3:00	Russia	%s	1921 Oct
 			 3:00	Russia	MSK/MSD	1922 Oct
 			 2:00	-	EET	1930 Jun 21
@@ -2618,21 +2596,22 @@
 # The 1988 transition is from USSR act No. 5 (1988-01-04).
 
 Zone Europe/Volgograd	 2:57:40 -	LMT	1920 Jan  3
-			 3:00	-	+03	1930 Jun 21
-			 4:00	-	+04	1961 Nov 11
-			 4:00	Russia	+04/+05	1988 Mar 27  2:00s
-			 3:00	Russia	+03/+04	1991 Mar 31  2:00s
-			 4:00	-	+04	1992 Mar 29  2:00s
-			 3:00	Russia	+03/+04	2011 Mar 27  2:00s
-			 4:00	-	+04	2014 Oct 26  2:00s
-			 3:00	-	+03
+			 3:00	-	TSAT	1925 Apr  6 # Tsaritsyn Time
+			 3:00	-	STAT	1930 Jun 21 # Stalingrad Time
+			 4:00	-	STAT	1961 Nov 11
+			 4:00	Russia	VOL%sT	1988 Mar 27  2:00s # Volgograd T
+			 3:00	Russia	VOL%sT	1991 Mar 31  2:00s
+			 4:00	-	VOLT	1992 Mar 29  2:00s
+			 3:00	Russia	MSK/MSD	2011 Mar 27  2:00s
+			 4:00	-	MSK	2014 Oct 26  2:00s
+			 3:00	-	MSK
 
 # From Paul Eggert (2016-03-18):
 # Europe/Kirov covers:
 # 43	RU-KIR	Kirov Oblast
 # The 1989 transition is from USSR act No. 227 (1989-03-14).
 #
-Zone Europe/Kirov	 3:18:48 -	LMT	1919 Jul  1  0:00u
+Zone Europe/Kirov	 3:18:48 -	LMT	1919 Jul  1  2:00
 			 3:00	-	+03	1930 Jun 21
 			 4:00	Russia	+04/+05	1989 Mar 26  2:00s
 			 3:00	Russia	+03/+04	1991 Mar 31  2:00s
@@ -2650,16 +2629,16 @@
 # Byalokoz 1919 says Samara was 3:20:20.
 # The 1989 transition is from USSR act No. 227 (1989-03-14).
 
-Zone Europe/Samara	 3:20:20 -	LMT	1919 Jul  1  0:00u
-			 3:00	-	+03	1930 Jun 21
-			 4:00	-	+04	1935 Jan 27
-			 4:00	Russia	+04/+05	1989 Mar 26  2:00s
-			 3:00	Russia	+03/+04	1991 Mar 31  2:00s
-			 2:00	Russia	+02/+03	1991 Sep 29  2:00s
-			 3:00	-	+03	1991 Oct 20  3:00
-			 4:00	Russia	+04/+05	2010 Mar 28  2:00s
-			 3:00	Russia	+03/+04	2011 Mar 27  2:00s
-			 4:00	-	+04
+Zone Europe/Samara	 3:20:20 -	LMT	1919 Jul  1  2:00
+			 3:00	-	SAMT	1930 Jun 21 # Samara Time
+			 4:00	-	SAMT	1935 Jan 27
+			 4:00	Russia	KUY%sT	1989 Mar 26  2:00s # Kuybyshev
+			 3:00	Russia	MSK/MSD	1991 Mar 31  2:00s
+			 2:00	Russia	EE%sT	1991 Sep 29  2:00s
+			 3:00	-	SAMT	1991 Oct 20  3:00
+			 4:00	Russia	SAM%sT	2010 Mar 28  2:00s
+			 3:00	Russia	SAM%sT	2011 Mar 27  2:00s
+			 4:00	-	SAMT
 
 # From Paul Eggert (2016-03-18):
 # Europe/Ulyanovsk covers:
@@ -2674,7 +2653,7 @@
 # From Matt Johnson (2016-03-09):
 # http://publication.pravo.gov.ru/Document/View/0001201603090051
 
-Zone Europe/Ulyanovsk	 3:13:36 -	LMT	1919 Jul  1  0:00u
+Zone Europe/Ulyanovsk	 3:13:36 -	LMT	1919 Jul  1  2:00
 			 3:00	-	+03	1930 Jun 21
 			 4:00	Russia	+04/+05	1989 Mar 26  2:00s
 			 3:00	Russia	+03/+04	1991 Mar 31  2:00s
@@ -2706,12 +2685,12 @@
 
 Zone Asia/Yekaterinburg	 4:02:33 -	LMT	1916 Jul  3
 			 3:45:05 -	PMT	1919 Jul 15  4:00
-			 4:00	-	+04	1930 Jun 21
-			 5:00	Russia	+05/+06	1991 Mar 31  2:00s
-			 4:00	Russia	+04/+05	1992 Jan 19  2:00s
-			 5:00	Russia	+05/+06	2011 Mar 27  2:00s
-			 6:00	-	+06	2014 Oct 26  2:00s
-			 5:00	-	+05
+			 4:00	-	SVET	1930 Jun 21 # Sverdlovsk Time
+			 5:00	Russia	SVE%sT	1991 Mar 31  2:00s
+			 4:00	Russia	SVE%sT	1992 Jan 19  2:00s
+			 5:00	Russia	YEK%sT	2011 Mar 27  2:00s
+			 6:00	-	YEKT	2014 Oct 26  2:00s
+			 5:00	-	YEKT
 
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2001-08-25):
@@ -2721,12 +2700,12 @@
 # Byalokoz 1919 says Omsk was 4:53:30.
 
 Zone Asia/Omsk		 4:53:30 -	LMT	1919 Nov 14
-			 5:00	-	+05	1930 Jun 21
-			 6:00	Russia	+06/+07	1991 Mar 31  2:00s
-			 5:00	Russia	+05/+06	1992 Jan 19  2:00s
-			 6:00	Russia	+06/+07	2011 Mar 27  2:00s
-			 7:00	-	+07	2014 Oct 26  2:00s
-			 6:00	-	+06
+			 5:00	-	OMST	1930 Jun 21 # Omsk Time
+			 6:00	Russia	OMS%sT	1991 Mar 31  2:00s
+			 5:00	Russia	OMS%sT	1992 Jan 19  2:00s
+			 6:00	Russia	OMS%sT	2011 Mar 27  2:00s
+			 7:00	-	OMST	2014 Oct 26  2:00s
+			 6:00	-	OMST
 
 # From Paul Eggert (2016-02-22):
 # Asia/Barnaul covers:
@@ -2806,7 +2785,7 @@
 # Note that time belts (numbered from 2 (Moscow) to 12 according to their
 # GMT/UTC offset and having too many exceptions like regions formally
 # belonging to one belt but using time from another) were replaced
-# with time zones in 2011 with different numbering (there was a
+# with time zones in 2011 with different numberings (there was a
 # 2-hour gap between second and third zones in 2011-2014).
 
 # From Stepan Golosunov (2016-04-12):
@@ -2889,12 +2868,12 @@
 # Byalokoz 1919 says Krasnoyarsk was 6:11:26.
 
 Zone Asia/Krasnoyarsk	 6:11:26 -	LMT	1920 Jan  6
-			 6:00	-	+06	1930 Jun 21
-			 7:00	Russia	+07/+08	1991 Mar 31  2:00s
-			 6:00	Russia	+06/+07	1992 Jan 19  2:00s
-			 7:00	Russia	+07/+08	2011 Mar 27  2:00s
-			 8:00	-	+08	2014 Oct 26  2:00s
-			 7:00	-	+07
+			 6:00	-	KRAT	1930 Jun 21 # Krasnoyarsk Time
+			 7:00	Russia	KRA%sT	1991 Mar 31  2:00s
+			 6:00	Russia	KRA%sT	1992 Jan 19  2:00s
+			 7:00	Russia	KRA%sT	2011 Mar 27  2:00s
+			 8:00	-	KRAT	2014 Oct 26  2:00s
+			 7:00	-	KRAT
 
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2001-08-25):
@@ -2911,12 +2890,12 @@
 
 Zone Asia/Irkutsk	 6:57:05 -	LMT	1880
 			 6:57:05 -	IMT	1920 Jan 25 # Irkutsk Mean Time
-			 7:00	-	+07	1930 Jun 21
-			 8:00	Russia	+08/+09	1991 Mar 31  2:00s
-			 7:00	Russia	+07/+08	1992 Jan 19  2:00s
-			 8:00	Russia	+08/+09	2011 Mar 27  2:00s
-			 9:00	-	+09	2014 Oct 26  2:00s
-			 8:00	-	+08
+			 7:00	-	IRKT	1930 Jun 21 # Irkutsk Time
+			 8:00	Russia	IRK%sT	1991 Mar 31  2:00s
+			 7:00	Russia	IRK%sT	1992 Jan 19  2:00s
+			 8:00	Russia	IRK%sT	2011 Mar 27  2:00s
+			 9:00	-	IRKT	2014 Oct 26  2:00s
+			 8:00	-	IRKT
 
 
 # From Tim Parenti (2014-07-06):
@@ -2933,13 +2912,13 @@
 # http://publication.pravo.gov.ru/Document/View/0001201512300107
 
 Zone Asia/Chita	 7:33:52 -	LMT	1919 Dec 15
-			 8:00	-	+08	1930 Jun 21
-			 9:00	Russia	+09/+10	1991 Mar 31  2:00s
-			 8:00	Russia	+08/+09	1992 Jan 19  2:00s
-			 9:00	Russia	+09/+10	2011 Mar 27  2:00s
-			10:00	-	+10	2014 Oct 26  2:00s
-			 8:00	-	+08	2016 Mar 27  2:00
-			 9:00	-	+09
+			 8:00	-	YAKT	1930 Jun 21 # Yakutsk Time
+			 9:00	Russia	YAK%sT	1991 Mar 31  2:00s
+			 8:00	Russia	YAK%sT	1992 Jan 19  2:00s
+			 9:00	Russia	YAK%sT	2011 Mar 27  2:00s
+			10:00	-	YAKT	2014 Oct 26  2:00s
+			 8:00	-	IRKT	2016 Mar 27  2:00
+			 9:00	-	YAKT
 
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2009-11-29):
@@ -2979,12 +2958,12 @@
 # Byalokoz 1919 says Yakutsk was 8:38:58.
 
 Zone Asia/Yakutsk	 8:38:58 -	LMT	1919 Dec 15
-			 8:00	-	+08	1930 Jun 21
-			 9:00	Russia	+09/+10	1991 Mar 31  2:00s
-			 8:00	Russia	+08/+09	1992 Jan 19  2:00s
-			 9:00	Russia	+09/+10	2011 Mar 27  2:00s
-			10:00	-	+10	2014 Oct 26  2:00s
-			 9:00	-	+09
+			 8:00	-	YAKT	1930 Jun 21 # Yakutsk Time
+			 9:00	Russia	YAK%sT	1991 Mar 31  2:00s
+			 8:00	Russia	YAK%sT	1992 Jan 19  2:00s
+			 9:00	Russia	YAK%sT	2011 Mar 27  2:00s
+			10:00	-	YAKT	2014 Oct 26  2:00s
+			 9:00	-	YAKT
 
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2009-11-29):
@@ -3002,12 +2981,12 @@
 # Go with Byalokoz.
 
 Zone Asia/Vladivostok	 8:47:31 -	LMT	1922 Nov 15
-			 9:00	-	+09	1930 Jun 21
-			10:00	Russia	+10/+11	1991 Mar 31  2:00s
-			 9:00	Russia	+09/+10	1992 Jan 19  2:00s
-			10:00	Russia	+10/+11	2011 Mar 27  2:00s
-			11:00	-	+11	2014 Oct 26  2:00s
-			10:00	-	+10
+			 9:00	-	VLAT	1930 Jun 21 # Vladivostok Time
+			10:00	Russia	VLA%sT	1991 Mar 31  2:00s
+			 9:00	Russia	VLA%sT	1992 Jan 19  2:00s
+			10:00	Russia	VLA%sT	2011 Mar 27  2:00s
+			11:00	-	VLAT	2014 Oct 26  2:00s
+			10:00	-	VLAT
 
 
 # From Tim Parenti (2014-07-03):
@@ -3025,14 +3004,14 @@
 # This transition is no doubt wrong, but we have no better info.
 
 Zone Asia/Khandyga	 9:02:13 -	LMT	1919 Dec 15
-			 8:00	-	+08	1930 Jun 21
-			 9:00	Russia	+09/+10	1991 Mar 31  2:00s
-			 8:00	Russia	+08/+09	1992 Jan 19  2:00s
-			 9:00	Russia	+09/+10	2004
-			10:00	Russia	+10/+11	2011 Mar 27  2:00s
-			11:00	-	+11	2011 Sep 13  0:00s # Decree 725?
-			10:00	-	+10	2014 Oct 26  2:00s
-			 9:00	-	+09
+			 8:00	-	YAKT	1930 Jun 21 # Yakutsk Time
+			 9:00	Russia	YAK%sT	1991 Mar 31  2:00s
+			 8:00	Russia	YAK%sT	1992 Jan 19  2:00s
+			 9:00	Russia	YAK%sT	2004
+			10:00	Russia	VLA%sT	2011 Mar 27  2:00s
+			11:00	-	VLAT	2011 Sep 13  0:00s # Decree 725?
+			10:00	-	YAKT	2014 Oct 26  2:00s
+			 9:00	-	YAKT
 
 
 # From Tim Parenti (2014-07-03):
@@ -3048,14 +3027,15 @@
 
 # The Zone name should be Asia/Yuzhno-Sakhalinsk, but that's too long.
 Zone Asia/Sakhalin	 9:30:48 -	LMT	1905 Aug 23
-			 9:00	-	+09	1945 Aug 25
-			11:00	Russia	+11/+12	1991 Mar 31  2:00s # Sakhalin T
-			10:00	Russia	+10/+11	1992 Jan 19  2:00s
-			11:00	Russia	+11/+12	1997 Mar lastSun  2:00s
-			10:00	Russia	+10/+11	2011 Mar 27  2:00s
-			11:00	-	+11	2014 Oct 26  2:00s
-			10:00	-	+10	2016 Mar 27  2:00s
-			11:00	-	+11
+			 9:00	-	JCST	1937 Oct  1
+			 9:00	-	JST	1945 Aug 25
+			11:00	Russia	SAK%sT	1991 Mar 31  2:00s # Sakhalin T
+			10:00	Russia	SAK%sT	1992 Jan 19  2:00s
+			11:00	Russia	SAK%sT	1997 Mar lastSun  2:00s
+			10:00	Russia	SAK%sT	2011 Mar 27  2:00s
+			11:00	-	SAKT	2014 Oct 26  2:00s
+			10:00	-	SAKT	2016 Mar 27  2:00s
+			11:00	-	SAKT
 
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2009-11-29):
@@ -3078,13 +3058,13 @@
 # http://publication.pravo.gov.ru/Document/View/0001201604050038
 
 Zone Asia/Magadan	10:03:12 -	LMT	1924 May  2
-			10:00	-	+10	1930 Jun 21 # Magadan Time
-			11:00	Russia	+11/+12	1991 Mar 31  2:00s
-			10:00	Russia	+10/+11	1992 Jan 19  2:00s
-			11:00	Russia	+11/+12	2011 Mar 27  2:00s
-			12:00	-	+12	2014 Oct 26  2:00s
-			10:00	-	+10	2016 Apr 24  2:00s
-			11:00	-	+11
+			10:00	-	MAGT	1930 Jun 21 # Magadan Time
+			11:00	Russia	MAG%sT	1991 Mar 31  2:00s
+			10:00	Russia	MAG%sT	1992 Jan 19  2:00s
+			11:00	Russia	MAG%sT	2011 Mar 27  2:00s
+			12:00	-	MAGT	2014 Oct 26  2:00s
+			10:00	-	MAGT	2016 Apr 24  2:00s
+			11:00	-	MAGT
 
 
 # From Tim Parenti (2014-07-06):
@@ -3127,14 +3107,17 @@
 # in Russian.)  In addition, Srednekolymsk appears to be a much older
 # settlement and the population of Zyryanka seems to be declining.
 # Go with Srednekolymsk.
+#
+# Since Magadan Oblast moves to UTC+10 on 2014-10-26, we cannot keep using MAGT
+# as the abbreviation.  Use SRET instead.
 
 Zone Asia/Srednekolymsk	10:14:52 -	LMT	1924 May  2
-			10:00	-	+10	1930 Jun 21
-			11:00	Russia	+11/+12	1991 Mar 31  2:00s
-			10:00	Russia	+10/+11	1992 Jan 19  2:00s
-			11:00	Russia	+11/+12	2011 Mar 27  2:00s
-			12:00	-	+12	2014 Oct 26  2:00s
-			11:00	-	+11
+			10:00	-	MAGT	1930 Jun 21 # Magadan Time
+			11:00	Russia	MAG%sT	1991 Mar 31  2:00s
+			10:00	Russia	MAG%sT	1992 Jan 19  2:00s
+			11:00	Russia	MAG%sT	2011 Mar 27  2:00s
+			12:00	-	MAGT	2014 Oct 26  2:00s
+			11:00	-	SRET	# Srednekolymsk Time
 
 
 # From Tim Parenti (2014-07-03):
@@ -3152,14 +3135,14 @@
 # UTC+12 since at least then, too.
 
 Zone Asia/Ust-Nera	 9:32:54 -	LMT	1919 Dec 15
-			 8:00	-	+08	1930 Jun 21
-			 9:00	Russia	+09/+10	1981 Apr  1
-			11:00	Russia	+11/+12	1991 Mar 31  2:00s
-			10:00	Russia	+10/+11	1992 Jan 19  2:00s
-			11:00	Russia	+11/+12	2011 Mar 27  2:00s
-			12:00	-	+12	2011 Sep 13  0:00s # Decree 725?
-			11:00	-	+11	2014 Oct 26  2:00s
-			10:00	-	+10
+			 8:00	-	YAKT	1930 Jun 21 # Yakutsk Time
+			 9:00	Russia	YAKT	1981 Apr  1
+			11:00	Russia	MAG%sT	1991 Mar 31  2:00s
+			10:00	Russia	MAG%sT	1992 Jan 19  2:00s
+			11:00	Russia	MAG%sT	2011 Mar 27  2:00s
+			12:00	-	MAGT	2011 Sep 13  0:00s # Decree 725?
+			11:00	-	VLAT	2014 Oct 26  2:00s
+			10:00	-	VLAT
 
 
 # From Tim Parenti (2014-07-03), per Oscar van Vlijmen (2001-08-25):
@@ -3172,12 +3155,12 @@
 # The Zone name should be Asia/Petropavlovsk-Kamchatski or perhaps
 # Asia/Petropavlovsk-Kamchatsky, but these are too long.
 Zone Asia/Kamchatka	10:34:36 -	LMT	1922 Nov 10
-			11:00	-	+11	1930 Jun 21
-			12:00	Russia	+12/+13	1991 Mar 31  2:00s
-			11:00	Russia	+11/+12	1992 Jan 19  2:00s
-			12:00	Russia	+12/+13	2010 Mar 28  2:00s
-			11:00	Russia	+11/+12	2011 Mar 27  2:00s
-			12:00	-	+12
+			11:00	-	PETT	1930 Jun 21 # P-K Time
+			12:00	Russia	PET%sT	1991 Mar 31  2:00s
+			11:00	Russia	PET%sT	1992 Jan 19  2:00s
+			12:00	Russia	PET%sT	2010 Mar 28  2:00s
+			11:00	Russia	PET%sT	2011 Mar 27  2:00s
+			12:00	-	PETT
 
 
 # From Tim Parenti (2014-07-03):
@@ -3185,13 +3168,13 @@
 # 87	RU-CHU	Chukotka Autonomous Okrug
 
 Zone Asia/Anadyr	11:49:56 -	LMT	1924 May  2
-			12:00	-	+12	1930 Jun 21
-			13:00	Russia	+13/+14	1982 Apr  1  0:00s
-			12:00	Russia	+12/+13	1991 Mar 31  2:00s
-			11:00	Russia	+11/+12	1992 Jan 19  2:00s
-			12:00	Russia	+12/+13	2010 Mar 28  2:00s
-			11:00	Russia	+11/+12	2011 Mar 27  2:00s
-			12:00	-	+12
+			12:00	-	ANAT	1930 Jun 21 # Anadyr Time
+			13:00	Russia	ANA%sT	1982 Apr  1  0:00s
+			12:00	Russia	ANA%sT	1991 Mar 31  2:00s
+			11:00	Russia	ANA%sT	1992 Jan 19  2:00s
+			12:00	Russia	ANA%sT	2010 Mar 28  2:00s
+			11:00	Russia	ANA%sT	2011 Mar 27  2:00s
+			12:00	-	ANAT
 
 
 # San Marino
@@ -3512,14 +3495,6 @@
 # Engineered Standard Time," said Twitter user @aysekarahasan.
 # http://www.bbc.com/news/world-europe-34631326
 
-# From Burak AYDIN (2016-09-08):
-# Turkey will stay in Daylight Saving Time even in winter....
-# http://www.resmigazete.gov.tr/eskiler/2016/09/20160908-2.pdf
-#
-# From Paul Eggert (2016-09-07):
-# The change is permanent, so this is the new standard time in Turkey.
-# It takes effect today, which is not much notice.
-
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER/S
 Rule	Turkey	1916	only	-	May	 1	0:00	1:00	S
 Rule	Turkey	1916	only	-	Oct	 1	0:00	0	-
@@ -3583,7 +3558,7 @@
 Zone	Europe/Istanbul	1:55:52 -	LMT	1880
 			1:56:56	-	IMT	1910 Oct # Istanbul Mean Time?
 			2:00	Turkey	EE%sT	1978 Oct 15
-			3:00	Turkey	+03/+04	1985 Apr 20
+			3:00	Turkey	TR%sT	1985 Apr 20 # Turkey Time
 			2:00	Turkey	EE%sT	2007
 			2:00	EU	EE%sT	2011 Mar 27  1:00u
 			2:00	-	EET	2011 Mar 28  1:00u
@@ -3591,8 +3566,7 @@
 			2:00	-	EET	2014 Mar 31  1:00u
 			2:00	EU	EE%sT	2015 Oct 25  1:00u
 			2:00	1:00	EEST	2015 Nov  8  1:00u
-			2:00	EU	EE%sT	2016 Sep  7
-			3:00	-	+03
+			2:00	EU	EE%sT
 Link	Europe/Istanbul	Asia/Istanbul	# Istanbul is in both continents.
 
 # Ukraine
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/factory b/jdk/test/sun/util/calendar/zi/tzdata/factory
index 7d79693..0a6041d 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/factory
+++ b/jdk/test/sun/util/calendar/zi/tzdata/factory
@@ -24,10 +24,9 @@
 # This file is in the public domain, so clarified as of
 # 2009-05-17 by Arthur David Olson.
 
-# For distributors who don't want to put time zone specification in
-# their installation procedures.  Users that run 'date' will get the
-# time zone abbreviation "-00", indicating that the actual time zone
-# is unknown.
+# For companies who don't want to put time zone specification in
+# their installation procedures.  When users run date, they'll get the message.
+# Also useful for the "comp.sources" version.
 
 # Zone	NAME	GMTOFF	RULES	FORMAT
-Zone	Factory	0	-	-00
+Zone	Factory	0	- "Local time zone must be set--see zic manual page"
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/leapseconds b/jdk/test/sun/util/calendar/zi/tzdata/leapseconds
index 71d774d..a08fbc7 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/leapseconds
+++ b/jdk/test/sun/util/calendar/zi/tzdata/leapseconds
@@ -79,7 +79,6 @@
 Leap	2008	Dec	31	23:59:60	+	S
 Leap	2012	Jun	30	23:59:60	+	S
 Leap	2015	Jun	30	23:59:60	+	S
-Leap	2016	Dec	31	23:59:60	+	S
 
-#	Updated through IERS Bulletin C52
-#	File expires on:  28 June 2017
+#	Updated through IERS Bulletin C51
+#	File expires on:  28 December 2016
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/northamerica b/jdk/test/sun/util/calendar/zi/tzdata/northamerica
index 8ab635d..ec59510 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/northamerica
+++ b/jdk/test/sun/util/calendar/zi/tzdata/northamerica
@@ -436,42 +436,11 @@
 # north of the Salmon River, and the towns of Burgdorf and Warren),
 # Nevada (except West Wendover), Oregon (except the northern 3/4 of
 # Malheur county), and Washington
-
-# From Paul Eggert (2016-08-20):
-# In early February 1948, in response to California's electricity shortage,
-# PG&E changed power frequency from 60 to 59.5 Hz during daylight hours,
-# causing electric clocks to lose six minutes per day.  (This did not change
-# legal time, and is not part of the data here.)  See:
-# Ross SA. An energy crisis from the past: Northern California in 1948.
-# Working Paper No. 8, Institute of Governmental Studies, UC Berkeley,
-# 1973-11.  http://escholarship.org/uc/item/8x22k30c
-#
-# In another measure to save electricity, DST was instituted from 1948-03-14
-# at 02:01 to 1949-01-16 at 02:00, with the governor having the option to move
-# the fallback transition earlier.  See pages 3-4 of:
-# http://clerk.assembly.ca.gov/sites/clerk.assembly.ca.gov/files/archive/Statutes/1948/48Vol1_Chapters.pdf
-#
-# In response:
-#
-#   Governor Warren received a torrent of objecting mail, and it is not too much
-#   to speculate that the objections to Daylight Saving Time were one important
-#   factor in the defeat of the Dewey-Warren Presidential ticket in California.
-#     -- Ross, p 25
-#
-# On December 8 the governor exercised the option, setting the date to January 1
-# (LA Times 1948-12-09).  The transition time was 02:00 (LA Times 1949-01-01).
-#
-# Despite the controversy, in 1949 California voters approved Proposition 12,
-# which established DST from April's last Sunday at 01:00 until September's
-# last Sunday at 02:00. This was amended by 1962's Proposition 6, which changed
-# the fall-back date to October's last Sunday. See:
-# http://repository.uchastings.edu/cgi/viewcontent.cgi?article=1501&context=ca_ballot_props
-# http://repository.uchastings.edu/cgi/viewcontent.cgi?article=1636&context=ca_ballot_props
 #
 # Rule	NAME	FROM	TO	TYPE	IN	ON	AT	SAVE	LETTER
-Rule	CA	1948	only	-	Mar	14	2:01	1:00	D
+Rule	CA	1948	only	-	Mar	14	2:00	1:00	D
 Rule	CA	1949	only	-	Jan	 1	2:00	0	S
-Rule	CA	1950	1966	-	Apr	lastSun	1:00	1:00	D
+Rule	CA	1950	1966	-	Apr	lastSun	2:00	1:00	D
 Rule	CA	1950	1961	-	Sep	lastSun	2:00	0	S
 Rule	CA	1962	1966	-	Oct	lastSun	2:00	0	S
 # Zone	NAME		GMTOFF	RULES	FORMAT	[UNTIL]
@@ -3335,7 +3304,7 @@
 # indicating that the normal ET rules are followed.
 #
 # From Paul Eggert (2014-08-19):
-# The 2014-08-13 Cabinet meeting decided to stay on UT -04 year-round.  See:
+# The 2014-08-13 Cabinet meeting decided to stay on UTC-4 year-round.  See:
 # http://tcweeklynews.com/daylight-savings-time-to-be-maintained-p5353-127.htm
 # Model this as a switch from EST/EDT to AST ...
 # From Chris Walton (2014-11-04):
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/southamerica b/jdk/test/sun/util/calendar/zi/tzdata/southamerica
index bbc0a95..08c89ca 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/southamerica
+++ b/jdk/test/sun/util/calendar/zi/tzdata/southamerica
@@ -433,9 +433,9 @@
 # stuck on Summer daylight savings time even though the summer is over.
 
 # From Paul Eggert (2013-09-05):
-# Perhaps San Luis operates on the legal fiction that it is at -04
+# Perhaps San Luis operates on the legal fiction that it is at UTC-4
 # with perpetual summer time, but ordinary usage typically seems to
-# just say it's at -03; see, for example,
+# just say it's at UTC-3; see, for example,
 # http://es.wikipedia.org/wiki/Hora_oficial_argentina
 # We've documented similar situations as being plain changes to
 # standard time, so let's do that here too.  This does not change UTC
diff --git a/jdk/test/sun/util/calendar/zi/tzdata/zone.tab b/jdk/test/sun/util/calendar/zi/tzdata/zone.tab
index db05060..5649691 100644
--- a/jdk/test/sun/util/calendar/zi/tzdata/zone.tab
+++ b/jdk/test/sun/util/calendar/zi/tzdata/zone.tab
@@ -284,7 +284,7 @@
 MH	+0905+16720	Pacific/Kwajalein	Kwajalein
 MK	+4159+02126	Europe/Skopje
 ML	+1239-00800	Africa/Bamako
-MM	+1647+09610	Asia/Yangon
+MM	+1647+09610	Asia/Rangoon
 MN	+4755+10653	Asia/Ulaanbaatar	Mongolia (most areas)
 MN	+4801+09139	Asia/Hovd	Bayan-Olgiy, Govi-Altai, Hovd, Uvs, Zavkhan
 MN	+4804+11430	Asia/Choibalsan	Dornod, Sukhbaatar
diff --git a/jdk/test/tools/launcher/Arrrghs.java b/jdk/test/tools/launcher/Arrrghs.java
index 73d8689..89893e4 100644
--- a/jdk/test/tools/launcher/Arrrghs.java
+++ b/jdk/test/tools/launcher/Arrrghs.java
@@ -24,7 +24,7 @@
 /**
  * @test
  * @bug 5030233 6214916 6356475 6571029 6684582 6742159 4459600 6758881 6753938
- *      6894719 6968053 7151434 7146424 8007333 8077822 8143640
+ *      6894719 6968053 7151434 7146424 8007333 8077822
  * @summary Argument parsing validation.
  * @compile -XDignore.symbol.file Arrrghs.java
  * @run main/othervm Arrrghs
@@ -324,8 +324,6 @@
         // more treatment of  mixed slashes
         checkArgumentParsing("f1/ f3\\ f4/", "f1/", "f3\\", "f4/");
         checkArgumentParsing("f1/ f2\' ' f3/ f4/", "f1/", "f2\'", "'", "f3/", "f4/");
-
-        checkArgumentParsing("a\\*\\b", "a\\*\\b");
     }
 
     private void initEmptyDir(File emptyDir) throws IOException {
diff --git a/langtools/ASSEMBLY_EXCEPTION b/langtools/ASSEMBLY_EXCEPTION
index 065b8d9..8b7ac1d 100644
--- a/langtools/ASSEMBLY_EXCEPTION
+++ b/langtools/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
-openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
-General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Sun at openjdk.java.net and
+openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
+GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Oracle gives you permission to link this
-    OpenJDK Code with certain code licensed by Oracle as indicated at
+    As a special exception, Sun gives you permission to link this
+    OpenJDK Code with certain code licensed by Sun as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Oracle.
+    governed by the licenses under which they were offered by Sun.
 
-As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
-to build an executable that includes those portions of necessary code that
-Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
-with the Classpath exception).  If you modify or add to the OpenJDK code,
-that new GPL2 code may still be combined with Designated Exception Modules
-if the new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
+build an executable that includes those portions of necessary code that Sun
+could not provide under GPL2 (or that Sun has provided under GPL2 with the
+Classpath exception).  If you modify or add to the OpenJDK code, that new
+GPL2 code may still be combined with Designated Exception Modules if the
+new code is made subject to this exception by its copyright holder.
diff --git a/langtools/LICENSE b/langtools/LICENSE
index 8b400c7..b40a0f4 100644
--- a/langtools/LICENSE
+++ b/langtools/LICENSE
@@ -3,7 +3,7 @@
 Version 2, June 1991
 
 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Everyone is permitted to copy and distribute verbatim copies of this license
 document, but changing it is not allowed.
@@ -287,8 +287,8 @@
     more details.
 
     You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+    with this program; if not, write to the Free Software Foundation, Inc., 59
+    Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Also add information on how to contact you by electronic and paper mail.
 
diff --git a/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java b/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
index 436ffea..e50d192 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/comp/LambdaToMethod.java
@@ -338,11 +338,6 @@
                 syntheticInits.append((JCExpression) captured_local);
             }
         }
-        // add captured outer this instances (used only when `this' capture itself is illegal)
-        for (Symbol fv : localContext.getSymbolMap(CAPTURED_OUTER_THIS).keySet()) {
-            JCTree captured_local = make.QualThis(fv.type);
-            syntheticInits.append((JCExpression) captured_local);
-        }
 
         //then, determine the arguments to the indy call
         List<JCExpression> indy_args = translate(syntheticInits.toList(), localContext.prev);
@@ -439,32 +434,6 @@
         }
     }
 
-    /**
-     * Translate qualified `this' references within a lambda to the mapped identifier
-     * @param tree
-     */
-    @Override
-    public void visitSelect(JCFieldAccess tree) {
-        if (context == null || !analyzer.lambdaFieldAccessFilter(tree)) {
-            super.visitSelect(tree);
-        } else {
-            int prevPos = make.pos;
-            try {
-                make.at(tree);
-
-                LambdaTranslationContext lambdaContext = (LambdaTranslationContext) context;
-                JCTree ltree = lambdaContext.translate(tree);
-                if (ltree != null) {
-                    result = ltree;
-                } else {
-                    super.visitSelect(tree);
-                }
-            } finally {
-                make.at(prevPos);
-            }
-        }
-    }
-
     @Override
     public void visitVarDef(JCVariableDecl tree) {
         LambdaTranslationContext lambdaContext = (LambdaTranslationContext)context;
@@ -1157,11 +1126,6 @@
         private int lambdaCount = 0;
 
         /**
-         * List of types undergoing construction via explicit constructor chaining.
-         */
-        private List<ClassSymbol> typesUnderConstruction;
-
-        /**
          * keep the count of lambda expression defined in given context (used to
          * generate unambiguous names for serializable lambdas)
          */
@@ -1192,36 +1156,11 @@
 
         private JCClassDecl analyzeAndPreprocessClass(JCClassDecl tree) {
             frameStack = List.nil();
-            typesUnderConstruction = List.nil();
             localClassDefs = new HashMap<Symbol, JCClassDecl>();
             return translate(tree);
         }
 
         @Override
-        public void visitApply(JCMethodInvocation tree) {
-            List<ClassSymbol> previousNascentTypes = typesUnderConstruction;
-            try {
-                Name methName = TreeInfo.name(tree.meth);
-                if (methName == names._this || methName == names._super) {
-                    typesUnderConstruction = typesUnderConstruction.prepend(currentClass());
-                }
-                super.visitApply(tree);
-            } finally {
-                typesUnderConstruction = previousNascentTypes;
-            }
-        }
-            // where
-            private ClassSymbol currentClass() {
-                for (Frame frame : frameStack) {
-                    if (frame.tree.hasTag(JCTree.Tag.CLASSDEF)) {
-                        JCClassDecl cdef = (JCClassDecl) frame.tree;
-                        return cdef.sym;
-                    }
-                }
-                return null;
-            }
-
-        @Override
         public void visitBlock(JCBlock tree) {
             List<Frame> prevStack = frameStack;
             try {
@@ -1685,22 +1624,6 @@
         }
 
         /**
-         *  This is used to filter out those select nodes that need to be adjusted
-         *  when translating away lambda expressions - at the moment, this is the
-         *  set of nodes that select `this' (qualified this)
-         */
-        private boolean lambdaFieldAccessFilter(JCFieldAccess fAccess) {
-            LambdaTranslationContext lambdaContext =
-                    context instanceof LambdaTranslationContext ?
-                            (LambdaTranslationContext) context : null;
-            return lambdaContext != null
-                    && !fAccess.sym.isStatic()
-                    && fAccess.name == names._this
-                    && (fAccess.sym.owner.kind == TYP)
-                    && !lambdaContext.translatedSymbols.get(CAPTURED_OUTER_THIS).isEmpty();
-        }
-
-        /**
          * This is used to filter out those new class expressions that need to
          * be qualified with an enclosing tree
          */
@@ -1874,7 +1797,6 @@
                 translatedSymbols.put(LOCAL_VAR, new LinkedHashMap<Symbol, Symbol>());
                 translatedSymbols.put(CAPTURED_VAR, new LinkedHashMap<Symbol, Symbol>());
                 translatedSymbols.put(CAPTURED_THIS, new LinkedHashMap<Symbol, Symbol>());
-                translatedSymbols.put(CAPTURED_OUTER_THIS, new LinkedHashMap<Symbol, Symbol>());
                 translatedSymbols.put(TYPE_VAR, new LinkedHashMap<Symbol, Symbol>());
 
                 freeVarProcessedLocalClasses = new HashSet<>();
@@ -1987,16 +1909,6 @@
                             }
                         };
                         break;
-                    case CAPTURED_OUTER_THIS:
-                        Name name = names.fromString(new String(sym.flatName().toString() + names.dollarThis));
-                        ret = new VarSymbol(SYNTHETIC | FINAL | PARAMETER, name, types.erasure(sym.type), translatedSym) {
-                            @Override
-                            public Symbol baseSymbol() {
-                                //keep mapping with original captured symbol
-                                return sym;
-                            }
-                        };
-                        break;
                     case LOCAL_VAR:
                         ret = new VarSymbol(sym.flags() & FINAL, sym.name, sym.type, translatedSym);
                         ((VarSymbol) ret).pos = ((VarSymbol) sym).pos;
@@ -2017,14 +1929,6 @@
             }
 
             void addSymbol(Symbol sym, LambdaSymbolKind skind) {
-                if (skind == CAPTURED_THIS && sym != null && sym.kind == TYP && !typesUnderConstruction.isEmpty()) {
-                    ClassSymbol currentClass = currentClass();
-                    if (currentClass != null && typesUnderConstruction.contains(currentClass)) {
-                        // reference must be to enclosing outer instance, mutate capture kind.
-                        Assert.check(sym != currentClass); // should have been caught right in Attr
-                        skind = CAPTURED_OUTER_THIS;
-                    }
-                }
                 Map<Symbol, Symbol> transMap = getSymbolMap(skind);
                 if (!transMap.containsKey(sym)) {
                     transMap.put(sym, translate(sym, skind));
@@ -2038,49 +1942,17 @@
             }
 
             JCTree translate(JCIdent lambdaIdent) {
-                for (LambdaSymbolKind kind : LambdaSymbolKind.values()) {
-                    Map<Symbol, Symbol> m = getSymbolMap(kind);
-                    switch(kind) {
-                        default:
-                            if (m.containsKey(lambdaIdent.sym)) {
-                                Symbol tSym = m.get(lambdaIdent.sym);
-                                JCTree t = make.Ident(tSym).setType(lambdaIdent.type);
-                                tSym.setTypeAttributes(lambdaIdent.sym.getRawTypeAttributes());
-                                return t;
-                            }
-                            break;
-                        case CAPTURED_OUTER_THIS:
-                            if (lambdaIdent.sym.owner.kind == TYP && m.containsKey(lambdaIdent.sym.owner)) {
-                                // Transform outer instance variable references anchoring them to the captured synthetic.
-                                Symbol tSym = m.get(lambdaIdent.sym.owner);
-                                JCExpression t = make.Ident(tSym).setType(lambdaIdent.sym.owner.type);
-                                tSym.setTypeAttributes(lambdaIdent.sym.owner.getRawTypeAttributes());
-                                t = make.Select(t, lambdaIdent.name);
-                                t.setType(lambdaIdent.type);
-                                TreeInfo.setSymbol(t, lambdaIdent.sym);
-                                return t;
-                            }
-                            break;
+                for (Map<Symbol, Symbol> m : translatedSymbols.values()) {
+                    if (m.containsKey(lambdaIdent.sym)) {
+                        Symbol tSym = m.get(lambdaIdent.sym);
+                        JCTree t = make.Ident(tSym).setType(lambdaIdent.type);
+                        tSym.setTypeAttributes(lambdaIdent.sym.getRawTypeAttributes());
+                        return t;
                     }
                 }
                 return null;
             }
 
-            /* Translate away qualified this expressions, anchoring them to synthetic parameters that
-               capture the qualified this handle. `fieldAccess' is guaranteed to one such.
-            */
-            public JCTree translate(JCFieldAccess fieldAccess) {
-                Assert.check(fieldAccess.name == names._this);
-                Map<Symbol, Symbol> m = translatedSymbols.get(LambdaSymbolKind.CAPTURED_OUTER_THIS);
-                if (m.containsKey(fieldAccess.sym.owner)) {
-                    Symbol tSym = m.get(fieldAccess.sym.owner);
-                    JCExpression t = make.Ident(tSym).setType(fieldAccess.sym.owner.type);
-                    tSym.setTypeAttributes(fieldAccess.sym.owner.getRawTypeAttributes());
-                    return t;
-                }
-                return null;
-            }
-
             /**
              * The translatedSym is not complete/accurate until the analysis is
              * finished.  Once the analysis is finished, the translatedSym is
@@ -2118,10 +1990,6 @@
                     params.append(make.VarDef((VarSymbol) thisSym, null));
                     parameterSymbols.append((VarSymbol) thisSym);
                 }
-                for (Symbol thisSym : getSymbolMap(CAPTURED_OUTER_THIS).values()) {
-                    params.append(make.VarDef((VarSymbol) thisSym, null));
-                    parameterSymbols.append((VarSymbol) thisSym);
-                }
                 for (Symbol thisSym : getSymbolMap(PARAM).values()) {
                     params.append(make.VarDef((VarSymbol) thisSym, null));
                     parameterSymbols.append((VarSymbol) thisSym);
@@ -2270,7 +2138,6 @@
         LOCAL_VAR,      // original to translated lambda locals
         CAPTURED_VAR,   // variables in enclosing scope to translated synthetic parameters
         CAPTURED_THIS,  // class symbols to translated synthetic parameters (for captured member access)
-        CAPTURED_OUTER_THIS, // used when `this' capture is illegal, but outer this capture is legit (JDK-8129740)
         TYPE_VAR;       // original to translated lambda type variables
     }
 
diff --git a/langtools/src/share/classes/com/sun/tools/javac/tree/TreeMaker.java b/langtools/src/share/classes/com/sun/tools/javac/tree/TreeMaker.java
index 794aba1..b39fd06 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/tree/TreeMaker.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/tree/TreeMaker.java
@@ -621,12 +621,6 @@
         return Ident(new VarSymbol(FINAL, names._this, t, t.tsym));
     }
 
-    /** Create a tree representing qualified `this' given its type
-     */
-    public JCExpression QualThis(Type t) {
-        return Select(Type(t), new VarSymbol(FINAL, names._this, t, t.tsym));
-    }
-
     /** Create a tree representing a class literal.
      */
     public JCExpression ClassLiteral(ClassSymbol clazz) {
diff --git a/langtools/src/share/classes/com/sun/tools/javac/util/Names.java b/langtools/src/share/classes/com/sun/tools/javac/util/Names.java
index 7f8ce46..cc52e0d 100644
--- a/langtools/src/share/classes/com/sun/tools/javac/util/Names.java
+++ b/langtools/src/share/classes/com/sun/tools/javac/util/Names.java
@@ -176,7 +176,6 @@
     public final Name lambda;
     public final Name metafactory;
     public final Name altMetafactory;
-    public final Name dollarThis;
 
     public final Name.Table table;
 
@@ -235,7 +234,6 @@
         value = fromString("value");
         valueOf = fromString("valueOf");
         values = fromString("values");
-        dollarThis = fromString("$this");
 
         // class names
         java_io_Serializable = fromString("java.io.Serializable");
diff --git a/nashorn/ASSEMBLY_EXCEPTION b/nashorn/ASSEMBLY_EXCEPTION
index 065b8d9..8b7ac1d 100644
--- a/nashorn/ASSEMBLY_EXCEPTION
+++ b/nashorn/ASSEMBLY_EXCEPTION
@@ -1,27 +1,27 @@
 
 OPENJDK ASSEMBLY EXCEPTION
 
-The OpenJDK source code made available by Oracle America, Inc. (Oracle) at
-openjdk.java.net ("OpenJDK Code") is distributed under the terms of the GNU
-General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
+The OpenJDK source code made available by Sun at openjdk.java.net and
+openjdk.dev.java.net ("OpenJDK Code") is distributed under the terms of the
+GNU General Public License <http://www.gnu.org/copyleft/gpl.html> version 2
 only ("GPL2"), with the following clarification and special exception.
 
     Linking this OpenJDK Code statically or dynamically with other code
     is making a combined work based on this library.  Thus, the terms
     and conditions of GPL2 cover the whole combination.
 
-    As a special exception, Oracle gives you permission to link this
-    OpenJDK Code with certain code licensed by Oracle as indicated at
+    As a special exception, Sun gives you permission to link this
+    OpenJDK Code with certain code licensed by Sun as indicated at
     http://openjdk.java.net/legal/exception-modules-2007-05-08.html
     ("Designated Exception Modules") to produce an executable,
     regardless of the license terms of the Designated Exception Modules,
     and to copy and distribute the resulting executable under GPL2,
     provided that the Designated Exception Modules continue to be
-    governed by the licenses under which they were offered by Oracle.
+    governed by the licenses under which they were offered by Sun.
 
-As such, it allows licensees and sublicensees of Oracle's GPL2 OpenJDK Code
-to build an executable that includes those portions of necessary code that
-Oracle could not provide under GPL2 (or that Oracle has provided under GPL2
-with the Classpath exception).  If you modify or add to the OpenJDK code,
-that new GPL2 code may still be combined with Designated Exception Modules
-if the new code is made subject to this exception by its copyright holder.
+As such, it allows licensees and sublicensees of Sun's GPL2 OpenJDK Code to
+build an executable that includes those portions of necessary code that Sun
+could not provide under GPL2 (or that Sun has provided under GPL2 with the
+Classpath exception).  If you modify or add to the OpenJDK code, that new
+GPL2 code may still be combined with Designated Exception Modules if the
+new code is made subject to this exception by its copyright holder.
diff --git a/nashorn/LICENSE b/nashorn/LICENSE
index 8b400c7..b40a0f4 100644
--- a/nashorn/LICENSE
+++ b/nashorn/LICENSE
@@ -3,7 +3,7 @@
 Version 2, June 1991
 
 Copyright (C) 1989, 1991 Free Software Foundation, Inc.
-51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Everyone is permitted to copy and distribute verbatim copies of this license
 document, but changing it is not allowed.
@@ -287,8 +287,8 @@
     more details.
 
     You should have received a copy of the GNU General Public License along
-    with this program; if not, write to the Free Software Foundation, Inc.,
-    51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+    with this program; if not, write to the Free Software Foundation, Inc., 59
+    Temple Place, Suite 330, Boston, MA 02111-1307 USA
 
 Also add information on how to contact you by electronic and paper mail.
 
diff --git a/nashorn/make/build.xml b/nashorn/make/build.xml
index d004102..e4ca328 100644
--- a/nashorn/make/build.xml
+++ b/nashorn/make/build.xml
@@ -83,12 +83,6 @@
     <condition property="jfr.options" value="${run.test.jvmargs.jfr}" else="">
       <istrue value="${jfr}"/>
     </condition>
-
-    <condition property="test-sys-prop-no-security.os.not.windows">
-      <not>
-        <os family="windows"/>
-      </not>
-    </condition>
   </target>
 
   <!-- check minimum ant version required to be 1.8.4 -->
@@ -425,10 +419,6 @@
     permission java.io.FilePermission "${basedir}/test/script/external/showdown/-", "read";
 };
 
-grant codeBase "file:/${basedir}/test/script/basic/JDK-8158467.js" {
-    permission java.lang.RuntimePermission "nashorn.setConfig";
-};
-
     </echo>
 
     <replace file="${build.dir}/nashorn.policy"><replacetoken>\</replacetoken><replacevalue>/</replacevalue></replace>    <!--hack for Windows - to make URLs with normal path separators -->
diff --git a/nashorn/samples/exec.js b/nashorn/samples/exec.js
index d10b621..68581c3 100644
--- a/nashorn/samples/exec.js
+++ b/nashorn/samples/exec.js
@@ -39,10 +39,9 @@
 $EXEC("cat", "Hello, world!")
 
 // Additional arguments can be passed after the stdin argument, as an array of
-// strings, or a sequence of varargs (if there is no stdin, null or undefined
-// can be passed):
-$EXEC("ls", undefined, "-l", "-a")
-$EXEC("ls", undefined, ["-l", "-a"])
+// strings, or a sequence of varargs:
+$EXEC("ls", "" /* no stdin */, "-l", "-a")
+$EXEC("ls", "" /* no stdin */, ["-l", "-a"])
 
 // Output of running external commands is returned from $EXEC:
 print($EXEC("ls"))
diff --git a/nashorn/src/jdk/nashorn/api/scripting/NashornException.java b/nashorn/src/jdk/nashorn/api/scripting/NashornException.java
index afaec95..4fe461c 100644
--- a/nashorn/src/jdk/nashorn/api/scripting/NashornException.java
+++ b/nashorn/src/jdk/nashorn/api/scripting/NashornException.java
@@ -175,8 +175,10 @@
                 String methodName = st.getMethodName();
                 if (methodName.equals(CompilerConstants.PROGRAM.symbolName())) {
                     methodName = "<program>";
-                } else {
-                    methodName = stripMethodName(methodName);
+                }
+
+                if (methodName.contains(CompilerConstants.ANON_FUNCTION_PREFIX.symbolName())) {
+                    methodName = "<anonymous>";
                 }
 
                 filtered.add(new StackTraceElement(className, methodName,
@@ -186,22 +188,6 @@
         return filtered.toArray(new StackTraceElement[filtered.size()]);
     }
 
-    private static String stripMethodName(final String methodName) {
-        String name = methodName;
-
-        final int nestedSeparator = name.lastIndexOf(CompilerConstants.NESTED_FUNCTION_SEPARATOR.symbolName());
-        if (nestedSeparator >= 0) {
-            name = name.substring(nestedSeparator + 1);
-        }
-
-        final int idSeparator = name.indexOf(CompilerConstants.ID_FUNCTION_SEPARATOR.symbolName());
-        if (idSeparator >= 0) {
-            name = name.substring(0, idSeparator);
-        }
-
-        return name.contains(CompilerConstants.ANON_FUNCTION_PREFIX.symbolName()) ? "<anonymous>" : name;
-    }
-
     /**
      * Return a formatted script stack trace string with frames information separated by '\n'
      *
diff --git a/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java b/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java
index 0a1bfb1..0f2f3d7 100644
--- a/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java
+++ b/nashorn/src/jdk/nashorn/api/scripting/NashornScriptEngine.java
@@ -319,9 +319,6 @@
         // Create new global instance mirror and associate with the Bindings.
         final ScriptObjectMirror mirror = createGlobalMirror();
         bindings.put(NASHORN_GLOBAL, mirror);
-        // Since we created this global explicitly for the non-default script context we set the
-        // current script context in global permanently so that invokes work as expected. See JDK-8150219
-        mirror.getHomeGlobal().setInitScriptContext(ctxt);
         return mirror.getHomeGlobal();
     }
 
diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
index b2a3164..9e1148f 100644
--- a/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
+++ b/nashorn/src/jdk/nashorn/internal/codegen/CodeGenerator.java
@@ -2454,6 +2454,11 @@
                     }
 
                     @Override
+                    public boolean enterObjectNode(final ObjectNode objectNode) {
+                        return false;
+                    }
+
+                    @Override
                     public boolean enterDefault(final Node node) {
                         if (contains) {
                             return false;
@@ -2521,8 +2526,7 @@
             oc = new FieldObjectCreator<Expression>(this, tuples) {
                 @Override
                 protected void loadValue(final Expression node, final Type type) {
-                    // Use generic type in order to avoid conversion between object types
-                    loadExpressionAsType(node, Type.generic(type));
+                    loadExpressionAsType(node, type);
                 }};
         }
 
@@ -2538,7 +2542,10 @@
         //handler
         if (restOfProperty) {
             final ContinuationInfo ci = getContinuationInfo();
-            ci.setObjectLiteralMap(method.getStackSize(), oc.getMap());
+            // Can be set at most once for a single rest-of method
+            assert ci.getObjectLiteralMap() == null;
+            ci.setObjectLiteralMap(oc.getMap());
+            ci.setObjectLiteralStackDepth(method.getStackSize());
         }
 
         method.dup();
@@ -5252,8 +5259,10 @@
         private Type[] stackTypes;
         // If non-null, this node should perform the requisite type conversion
         private Type returnValueType;
-        // If we are in the middle of an object literal initialization, we need to update the property maps
-        private Map<Integer, PropertyMap> objectLiteralMaps;
+        // If we are in the middle of an object literal initialization, we need to update the map
+        private PropertyMap objectLiteralMap;
+        // Object literal stack depth for object literal - not necessarily top if property is a tree
+        private int objectLiteralStackDepth = -1;
         // The line number at the continuation point
         private int lineNumber;
         // The active catch label, in case the continuation point is in a try/catch block
@@ -5305,15 +5314,20 @@
             this.returnValueType = returnValueType;
         }
 
-        void setObjectLiteralMap(final int objectLiteralStackDepth, final PropertyMap objectLiteralMap) {
-            if (objectLiteralMaps == null) {
-                objectLiteralMaps = new HashMap<>();
-            }
-            objectLiteralMaps.put(objectLiteralStackDepth, objectLiteralMap);
+        int getObjectLiteralStackDepth() {
+            return objectLiteralStackDepth;
         }
 
-        PropertyMap getObjectLiteralMap(final int stackDepth) {
-            return objectLiteralMaps == null ? null : objectLiteralMaps.get(stackDepth);
+        void setObjectLiteralStackDepth(final int objectLiteralStackDepth) {
+            this.objectLiteralStackDepth = objectLiteralStackDepth;
+        }
+
+        PropertyMap getObjectLiteralMap() {
+            return objectLiteralMap;
+        }
+
+        void setObjectLiteralMap(final PropertyMap objectLiteralMap) {
+            this.objectLiteralMap = objectLiteralMap;
         }
 
         @Override
@@ -5403,9 +5417,10 @@
         final int[]   stackStoreSpec = ci.getStackStoreSpec();
         final Type[]  stackTypes     = ci.getStackTypes();
         final boolean isStackEmpty   = stackStoreSpec.length == 0;
-        int replacedObjectLiteralMaps = 0;
+        boolean replacedObjectLiteralMap = false;
         if(!isStackEmpty) {
             // Load arguments on the stack
+            final int objectLiteralStackDepth = ci.getObjectLiteralStackDepth();
             for(int i = 0; i < stackStoreSpec.length; ++i) {
                 final int slot = stackStoreSpec[i];
                 method.load(lvarTypes.get(slot), slot);
@@ -5413,18 +5428,18 @@
                 // stack: s0=object literal being initialized
                 // change map of s0 so that the property we are initializing when we failed
                 // is now ci.returnValueType
-                final PropertyMap map = ci.getObjectLiteralMap(i);
-                if (map != null) {
+                if (i == objectLiteralStackDepth) {
                     method.dup();
+                    assert ci.getObjectLiteralMap() != null;
                     assert ScriptObject.class.isAssignableFrom(method.peekType().getTypeClass()) : method.peekType().getTypeClass() + " is not a script object";
-                    loadConstant(map);
+                    loadConstant(ci.getObjectLiteralMap());
                     method.invoke(ScriptObject.SET_MAP);
-                    replacedObjectLiteralMaps++;
+                    replacedObjectLiteralMap = true;
                 }
             }
         }
-        // Must have emitted the code for replacing all object literal maps
-        assert ci.objectLiteralMaps == null || ci.objectLiteralMaps.size() == replacedObjectLiteralMaps;
+        // Must have emitted the code for replacing the map of an object literal if we have a set object literal stack depth
+        assert ci.getObjectLiteralStackDepth() == -1 || replacedObjectLiteralMap;
         // Load RewriteException back.
         method.load(rewriteExceptionType, lvarCount);
         // Get rid of the stored reference
diff --git a/nashorn/src/jdk/nashorn/internal/codegen/CompilerConstants.java b/nashorn/src/jdk/nashorn/internal/codegen/CompilerConstants.java
index 28bd19f..0d64ac2 100644
--- a/nashorn/src/jdk/nashorn/internal/codegen/CompilerConstants.java
+++ b/nashorn/src/jdk/nashorn/internal/codegen/CompilerConstants.java
@@ -78,12 +78,6 @@
     /** function prefix for anonymous functions */
     ANON_FUNCTION_PREFIX("L:"),
 
-    /** separator for method names of nested functions */
-    NESTED_FUNCTION_SEPARATOR("#"),
-
-    /** separator for making method names unique by appending numeric ids */
-    ID_FUNCTION_SEPARATOR("-"),
-
     /** method name for Java method that is the program entry point */
     PROGRAM(":program"),
 
diff --git a/nashorn/src/jdk/nashorn/internal/codegen/Namespace.java b/nashorn/src/jdk/nashorn/internal/codegen/Namespace.java
index 08ae356..17304a9 100644
--- a/nashorn/src/jdk/nashorn/internal/codegen/Namespace.java
+++ b/nashorn/src/jdk/nashorn/internal/codegen/Namespace.java
@@ -68,7 +68,7 @@
     }
 
     /**
-     * Create a uniqueName name in the namespace in the form base-n where n varies.
+     * Create a uniqueName name in the namespace in the form base$n where n varies.
      * Also truncates very long names that would otherwise break ASM.
      *
      * @param base Base of name.  Base will be returned if uniqueName.
@@ -83,7 +83,7 @@
             if (counter != null) {
                 final int count = counter + 1;
                 namespaceDirectory.put(truncatedBase, count);
-                return truncatedBase + CompilerConstants.ID_FUNCTION_SEPARATOR.symbolName() + count;
+                return truncatedBase + '-' + count;
             }
         }
 
diff --git a/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java b/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java
index 22dc72e..3783ad8 100644
--- a/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java
+++ b/nashorn/src/jdk/nashorn/internal/codegen/SpillObjectCreator.java
@@ -188,8 +188,7 @@
 
     @Override
     protected void loadValue(final Expression expr, final Type type) {
-        // Use generic type in order to avoid conversion between object types
-        codegen.loadExpressionAsType(expr, Type.generic(type));
+        codegen.loadExpressionAsType(expr, type);
     }
 
     @Override
diff --git a/nashorn/src/jdk/nashorn/internal/objects/Global.java b/nashorn/src/jdk/nashorn/internal/objects/Global.java
index 7ad2524..cf83468 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/Global.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/Global.java
@@ -928,8 +928,6 @@
     private ThreadLocal<ScriptContext> scontext;
     // current ScriptEngine associated - can be null.
     private ScriptEngine engine;
-    // initial ScriptContext - usually null and only used for special case
-    private volatile ScriptContext initscontext;
 
     // ES6 global lexical scope.
     private final LexicalScope lexicalScope;
@@ -955,22 +953,9 @@
         return scontext.get();
     }
 
-    /**
-     * Set the initial script context
-     * @param ctxt initial script context
-     */
-    public void setInitScriptContext(final ScriptContext ctxt) {
-        this.initscontext = ctxt;
-    }
-
     private ScriptContext currentContext() {
         final ScriptContext sc = scontext != null? scontext.get() : null;
-        if (sc != null) {
-            return sc;
-        } else if (initscontext != null) {
-            return initscontext;
-        }
-        return engine != null? engine.getContext() : null;
+        return (sc != null)? sc : (engine != null? engine.getContext() : null);
     }
 
     @Override
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeArray.java b/nashorn/src/jdk/nashorn/internal/objects/NativeArray.java
index 0b036a2..e05435a 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeArray.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeArray.java
@@ -247,7 +247,7 @@
                     @Override
                     public MethodHandle call() {
                         return Bootstrap.createDynamicInvoker("dyn:call", double.class,
-                            Object.class, Object.class, Object.class, Object.class);
+                            ScriptFunction.class, Object.class, Object.class, Object.class);
                     }
                 });
     }
@@ -1219,23 +1219,23 @@
         return copy;
     }
 
-    private static Object compareFunction(final Object comparefn) {
+    private static ScriptFunction compareFunction(final Object comparefn) {
         if (comparefn == ScriptRuntime.UNDEFINED) {
             return null;
         }
 
-        if (!Bootstrap.isCallable(comparefn)) {
+        if (! (comparefn instanceof ScriptFunction)) {
             throw typeError("not.a.function", ScriptRuntime.safeToString(comparefn));
         }
 
-        return comparefn;
+        return (ScriptFunction)comparefn;
     }
 
     private static Object[] sort(final Object[] array, final Object comparefn) {
-        final Object cmp = compareFunction(comparefn);
+        final ScriptFunction cmp = compareFunction(comparefn);
 
         final List<Object> list = Arrays.asList(array);
-        final Object cmpThis = cmp == null || Bootstrap.isStrictCallable(cmp) ? ScriptRuntime.UNDEFINED : Global.instance();
+        final Object cmpThis = cmp == null || cmp.isStrict() ? ScriptRuntime.UNDEFINED : Global.instance();
 
         try {
             Collections.sort(list, new Comparator<Object>() {
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java b/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java
index e4a9ac5..877de50 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeJSON.java
@@ -35,10 +35,7 @@
 import java.util.Iterator;
 import java.util.List;
 import java.util.Map;
-import java.util.Objects;
 import java.util.concurrent.Callable;
-import jdk.nashorn.api.scripting.JSObject;
-import jdk.nashorn.api.scripting.ScriptObjectMirror;
 import jdk.nashorn.internal.objects.annotations.Attribute;
 import jdk.nashorn.internal.objects.annotations.Function;
 import jdk.nashorn.internal.objects.annotations.ScriptClass;
@@ -47,6 +44,7 @@
 import jdk.nashorn.internal.runtime.JSONFunctions;
 import jdk.nashorn.internal.runtime.JSType;
 import jdk.nashorn.internal.runtime.PropertyMap;
+import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
 import jdk.nashorn.internal.runtime.arrays.ArrayLikeIterator;
 import jdk.nashorn.internal.runtime.linker.Bootstrap;
@@ -70,18 +68,6 @@
                 });
     }
 
-    private static final Object JSOBJECT_INVOKER = new Object();
-
-    private static MethodHandle getJSOBJECT_INVOKER() {
-        return Global.instance().getDynamicInvoker(JSOBJECT_INVOKER,
-                new Callable<MethodHandle>() {
-                    @Override
-                    public MethodHandle call() {
-                        return Bootstrap.createDynamicInvoker("dyn:call",
-                            Object.class, Object.class, Object.class);
-                    }
-                });
-    }
 
     private static final Object REPLACER_INVOKER = new Object();
 
@@ -91,7 +77,7 @@
                     @Override
                     public MethodHandle call() {
                         return Bootstrap.createDynamicInvoker("dyn:call", Object.class,
-                            Object.class, Object.class, Object.class, Object.class);
+                            ScriptFunction.class, ScriptObject.class, Object.class, Object.class);
                     }
                 });
     }
@@ -141,10 +127,9 @@
         final StringifyState state = new StringifyState();
 
         // If there is a replacer, it must be a function or an array.
-        if (Bootstrap.isCallable(replacer)) {
-            state.replacerFunction = replacer;
+        if (replacer instanceof ScriptFunction) {
+            state.replacerFunction = (ScriptFunction) replacer;
         } else if (isArray(replacer) ||
-                isJSObjectArray(replacer) ||
                 replacer instanceof Iterable ||
                 (replacer != null && replacer.getClass().isArray())) {
 
@@ -216,19 +201,18 @@
     // stringify helpers.
 
     private static class StringifyState {
-        final Map<Object, Object> stack = new IdentityHashMap<>();
+        final Map<ScriptObject, ScriptObject> stack = new IdentityHashMap<>();
 
         StringBuilder  indent = new StringBuilder();
         String         gap = "";
         List<String>   propertyList = null;
-        Object         replacerFunction = null;
+        ScriptFunction replacerFunction = null;
     }
 
     // Spec: The abstract operation Str(key, holder).
-    private static Object str(final Object key, final Object holder, final StringifyState state) {
-        assert holder instanceof ScriptObject || holder instanceof JSObject;
+    private static Object str(final Object key, final ScriptObject holder, final StringifyState state) {
+        Object value = holder.get(key);
 
-        Object value = getProperty(holder, key);
         try {
             if (value instanceof ScriptObject) {
                 final InvokeByName toJSONInvoker = getTO_JSON();
@@ -237,12 +221,6 @@
                 if (Bootstrap.isCallable(toJSON)) {
                     value = toJSONInvoker.getInvoker().invokeExact(toJSON, svalue, key);
                 }
-            } else if (value instanceof JSObject) {
-                final JSObject jsObj = (JSObject)value;
-                final Object toJSON = jsObj.getMember("toJSON");
-                if (Bootstrap.isCallable(toJSON)) {
-                    value = getJSOBJECT_INVOKER().invokeExact(toJSON, value);
-                }
             }
 
             if (state.replacerFunction != null) {
@@ -284,10 +262,10 @@
 
         final JSType type = JSType.of(value);
         if (type == JSType.OBJECT) {
-            if (isArray(value) || isJSObjectArray(value)) {
-                return JA(value, state);
-            } else if (value instanceof ScriptObject || value instanceof JSObject) {
-                return JO(value, state);
+            if (isArray(value)) {
+                return JA((ScriptObject)value, state);
+            } else if (value instanceof ScriptObject) {
+                return JO((ScriptObject)value, state);
             }
         }
 
@@ -295,9 +273,7 @@
     }
 
     // Spec: The abstract operation JO(value) serializes an object.
-    private static String JO(final Object value, final StringifyState state) {
-        assert value instanceof ScriptObject || value instanceof JSObject;
-
+    private static String JO(final ScriptObject value, final StringifyState state) {
         if (state.stack.containsKey(value)) {
             throw typeError("JSON.stringify.cyclic");
         }
@@ -308,8 +284,7 @@
 
         final StringBuilder finalStr = new StringBuilder();
         final List<Object>  partial  = new ArrayList<>();
-        final List<String>  k        = state.propertyList == null ?
-                Arrays.asList(getOwnKeys(value)) : state.propertyList;
+        final List<String>  k        = state.propertyList == null ? Arrays.asList(value.getOwnKeys(false)) : state.propertyList;
 
         for (final Object p : k) {
             final Object strP = str(p, value, state);
@@ -374,9 +349,7 @@
     }
 
     // Spec: The abstract operation JA(value) serializes an array.
-    private static Object JA(final Object value, final StringifyState state) {
-        assert value instanceof ScriptObject || value instanceof JSObject;
-
+    private static Object JA(final ScriptObject value, final StringifyState state) {
         if (state.stack.containsKey(value)) {
             throw typeError("JSON.stringify.cyclic");
         }
@@ -386,7 +359,7 @@
         state.indent.append(state.gap);
         final List<Object> partial = new ArrayList<>();
 
-        final int length = JSType.toInteger(getLength(value));
+        final int length = JSType.toInteger(value.getLength());
         int index = 0;
 
         while (index < length) {
@@ -440,48 +413,4 @@
 
         return finalStr.toString();
     }
-
-    private static String[] getOwnKeys(final Object obj) {
-        if (obj instanceof ScriptObject) {
-            return ((ScriptObject)obj).getOwnKeys(false);
-        } else if (obj instanceof ScriptObjectMirror) {
-            return ((ScriptObjectMirror)obj).getOwnKeys(false);
-        } else if (obj instanceof JSObject) {
-            // No notion of "own keys" or "proto" for general JSObject! We just
-            // return all keys of the object. This will be useful for POJOs
-            // implementing JSObject interface.
-            return ((JSObject)obj).keySet().toArray(new String[0]);
-        } else {
-            throw new AssertionError("should not reach here");
-        }
-    }
-
-    private static Object getLength(final Object obj) {
-        if (obj instanceof ScriptObject) {
-            return ((ScriptObject)obj).getLength();
-        } else if (obj instanceof JSObject) {
-            return ((JSObject)obj).getMember("length");
-        } else {
-            throw new AssertionError("should not reach here");
-        }
-    }
-
-    private static boolean isJSObjectArray(final Object obj) {
-        return (obj instanceof JSObject) && ((JSObject)obj).isArray();
-    }
-
-    private static Object getProperty(final Object holder, final Object key) {
-        if (holder instanceof ScriptObject) {
-            return ((ScriptObject)holder).get(key);
-        } else if (holder instanceof JSObject) {
-            JSObject jsObj = (JSObject)holder;
-            if (key instanceof Integer) {
-                return jsObj.getSlot((Integer)key);
-            } else {
-                return jsObj.getMember(Objects.toString(key));
-            }
-        } else {
-            return new AssertionError("should not reach here");
-        }
-    }
 }
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java
index 52e87d3..da64372 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeRegExp.java
@@ -46,6 +46,7 @@
 import jdk.nashorn.internal.runtime.JSType;
 import jdk.nashorn.internal.runtime.ParserException;
 import jdk.nashorn.internal.runtime.PropertyMap;
+import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
 import jdk.nashorn.internal.runtime.ScriptRuntime;
 import jdk.nashorn.internal.runtime.linker.Bootstrap;
@@ -655,7 +656,7 @@
      * @param replacement Replacement string.
      * @return String with substitutions.
      */
-    String replace(final String string, final String replacement, final Object function) throws Throwable {
+    String replace(final String string, final String replacement, final ScriptFunction function) throws Throwable {
         final RegExpMatcher matcher = regexp.match(string);
 
         if (matcher == null) {
@@ -671,7 +672,7 @@
             sb.append(string, 0, matcher.start());
 
             if (function != null) {
-                final Object self = Bootstrap.isStrictCallable(function) ? UNDEFINED : Global.instance();
+                final Object self = function.isStrict() ? UNDEFINED : Global.instance();
                 sb.append(callReplaceValue(getReplaceValueInvoker(), function, self, matcher, string));
             } else {
                 appendReplacement(matcher, string, replacement, sb);
@@ -691,7 +692,7 @@
         final StringBuilder sb = new StringBuilder();
 
         final MethodHandle invoker = function == null ? null : getReplaceValueInvoker();
-        final Object self = function == null || Bootstrap.isStrictCallable(function) ? UNDEFINED : Global.instance();
+        final Object self = function == null || function.isStrict() ? UNDEFINED : Global.instance();
 
         do {
             sb.append(string, thisIndex, matcher.start());
@@ -807,13 +808,12 @@
                 new Callable<MethodHandle>() {
                     @Override
                     public MethodHandle call() {
-                        return Bootstrap.createDynamicInvoker("dyn:call",
-                            String.class, Object.class, Object.class, Object[].class);
+                        return Bootstrap.createDynamicInvoker("dyn:call", String.class, ScriptFunction.class, Object.class, Object[].class);
                     }
                 });
     }
 
-    private String callReplaceValue(final MethodHandle invoker, final Object function, final Object self, final RegExpMatcher matcher, final String string) throws Throwable {
+    private String callReplaceValue(final MethodHandle invoker, final ScriptFunction function, final Object self, final RegExpMatcher matcher, final String string) throws Throwable {
         final Object[] groups = groups(matcher);
         final Object[] args   = Arrays.copyOf(groups, groups.length + 2);
 
diff --git a/nashorn/src/jdk/nashorn/internal/objects/NativeString.java b/nashorn/src/jdk/nashorn/internal/objects/NativeString.java
index 304ec99..7e862cb 100644
--- a/nashorn/src/jdk/nashorn/internal/objects/NativeString.java
+++ b/nashorn/src/jdk/nashorn/internal/objects/NativeString.java
@@ -56,13 +56,14 @@
 import jdk.nashorn.internal.runtime.JSType;
 import jdk.nashorn.internal.runtime.OptimisticBuiltins;
 import jdk.nashorn.internal.runtime.PropertyMap;
+import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptObject;
 import jdk.nashorn.internal.runtime.ScriptRuntime;
 import jdk.nashorn.internal.runtime.arrays.ArrayIndex;
-import jdk.nashorn.internal.runtime.linker.Bootstrap;
 import jdk.nashorn.internal.runtime.linker.NashornGuards;
 import jdk.nashorn.internal.runtime.linker.PrimitiveLookup;
 
+
 /**
  * ECMA 15.5 String Objects.
  */
@@ -748,8 +749,8 @@
             nativeRegExp = NativeRegExp.flatRegExp(JSType.toString(string));
         }
 
-        if (Bootstrap.isCallable(replacement)) {
-            return nativeRegExp.replace(str, "", replacement);
+        if (replacement instanceof ScriptFunction) {
+            return nativeRegExp.replace(str, "", (ScriptFunction)replacement);
         }
 
         return nativeRegExp.replace(str, JSType.toString(replacement), null);
diff --git a/nashorn/src/jdk/nashorn/internal/parser/AbstractParser.java b/nashorn/src/jdk/nashorn/internal/parser/AbstractParser.java
index 1c7f410..a7c7fb9 100644
--- a/nashorn/src/jdk/nashorn/internal/parser/AbstractParser.java
+++ b/nashorn/src/jdk/nashorn/internal/parser/AbstractParser.java
@@ -200,10 +200,8 @@
      * @return tokenType of next token.
      */
     private TokenType nextToken() {
-        // Capture last token type, but ignore comments (which are irrelevant for the purpose of newline detection).
-        if (type != COMMENT) {
-            last = type;
-        }
+        // Capture last token tokenType.
+        last = type;
         if (type != EOF) {
 
             // Set up next token.
diff --git a/nashorn/src/jdk/nashorn/internal/parser/Parser.java b/nashorn/src/jdk/nashorn/internal/parser/Parser.java
index 91cd266..cfdd599 100644
--- a/nashorn/src/jdk/nashorn/internal/parser/Parser.java
+++ b/nashorn/src/jdk/nashorn/internal/parser/Parser.java
@@ -459,7 +459,7 @@
 
         final FunctionNode parentFunction = lc.getCurrentFunction();
         if (parentFunction != null && !parentFunction.isProgram()) {
-            sb.append(parentFunction.getName()).append(CompilerConstants.NESTED_FUNCTION_SEPARATOR.symbolName());
+            sb.append(parentFunction.getName()).append('$');
         }
 
         assert ident.getName() != null;
@@ -1135,7 +1135,7 @@
 
     /**
      * ExpressionStatement :
-     *      Expression ; // [lookahead ~({ or  function )]
+     *      Expression ; // [lookahead ~( or  function )]
      *
      * See 12.4
      *
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/Context.java b/nashorn/src/jdk/nashorn/internal/runtime/Context.java
index 47a8233..0d82136 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/Context.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/Context.java
@@ -377,12 +377,10 @@
     final boolean _strict;
 
     /** class loader to resolve classes from script. */
-    private final ClassLoader appLoader;
+    private final ClassLoader  appLoader;
 
-    /*package-private*/
-    ClassLoader getAppLoader() {
-        return appLoader;
-    }
+    /** Class loader to load classes from -classpath option, if set. */
+    private final ClassLoader  classPathLoader;
 
     /** Class loader to load classes compiled from scripts. */
     private final ScriptLoader scriptLoader;
@@ -397,12 +395,11 @@
     private final ClassFilter classFilter;
 
     private static final ClassLoader myLoader = Context.class.getClassLoader();
-    /** Process-wide singleton structure loader */
-    private static final StructureLoader theStructLoader;
+    private static final StructureLoader sharedLoader;
 
     /*package-private*/ @SuppressWarnings("static-method")
-    ClassLoader getStructLoader() {
-        return theStructLoader;
+    ClassLoader getSharedLoader() {
+        return sharedLoader;
     }
 
     private static AccessControlContext createNoPermAccCtxt() {
@@ -420,7 +417,7 @@
     private static final AccessControlContext CREATE_GLOBAL_ACC_CTXT  = createPermAccCtxt(NASHORN_CREATE_GLOBAL);
 
     static {
-        theStructLoader = AccessController.doPrivileged(new PrivilegedAction<StructureLoader>() {
+        sharedLoader = AccessController.doPrivileged(new PrivilegedAction<StructureLoader>() {
             @Override
             public StructureLoader run() {
                 return new StructureLoader(myLoader);
@@ -498,6 +495,7 @@
         this.classFilter = classFilter;
         this.env       = new ScriptEnvironment(options, out, err);
         this._strict   = env._strict;
+        this.appLoader = appLoader;
         if (env._loader_per_compile) {
             this.scriptLoader = null;
             this.uniqueScriptId = null;
@@ -507,17 +505,17 @@
         }
         this.errors    = errors;
 
-        // if user passed -classpath option, make a URLClassLoader with that and
-        // the app loader as the parent.
+        // if user passed -classpath option, make a class loader with that and set it as
+        // thread context class loader so that script can access classes from that path.
         final String classPath = options.getString("classpath");
         if (!env._compile_only && classPath != null && !classPath.isEmpty()) {
             // make sure that caller can create a class loader.
             if (sm != null) {
-                sm.checkCreateClassLoader();
+                sm.checkPermission(new RuntimePermission("createClassLoader"));
             }
-            this.appLoader = NashornLoader.createClassLoader(classPath, appLoader);
+            this.classPathLoader = NashornLoader.createClassLoader(classPath);
         } else {
-            this.appLoader = appLoader;
+            this.classPathLoader = null;
         }
 
         final int cacheSize = env._class_cache_size;
@@ -929,7 +927,7 @@
         if (System.getSecurityManager() != null && !StructureLoader.isStructureClass(fullName)) {
             throw new ClassNotFoundException(fullName);
         }
-        return (Class<? extends ScriptObject>)Class.forName(fullName, true, theStructLoader);
+        return (Class<? extends ScriptObject>)Class.forName(fullName, true, sharedLoader);
     }
 
     /**
@@ -1046,18 +1044,17 @@
             checkPackageAccess(sm, fullName);
         }
 
-        // Try finding using the "app" loader.
-        if (appLoader != null) {
-            return Class.forName(fullName, true, appLoader);
-        } else {
-            final Class<?> cl = Class.forName(fullName);
-            // return the Class only if it was loaded by boot loader
-            if (cl.getClassLoader() == null) {
-                return cl;
-            } else {
-                throw new ClassNotFoundException(fullName);
+        // try the script -classpath loader, if that is set
+        if (classPathLoader != null) {
+            try {
+                return Class.forName(fullName, true, classPathLoader);
+            } catch (final ClassNotFoundException ignored) {
+                // ignore, continue search
             }
         }
+
+        // Try finding using the "app" loader.
+        return Class.forName(fullName, true, appLoader);
     }
 
     /**
@@ -1088,7 +1085,7 @@
             // No verification when security manager is around as verifier
             // may load further classes - which should be avoided.
             if (System.getSecurityManager() == null) {
-                CheckClassAdapter.verify(new ClassReader(bytecode), theStructLoader, false, new PrintWriter(System.err, true));
+                CheckClassAdapter.verify(new ClassReader(bytecode), sharedLoader, false, new PrintWriter(System.err, true));
             }
         }
     }
@@ -1204,10 +1201,15 @@
     }
 
     private URL getResourceURL(final String resName) {
-        if (appLoader != null) {
+        // try the classPathLoader if we have and then
+        // try the appLoader if non-null.
+        if (classPathLoader != null) {
+            return classPathLoader.getResource(resName);
+        } else if (appLoader != null) {
             return appLoader.getResource(resName);
         }
-        return ClassLoader.getSystemResource(resName);
+
+        return null;
     }
 
     private Object evaluateSource(final Source source, final ScriptObject scope, final ScriptObject thiz) {
@@ -1334,7 +1336,7 @@
              new PrivilegedAction<ScriptLoader>() {
                 @Override
                 public ScriptLoader run() {
-                    return new ScriptLoader(Context.this);
+                    return new ScriptLoader(appLoader, Context.this);
                 }
              }, CREATE_LOADER_ACC_CTXT);
     }
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/JSONFunctions.java b/nashorn/src/jdk/nashorn/internal/runtime/JSONFunctions.java
index 3c4d574..d265e6d 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/JSONFunctions.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/JSONFunctions.java
@@ -46,7 +46,7 @@
                     @Override
                     public MethodHandle call() {
                         return Bootstrap.createDynamicInvoker("dyn:call", Object.class,
-                             Object.class, Object.class, String.class, Object.class);
+                            ScriptFunction.class, ScriptObject.class, String.class, Object.class);
                     }
                 });
     }
@@ -90,16 +90,16 @@
 
     // apply 'reviver' function if available
     private static Object applyReviver(final Global global, final Object unfiltered, final Object reviver) {
-        if (Bootstrap.isCallable(reviver)) {
+        if (reviver instanceof ScriptFunction) {
             final ScriptObject root = global.newObject();
             root.addOwnProperty("", Property.WRITABLE_ENUMERABLE_CONFIGURABLE, unfiltered);
-            return walk(root, "", reviver);
+            return walk(root, "", (ScriptFunction)reviver);
         }
         return unfiltered;
     }
 
     // This is the abstract "Walk" operation from the spec.
-    private static Object walk(final ScriptObject holder, final Object name, final Object reviver) {
+    private static Object walk(final ScriptObject holder, final Object name, final ScriptFunction reviver) {
         final Object val = holder.get(name);
         if (val instanceof ScriptObject) {
             final ScriptObject     valueObj = (ScriptObject)val;
@@ -131,7 +131,7 @@
 
         try {
              // Object.class, ScriptFunction.class, ScriptObject.class, String.class, Object.class);
-             return getREVIVER_INVOKER().invokeExact(reviver, (Object)holder, JSType.toString(name), val);
+             return getREVIVER_INVOKER().invokeExact(reviver, holder, JSType.toString(name), val);
         } catch(Error|RuntimeException t) {
             throw t;
         } catch(final Throwable t) {
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/JSType.java b/nashorn/src/jdk/nashorn/internal/runtime/JSType.java
index 89e5cb5..9ca599c 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/JSType.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/JSType.java
@@ -457,8 +457,6 @@
             return toPrimitive((ScriptObject)obj, hint);
         } else if (isPrimitive(obj)) {
             return obj;
-        } else if (hint == Number.class && obj instanceof Number) {
-            return ((Number) obj).doubleValue();
         } else if (obj instanceof JSObject) {
             return toPrimitive((JSObject)obj, hint);
         } else if (obj instanceof StaticClass) {
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/NashornLoader.java b/nashorn/src/jdk/nashorn/internal/runtime/NashornLoader.java
index 237ccaa..423b87d 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/NashornLoader.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/NashornLoader.java
@@ -35,6 +35,7 @@
 import java.security.PermissionCollection;
 import java.security.Permissions;
 import java.security.SecureClassLoader;
+import jdk.nashorn.tools.Shell;
 
 /**
  * Superclass for Nashorn class loader classes.
@@ -102,10 +103,10 @@
     /**
      * Create a secure URL class loader for the given classpath
      * @param classPath classpath for the loader to search from
-     * @param parent the parent class loader for the new class loader
      * @return the class loader
      */
-    static ClassLoader createClassLoader(final String classPath, final ClassLoader parent) {
+    static ClassLoader createClassLoader(final String classPath) {
+        final ClassLoader parent = Shell.class.getClassLoader();
         final URL[] urls = pathToURLs(classPath);
         return URLClassLoader.newInstance(urls, parent);
     }
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptLoader.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptLoader.java
index 2f7401f..3b66c99 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptLoader.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptLoader.java
@@ -44,45 +44,20 @@
     /**
      * Constructor.
      */
-    ScriptLoader(final Context context) {
-        super(context.getStructLoader());
+    ScriptLoader(final ClassLoader parent, final Context context) {
+        super(parent);
         this.context = context;
     }
 
     @Override
     protected Class<?> loadClass(final String name, final boolean resolve) throws ClassNotFoundException {
         checkPackageAccess(name);
+        if (name.startsWith(NASHORN_PKG_PREFIX)) {
+            return context.getSharedLoader().loadClass(name);
+        }
         return super.loadClass(name, resolve);
     }
 
-
-     @Override
-     protected Class<?> findClass(String name) throws ClassNotFoundException {
-         final ClassLoader appLoader = context.getAppLoader();
-
-         /*
-          * If the appLoader is null, don't bother side-delegating to it!
-          * Bootloader has been already attempted via parent loader
-          * delegation from the "loadClass" method.
-          *
-          * Also, make sure that we don't delegate to the app loader
-          * for nashorn's own classes or nashorn generated classes!
-          */
-         if (appLoader == null || name.startsWith(NASHORN_PKG_PREFIX)) {
-             throw new ClassNotFoundException(name);
-         }
-
-         /*
-          * This split-delegation is used so that caller loader
-          * based resolutions of classes would work. For example,
-          * java.sql.DriverManager uses caller's class loader to
-          * get Driver instances. Without this split-delegation
-          * a script class evaluating DriverManager.getDrivers()
-          * will not get back any JDBC driver!
-          */
-         return appLoader.loadClass(name);
-     }
-
     // package-private and private stuff below this point
 
     /**
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/ScriptingFunctions.java b/nashorn/src/jdk/nashorn/internal/runtime/ScriptingFunctions.java
index 5f849ea..d06c06f 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/ScriptingFunctions.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/ScriptingFunctions.java
@@ -132,9 +132,9 @@
      * Nashorn extension: exec a string in a separate process.
      *
      * @param self   self reference
-     * @param args   string to execute, input and additional arguments, to be appended to {@code string}. Additional
-     *               arguments can be passed as either one JavaScript array, whose elements will be converted to
-     *               strings; or as a sequence of varargs, each of which will be converted to a string.
+     * @param args   string to execute, input and additional arguments, to be appended to {@code string}. Additional arguments can be passed as
+     *               either one JavaScript array, whose elements will be converted to strings; or as a sequence of
+     *               varargs, each of which will be converted to a string.
      *
      * @return output string from the request
      *
@@ -167,10 +167,7 @@
             // If a working directory is present, use it.
             final Object pwd = envProperties.get(PWD_NAME);
             if (pwd != UNDEFINED) {
-                final File pwdFile = new File(JSType.toString(pwd));
-                if (pwdFile.exists()) {
-                    processBuilder.directory(pwdFile);
-                }
+                processBuilder.directory(new File(JSType.toString(pwd)));
             }
 
             // Set up ENV variables.
@@ -222,13 +219,13 @@
         errThread.start();
 
         // If input is present, pass on to process.
-        if (!JSType.nullOrUndefined(input)) {
-            try (OutputStreamWriter outputStream = new OutputStreamWriter(process.getOutputStream())) {
+        try (OutputStreamWriter outputStream = new OutputStreamWriter(process.getOutputStream())) {
+            if (input != UNDEFINED) {
                 final String in = JSType.toString(input);
                 outputStream.write(in, 0, in.length());
-            } catch (final IOException ex) {
-                // Process was not expecting input.  May be normal state of affairs.
             }
+        } catch (final IOException ex) {
+            // Process was not expecting input.  May be normal state of affairs.
         }
 
         // Wait for the process to complete.
@@ -278,8 +275,9 @@
      * @param str a {@link String} to tokenize.
      * @return a {@link List} of {@link String}s representing the tokens that
      * constitute the string.
+     * @throws IOException in case {@link StreamTokenizer#nextToken()} raises it.
      */
-    public static List<String> tokenizeString(final String str) {
+    public static List<String> tokenizeString(final String str) throws IOException {
         final StreamTokenizer tokenizer = new StreamTokenizer(new StringReader(str));
         tokenizer.resetSyntax();
         tokenizer.wordChars(0, 255);
@@ -289,7 +287,7 @@
         tokenizer.quoteChar('\'');
         final List<String> tokenList = new ArrayList<>();
         final StringBuilder toAppend = new StringBuilder();
-        while (nextToken(tokenizer) != StreamTokenizer.TT_EOF) {
+        while (tokenizer.nextToken() != StreamTokenizer.TT_EOF) {
             final String s = tokenizer.sval;
             // The tokenizer understands about honoring quoted strings and recognizes
             // them as one token that possibly contains multiple space-separated words.
@@ -308,12 +306,4 @@
         }
         return tokenList;
     }
-
-    private static int nextToken(final StreamTokenizer tokenizer) {
-        try {
-            return tokenizer.nextToken();
-        } catch (final IOException ioe) {
-            return StreamTokenizer.TT_EOF;
-        }
-    }
 }
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java
index d2447be..ca3fc76 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/Bootstrap.java
@@ -159,9 +159,7 @@
             return ((JSObject)callable).isStrictFunction();
         } else if (callable instanceof BoundCallable) {
             return isStrictCallable(((BoundCallable)callable).getCallable());
-        } else if (BeansLinker.isDynamicMethod(callable) ||
-                callable instanceof StaticClass ||
-                isFunctionalInterfaceObject(callable)) {
+        } else if (BeansLinker.isDynamicMethod(callable) || callable instanceof StaticClass) {
             return false;
         }
         throw notFunction(callable);
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/JSObjectLinker.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/JSObjectLinker.java
index e8e493b..8fd28cc 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/JSObjectLinker.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/JSObjectLinker.java
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2010, 2016, Oracle and/or its affiliates. All rights reserved.
+ * Copyright (c) 2010, 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
@@ -29,7 +29,6 @@
 
 import java.lang.invoke.MethodHandle;
 import java.lang.invoke.MethodHandles;
-import java.lang.invoke.MethodType;
 import java.util.Map;
 import javax.script.Bindings;
 import jdk.internal.dynalink.CallSiteDescriptor;
@@ -141,15 +140,12 @@
     }
 
     private static GuardedInvocation findCallMethod(final CallSiteDescriptor desc) {
+        // TODO: if call site is already a vararg, don't do asCollector
         MethodHandle mh = JSOBJECT_CALL;
         if (NashornCallSiteDescriptor.isApplyToCall(desc)) {
             mh = MH.insertArguments(JSOBJECT_CALL_TO_APPLY, 0, JSOBJECT_CALL);
         }
-        final MethodType type = desc.getMethodType();
-        mh = type.parameterType(type.parameterCount() - 1) == Object[].class ?
-                mh :
-                MH.asCollector(mh, Object[].class, type.parameterCount() - 2);
-        return new GuardedInvocation(mh, IS_JSOBJECT_GUARD);
+        return new GuardedInvocation(MH.asCollector(mh, Object[].class, desc.getMethodType().parameterCount() - 2), IS_JSOBJECT_GUARD);
     }
 
     private static GuardedInvocation findNewMethod(final CallSiteDescriptor desc) {
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornBeansLinker.java b/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornBeansLinker.java
index d6d4f61..6b7bce3 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornBeansLinker.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/linker/NashornBeansLinker.java
@@ -177,7 +177,7 @@
             if (iface.isAnnotationPresent(FunctionalInterface.class)) {
                 // return the first abstract method
                 for (final Method m : iface.getMethods()) {
-                    if (Modifier.isAbstract(m.getModifiers()) && !isOverridableObjectMethod(m)) {
+                    if (Modifier.isAbstract(m.getModifiers())) {
                         return m.getName();
                     }
                 }
@@ -188,23 +188,6 @@
         return findFunctionalInterfaceMethodName(clazz.getSuperclass());
     }
 
-    // is this an overridable java.lang.Object method?
-    private static boolean isOverridableObjectMethod(final Method m) {
-        switch (m.getName()) {
-            case "equals":
-                if (m.getReturnType() == boolean.class) {
-                    final Class<?>[] params = m.getParameterTypes();
-                    return params.length == 1 && params[0] == Object.class;
-                }
-                return false;
-            case "hashCode":
-                return m.getReturnType() == int.class && m.getParameterCount() == 0;
-            case "toString":
-                return m.getReturnType() == String.class && m.getParameterCount() == 0;
-        }
-        return false;
-    }
-
     // Returns @FunctionalInterface annotated interface's single abstract
     // method name. If not found, returns null.
     static String getFunctionalInterfaceMethodName(final Class<?> clazz) {
diff --git a/nashorn/src/jdk/nashorn/internal/runtime/regexp/RegExpScanner.java b/nashorn/src/jdk/nashorn/internal/runtime/regexp/RegExpScanner.java
index d194e2d..88b023a 100644
--- a/nashorn/src/jdk/nashorn/internal/runtime/regexp/RegExpScanner.java
+++ b/nashorn/src/jdk/nashorn/internal/runtime/regexp/RegExpScanner.java
@@ -80,17 +80,8 @@
             this.negLookaheadLevel = negLookaheadLevel;
         }
 
-        /**
-         * Returns true if this Capture can be referenced from the position specified by the
-         * group and level parameters. This is the case if either the group is not within
-         * a negative lookahead, or the position of the referrer is in the same negative lookahead.
-         *
-         * @param group current negative lookahead group
-         * @param level current negative lokahead level
-         * @return true if this capture group can be referenced from the given position
-         */
-        boolean canBeReferencedFrom(final int group, final int level) {
-            return this.negLookaheadLevel == 0 || (group == this.negLookaheadGroup && level >= this.negLookaheadLevel);
+        boolean isContained(final int group, final int level) {
+            return group == this.negLookaheadGroup && level >= this.negLookaheadLevel;
         }
 
     }
@@ -680,9 +671,8 @@
 
                 } else if (decimalValue <= caps.size()) {
                     //  Captures inside a negative lookahead are undefined when referenced from the outside.
-                    final Capture capture = caps.get(decimalValue - 1);
-                    if (!capture.canBeReferencedFrom(negLookaheadGroup, negLookaheadLevel)) {
-                        // Outside reference to capture in negative lookahead, omit from output buffer.
+                    if (!caps.get(decimalValue - 1).isContained(negLookaheadGroup, negLookaheadLevel)) {
+                        // Reference to capture in negative lookahead, omit from output buffer.
                         sb.setLength(sb.length() - 1);
                     } else {
                         // Append backreference to output buffer.
diff --git a/nashorn/src/jdk/nashorn/tools/Shell.java b/nashorn/src/jdk/nashorn/tools/Shell.java
index 2dcf190..9ee02af 100644
--- a/nashorn/src/jdk/nashorn/tools/Shell.java
+++ b/nashorn/src/jdk/nashorn/tools/Shell.java
@@ -25,6 +25,20 @@
 
 package jdk.nashorn.tools;
 
+import static jdk.nashorn.internal.runtime.Source.sourceFor;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.io.OutputStream;
+import java.io.PrintStream;
+import java.io.PrintWriter;
+import java.util.List;
+import java.util.Locale;
+import java.util.ResourceBundle;
 import jdk.nashorn.api.scripting.NashornException;
 import jdk.nashorn.internal.codegen.Compiler;
 import jdk.nashorn.internal.codegen.Compiler.CompilationPhases;
@@ -40,30 +54,8 @@
 import jdk.nashorn.internal.runtime.ScriptEnvironment;
 import jdk.nashorn.internal.runtime.ScriptFunction;
 import jdk.nashorn.internal.runtime.ScriptRuntime;
-import jdk.nashorn.internal.runtime.ScriptingFunctions;
 import jdk.nashorn.internal.runtime.options.Options;
 
-import java.io.BufferedReader;
-import java.io.File;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.OutputStream;
-import java.io.PrintStream;
-import java.io.PrintWriter;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collections;
-import java.util.List;
-import java.util.Locale;
-import java.util.ResourceBundle;
-
-import static jdk.nashorn.internal.runtime.Source.sourceFor;
-
 /**
  * Command line Shell for processing JavaScript files.
  */
@@ -203,8 +195,7 @@
         // parse options
         if (args != null) {
             try {
-                final String[] prepArgs = preprocessArgs(args);
-                options.process(prepArgs);
+                options.process(args);
             } catch (final IllegalArgumentException e) {
                 werr.println(bundle.getString("shell.usage"));
                 options.displayHelp(e);
@@ -235,75 +226,6 @@
     }
 
     /**
-     * Preprocess the command line arguments passed in by the shell. This method checks, for the first non-option
-     * argument, whether the file denoted by it begins with a shebang line. If so, it is assumed that execution in
-     * shebang mode is intended. The consequence of this is that the identified script file will be treated as the
-     * <em>only</em> script file, and all subsequent arguments will be regarded as arguments to the script.
-     * <p>
-     * This method canonicalizes the command line arguments to the form {@code <options> <script> -- <arguments>} if a
-     * shebang script is identified. On platforms that pass shebang arguments as single strings, the shebang arguments
-     * will be broken down into single arguments; whitespace is used as separator.
-     * <p>
-     * Shebang mode is entered regardless of whether the script is actually run directly from the shell, or indirectly
-     * via the {@code jjs} executable. It is the user's / script author's responsibility to ensure that the arguments
-     * given on the shebang line do not lead to a malformed argument sequence. In particular, the shebang arguments
-     * should not contain any whitespace for purposes other than separating arguments, as the different platforms deal
-     * with whitespace in different and incompatible ways.
-     * <p>
-     * @implNote Example:<ul>
-     * <li>Shebang line in {@code script.js}: {@code #!/path/to/jjs --language=es6}</li>
-     * <li>Command line: {@code ./script.js arg2}</li>
-     * <li>{@code args} array passed to Nashorn: {@code --language=es6,./script.js,arg}</li>
-     * <li>Required canonicalized arguments array: {@code --language=es6,./script.js,--,arg2}</li>
-     * </ul>
-     *
-     * @param args the command line arguments as passed into Nashorn.
-     * @return the passed and possibly canonicalized argument list
-     */
-    private static String[] preprocessArgs(final String[] args) {
-        if (args.length == 0) {
-            return args;
-        }
-
-        final List<String> processedArgs = new ArrayList<>();
-        processedArgs.addAll(Arrays.asList(args));
-
-        // Nashorn supports passing multiple shebang arguments. On platforms that pass anything following the
-        // shebang interpreter notice as one argument, the first element of the argument array needs to be special-cased
-        // as it might actually contain several arguments. Mac OS X splits shebang arguments, other platforms don't.
-        // This special handling is also only necessary if the first argument actually starts with an option.
-        if (args[0].startsWith("-") && !System.getProperty("os.name", "generic").startsWith("Mac OS X")) {
-            processedArgs.addAll(0, ScriptingFunctions.tokenizeString(processedArgs.remove(0)));
-        }
-
-        int shebangFilePos = -1; // -1 signifies "none found"
-        // identify a shebang file and its position in the arguments array (if any)
-        for (int i = 0; i < processedArgs.size(); ++i) {
-            final String a = processedArgs.get(i);
-            if (!a.startsWith("-")) {
-                final Path p = Paths.get(a);
-                String l = "";
-                try (final BufferedReader r = Files.newBufferedReader(p)) {
-                    l = r.readLine();
-                } catch (IOException ioe) {
-                    // ignore
-                }
-                if (l.startsWith("#!")) {
-                    shebangFilePos = i;
-                }
-                // We're only checking the first non-option argument. If it's not a shebang file, we're in normal
-                // execution mode.
-                break;
-            }
-        }
-        if (shebangFilePos != -1) {
-            // Insert the argument separator after the shebang script file.
-            processedArgs.add(shebangFilePos + 1, "--");
-        }
-        return processedArgs.toArray(new String[0]);
-    }
-
-    /**
      * Compiles the given script files in the command line
      * This is called only when using the --compile-only flag
      *
diff --git a/nashorn/test/script/basic/JDK-8025515.js b/nashorn/test/script/basic/JDK-8025515.js
index 6538f54..b88897b 100644
--- a/nashorn/test/script/basic/JDK-8025515.js
+++ b/nashorn/test/script/basic/JDK-8025515.js
@@ -61,8 +61,8 @@
 var f = (function() {
     return function() { a.b.c; };
 })();
-testMethodName(f, "f#L:62");
+testMethodName(f, "f$L:62");
 
 testMethodName((function() {
     return function() { return a.b.c; };
-})(), "L:66#L:67");
+})(), "L:66$L:67");
diff --git a/nashorn/test/script/trusted/JDK-8087292.js b/nashorn/test/script/trusted/JDK-8087292.js
index 57223d3..2973eb3 100644
--- a/nashorn/test/script/trusted/JDK-8087292.js
+++ b/nashorn/test/script/trusted/JDK-8087292.js
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2015, 2016, Oracle and/or its affiliates. All rights reserved.
+ * 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
@@ -29,58 +29,26 @@
  * @run
  */
 
-load(__DIR__ + "JDK-util.js")
-
-var jHomePath = System.getenv("JAVA_HOME")
-var jLauncher = "${jHomePath}/bin/java"
-var altjLauncher = which('java')
-
-if (windows) {
-    if(winCyg) {
-        jLauncher = "${jHomePath}" + "/bin/java.exe"
-        jLauncher = cygpath(jLauncher,outPath.windows) 
-    }
-    else {
-        jLauncher = "${jHomePath}" + "\\bin\\java.exe"
-        altjLauncher = which('java.exe')
-        altjLauncher = cygpath(altjLauncher,outPath.windows)
-    }
-}
-
-function exists(f) {
-    return Files.exists(Paths.get(f))
-}
-
-var javaLauncher = exists(jLauncher) ? jLauncher : altjLauncher
-
-
-if (!exists(javaLauncher)) {
-    throw "no java launcher found; tried ${jLauncher} and ${altjLauncher}"
-}
-
 function tryExec() {
     try {
-	$EXEC("${javaLauncher}")
+        `java`
     } catch (e) {
-      print(e)
+        print(e);
     }
 
     // make sure we got non-zero ("failure") exit code!
     if ($EXIT == 0) {
-        print("Error: expected $EXIT code to be non-zero")
+        print("Error: expected $EXIT code to be non-zero");
     }
 }
-//convert windows paths to cygwin
-if (windows)
-    javaLauncher = (winCyg) ? cygpath(javaLauncher,outPath.mixed).trim() : cygpath(javaLauncher,outPath.windows).trim()
 
 // no exception now!
-tryExec()
+tryExec();
 
 // turn on error with non-zero exit code
-$EXEC.throwOnError = true
-tryExec()
+$EXEC.throwOnError = true;
+tryExec();
 
 // no exception after this
-$EXEC.throwOnError = false
-tryExec()
+$EXEC.throwOnError = false;
+tryExec();
diff --git a/nashorn/test/src/jdk/nashorn/api/scripting/test/ScopeTest.java b/nashorn/test/src/jdk/nashorn/api/scripting/test/ScopeTest.java
index a4c1f94..05b614a 100644
--- a/nashorn/test/src/jdk/nashorn/api/scripting/test/ScopeTest.java
+++ b/nashorn/test/src/jdk/nashorn/api/scripting/test/ScopeTest.java
@@ -30,8 +30,6 @@
 import static org.testng.Assert.assertTrue;
 import static org.testng.Assert.fail;
 import javax.script.Bindings;
-import javax.script.Compilable;
-import javax.script.CompiledScript;
 import javax.script.Invocable;
 import javax.script.ScriptContext;
 import javax.script.ScriptEngine;
@@ -913,27 +911,4 @@
          Object value = ((Invocable)engine).invokeFunction("newfunc");
          assertTrue(((Number)value).intValue() == 42);
     }
-
-    // @bug 8150219 ReferenceError in 1.8.0_72
-    // When we create a Global for a non-default ScriptContext that needs one keep the
-    // ScriptContext associated with the Global so that invoke methods work as expected.
-    @Test
-    public void invokeFunctionWithCustomScriptContextTest() throws Exception {
-        final ScriptEngine engine = new ScriptEngineManager().getEngineByName("nashorn");
-
-        // create an engine and a ScriptContext, but don't set it as default
-        ScriptContext scriptContext = new SimpleScriptContext();
-
-        // Set some value in the context
-        scriptContext.setAttribute("myString", "foo", ScriptContext.ENGINE_SCOPE);
-
-        // Evaluate script with custom context and get back a function
-        final String script = "function (c) { return myString.indexOf(c); }";
-        CompiledScript compiledScript = ((Compilable)engine).compile(script);
-        Object func = compiledScript.eval(scriptContext);
-
-        // Invoked function should be able to see context it was evaluated with
-        Object result = ((Invocable) engine).invokeMethod(func, "call", func, "o", null);
-        assertTrue(((Number)result).intValue() == 1);
-    }
 }